Tuesday, December 1, 2009

ViewState and Dynamic Control

ViewState and Dynamic Control



I thought I understand ViewState, until I came cross this exception:

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.



This is a question asked by someone on a .NET mailing list. My first guess of what causing the problem is that on a page postback, when LoadViewState() is invoked to restore the saved ViewState values to the page and its controls (both Control tree and ViewState tree have been created at this stage), somehow, the ViewState tree doesn't match the control tree. So when ASP.NET tries to restore a ViewState value to a control, no control or a wrong control is found and then the exception occurs.

Note: the ViewState tree (type of Triplet or Pair) is NOT the ViewState property (type of StateBag) of the page or any of its controls. You can think it as an object representation of the ViewState value on the html page (the __VIEWSTATE hidden field), which contains all the values need to be written back to the controls during a page postback. If you don't change the default behavior, during the page initialize/load phrase, the ViewState tree will be created by de-serializing the value __VIEWSTATE field by LoadPageStateFromPersistenceMedium(), and the values on the ViewState tree will be put into the controls ViewState bag in LoadViewState() . During the page save/render phrase, the ViewState tree will be created again by SaveViewState (), then serialized and written onto html page by SavePageStateToPersistenceMedium ()

So, I thought I could reproduce same exception with something simple like this:

Defualt.aspx







Default.aspx.cs

public partial class _Default : Page

{

protected override void OnInit(EventArgs e)

{

base.OnInit(e);

if (!IsPostBack)

{

Button btnClickMe = new Button();

form1.Controls.Add(btnClickMe);

}

}

}

It is indeed a very simple page with a button named btnPostback created statically on .aspx file, and another button named btnClickMe created dynamically in Page.OnInit(), and I will not recreate the btnClickMe for postbacks. So on a page postback, by the time OnInit() and LoadPageStateFromPersistenceMedium() is executed, the control tree and ViewState tree would have different structure, the ViewState tree will have value for btnClickMe, but the control tree will not have the control btnClickMe. I thought it would be good enough to cause the exception, but soon I was proved wrong, there was no exception thrown.

To find out why, let's have a look of the actual ViewState value generated on the html page

“/wEPDwUKMTQ2OTkzNDMyMWRkOWxNFeQcY9jzeKVCluHBdzA6WBo=”

With a little help from ViewState Decoder I got this:







1469934321







There is no view state data for the neither of the buttons! I did expect something like for a control has empty state though.

So, I think here is the first thing I learned:

For a control on the Control tree, there may not be a corresponding item on the ViewState tree (if there is no state for this control need to be saved). If there is nothing found on ViewState tree for a control, the control’s LoadViewState() will not be invoked.

So, let's do something to make the button "dirty" and its ViewState saved.

public partial class _Default : Page

{

protected override void OnInit(EventArgs e)

{

base.OnInit(e);

if (!IsPostBack)

{

Button btnClickMe = new Button();

form1.Controls.Add(btnClickMe);

btnClickMe.Text = "Click me";

}

}

}



The ViewState now became:



/wEPDwUKMTQ2OT

in reference to:

"ViewState and Dynamic Control"
- ViewState and Dynamic Control (view on Google Sidewiki)

Monday, November 16, 2009

compress your http response

 add this code on global.ascx PreRequestHandlerExecute events


<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>

Thursday, November 5, 2009

useing web service without webrefrence

Imports System.CodeDom


Imports System.CodeDom.Compiler

Imports System.Security.Permissions

Imports System.Web.Services.Description

Imports System.Reflection





Public Function CallWebService(ByVal webServiceAsmxUrl As String, _

ByVal serviceName As String, ByVal methodName As String, _

ByVal args() As Object) As Object



Try

Dim client As System.Net.WebClient = New System.Net.WebClient()



'-Connect To the web service

Dim stream As System.IO.Stream = _

client.OpenRead(webServiceAsmxUrl + "?wsdl")



'Read the WSDL file describing a service.

Dim description As ServiceDescription = ServiceDescription.Read(stream)



'LOAD THE DOM'''''''''''''''''''''''''''



'--Initialize a service description importer.

Dim importer As ServiceDescriptionImporter = New ServiceDescriptionImporter()

importer.ProtocolName = "Soap12" ' Use SOAP 1.2.

importer.AddServiceDescription(description, Nothing, Nothing)



'--Generate a proxy client.



importer.Style = ServiceDescriptionImportStyle.Client

'--Generate properties to represent primitive values.

importer.CodeGenerationOptions = _

System.Xml.Serialization.CodeGenerationOptions.GenerateProperties



'Initialize a Code-DOM tree into which we will import the service.

Dim nmspace As CodeNamespace = New CodeNamespace()

Dim unit1 As CodeCompileUnit = New CodeCompileUnit()

unit1.Namespaces.Add(nmspace)



'Import the service into the Code-DOM tree.

'This creates proxy code that uses the service.



Dim warning As ServiceDescriptionImportWarnings = _

importer.Import(nmspace, unit1)



If warning = 0 Then



'--Generate the proxy code

Dim provider1 As CodeDomProvider = _

CodeDomProvider.CreateProvider("VB")

'--Compile the assembly proxy with the // appropriate references

Dim assemblyReferences() As String

assemblyReferences = New String() {"System.dll", _

"System.Web.Services.dll", "System.Web.dll", _

"System.Xml.dll", "System.Data.dll"}

Dim parms As CompilerParameters = New CompilerParameters(assemblyReferences)

parms.GenerateInMemory = True '(Thanks for this line nikolas)

Dim results As CompilerResults = provider1.CompileAssemblyFromDom(parms, unit1)



'-Check For Errors

If results.Errors.Count > 0 Then



Dim oops As CompilerError

For Each oops In results.Errors

System.Diagnostics.Debug.WriteLine("========Compiler error============")

System.Diagnostics.Debug.WriteLine(oops.ErrorText)

Next

Throw New System.Exception("Compile Error Occured calling webservice.")

End If



'--Finally, Invoke the web service method

Dim wsvcClass As Object = results.CompiledAssembly.CreateInstance(serviceName)

Dim mi As MethodInfo = wsvcClass.GetType().GetMethod(methodName)

Return mi.Invoke(wsvcClass, args)



Else

Return Nothing

End If



Catch ex As Exception

Throw ex

End Try

End Function

Calling

Call this web service in a Webform or wndows form or method etc... as below:

Collapse

Dim WebserviceUrl As String = "http://www.abc.com/lgl/test/webservice/v1_00/security.asmx"



'specify service name

Dim serviceName As String = "SecurityAndSessionManagement"



'specify method name to be called

Dim methodName As String = "Session_Start"



'Paraments passed to the method

Dim arArguments(1) As String

arArguments(0) = "abc"

arArguments(1) = "xxxx"



Dim objCallWS As New DynamicWebService

sSessionID = objCallWS.CallWebService(WebserviceUrl, serviceName, _

methodName, arArguments)

MsgBox("new SessionID: " & sSessionID)

Friday, October 30, 2009

Posting form data from <a href="http://ASP.NET">ASP.NET</a> page to another URL

Introduction.

Sometime you need to post a form to an different url from asp.net pages, for example you might need to send user to third party payment processing system using post method, asp.net does not provide any straight forward way to accomplish this task.

Problem which most users faces with server side form in aspx page are, you are not allowed to change action of form and you are allowed to use only one server side form per page.

Possible Solutions.

1. One possible solution to this problem is to Create your own form control and use it on page this will allow you to change action of form, but again what if you do not want some existing input elements in current page to go to post.

2. There is good way to post form data using HttpWebResponse & HttpWebRequest class if you want to post data behind the scenes, but if you want to post data using user browser then you are stuck.

Our Solution.

I will try to show you one possible way to accomplish this task, we will create 1)component that will create form with required fields and post the form to specified url, 2) web page that will use that component to post data and 3) page which will receive that data and display posted data.
















A) RemotePost Class.

Public Class RemotePost
Private Inputs As System.Collections.Specialized.NameValueCollection = New System.Collections.Specialized.NameValueCollection

Public Url As String = ""
Public Method As String = "post"
Public FormName As String = "form1"
Public Sub Add(ByVal name As String, ByVal value As String)
Inputs.Add(name, value)
End Sub
Public Sub Post()
System.Web.HttpContext.Current.Response.Clear()System.Web.HttpContext.Current.Response.Write("")System.Web.HttpContext.Current.Response.Write(String.Format("", FormName))System.Web.HttpContext.Current.Response.Write(String.Format("", FormName, Method, Url))
Dim i As Integer = 0
Do While i < Inputs.Keys.Count
System.Web.HttpContext.Current.Response.Write(String.Format("", Inputs.Keys(i), Inputs(Inputs.Keys(i))))
i += 1
Loop
System.Web.HttpContext.Current.Response.Write("")System.Web.HttpContext.Current.Response.Write("")System.Web.HttpContext.Current.Response.End()
End Sub
End Class

Properties of our component.

1. "Url" which is action of our form.
2. "Method" which is Method of our form, default is Post but you can also use Get.
3. "FormName" which is name of form.

Methods of our component.

1. "Add" which will be used to add form input name and value. and

2. "Post" which will render html on page to do actual posting, most important part of this method is onload event of rendered html's body which will post form to specified URL.

3. Private field Inputs which will hold name value pair collection of all inputs that goes into form.

4. You can compile this class to dll and use in your project but for simplicity I am including that class directly into page itself.

B) Sample Page.

Following is sample page code which posts form to specified url.

Dim myremotepost As RemotePost = New RemotePost
myremotepost.Url = htttp://www.jigar.net/demo/HttpRequestDemoServer.aspx"myremotepost.Add("field1", "Huckleberry")
myremotepost.Add("field2", "Finn")
myremotepost.Post()

C) Receiving Page.

Following is sample page code which posts form to specified url.

This is the page where posting will occur for simplicity we will just write posed value so that we can know what was posted.

If Not Request.Form("field1") Is Nothing Then
Response.Write("field1 : " & Request.Form("field1") & "")
End If
If Not Request.Form("field2") Is Nothing Then
Response.Write("field2 : " & Request.Form("field2") & "")
End If

Run Sample

Click "http://www.jigar.net/demo/RemotePost.aspx" target="new">here to run sample

There will be cases where you will need to tweak the code to suit your requirement. you will also need to check scenario where user uses back button of browser(from posted p
in reference to:
"Posting form data from ASP.NET page to another URL"
- Posting form data from ASP.NET page to another URL (view on Google Sidewiki)

Monday, October 5, 2009

Install CSS Viewer For Firefox 3.5.X

Install CSS Viewer For Firefox 3.5.X
CSSViewer is a very handy add on for Firefox, which shows the css parameters of any element in a website. If you use it once then you cannot live without it.

The bad news are that it is not compatible with the Firefox 3.5.* version, and from what I can understand there are no plans for an update.

The good news are that there is a really easy way to install it and make it work perfect in Firefox 3.5.*

1. Copy the following address to another browser than Firefox (so that the pop up installation window will not come out)

https://addons.mozilla.org/en-US/firefox/addon/2104

if you do not have any other browser installed go to

https://addons.mozilla.org/en-US/firefox/addons/versions/2104

2. Download the file cssviewer-1.0.3-fx.xpi

3. Use 7-zip (or any other extractor) to open it and extract it

4. Open install.rdf with notepad (I used Notepad++ to find easily the line I must change)

5. On line 18 you see 3.0.* you must change it to 3.5.*

6. Save the file and select all the files you extracted and make a zip file

7. Now you must rename the zip file including the zip extension to cssviewer-1.0.3-fx.xpi (it will prompt you if you are sure you want to change the file name extension and you must click yes)

8. Now drag n’ drop the xpi file to Firefox 3.5.* and the installation window will pop up. Install it normally ;)

I have checked it and it works great in Firefox 3.5.1

Sunday, October 4, 2009

Best Web Developer tools for Firefox and Internet Explorer

Best Web Developer tools for Firefox and Internet Explorer
May 4th, 2008 | Save to del.icio.us now(84)
Here are 11 web developer tools & add-ons that i personally use and find them very useful. These are the tools that i need whenever i am doing any web application development, In their absence i feel i have become a handless person.
This list is in priority order of my usage or in other words, their importance to my work.
1. Firebug
2. Measure It
3. ColorZilla
4. Web developer Tool bar
5. Del.icio.us Bookmarks
6. YSlow
7. Screengrab & FireShot
8. IE Developer Tool bar
9. Delicious Button for Internet Explorer
10. DebugBar
11. Nikhil’s Web development Helper


Add-ons That I use on Firefox

All these extensions complement each other really good. check out this screenshot to see their exact location.
1. Firebug
If I have to choose between all these plugins I will choose firebug. It is a very versatile tool, which provides ability to see html source code in a formated manner. You can see style sheet applied to each and every element in the webpage and you can see all the ajax request headers. You can actually edit the css to see them affecting the website in real time. this is swiss army knife of web development world. Download the firebug.

2. Measure It
A very handy and simple tool, Measure It allows you to measure the width and height of any area in the webpage. You don’t have to any image editors any more to get the width and height of that block. Download Measure It.
3. ColorZilla
This is a very cool color picker tool that is available for Firefox. If you want to know the color of any thing opened in the web browser, yes even images, then this is the tool for you.

You can see all the options that are available. Download ColorZilla.

4. Web Developer Toolbar
This is another very useful tool, You can use this to disabling js, css images etc to simulate different conditions. You can read and delete cookies, clear caches, enable or disable form elements and lot of other things easily. Get the Web Developer Toolbar.

5. Delicious Bookmarks

Well, In general if you see, it does not contribute to web application development directly, but it’s ability to share my bookmarks across different machines that i use, It becomes very valuable. After all those book marks are all the references collected from the web that are related to my web development activities. Get Delicious Bokmarks.
6. YSlow
A plugin from yahoo, this one helps me analyze the speed of my website as per yahoo’s recommendations for optimizing and speeding up the website for my users. Get YSlow.

7. Screengrab And/Or FireShot

I was using screen grab for capturing screenshot’s of webpages that i liked, and sometimes, to show my colleagues what’s wrong with their layout. Get ScreenGrab.Since i have found out about FireShot, i am using it exclusively for this purpose.

FireShot provides the features to added notes without opening any image editor, this is the feature that made me fall in love with it. Get FireShot now.

Extensions That I use on Internet Explorer
Even though lot of people have to use Internet Explorer for development. Very small percentage of them know about the tools available for Internet Explorer. Lack of these tools had forced me to switch to Firefox(otherwise i would have never known about beauties of firefox.), but now that i know about these tools i use them every time i have to fix an issue in IE. It has made my life very easier.

1. IE Developer Toolbar
This is a combination of firebug+web developer toolbar+colorzilla and measure it, but for Internet Explorer. Though It does not provides all the features of firebug, still something is better then nothing. I liked the way you can add ruler with this plugin. Get IE Developer Toolbar now.
Designers on Design
2. Del.icio.us Buttons for Internet Explorer

Well I need easy access to Delicious on every browser. Download it from Delicious website.
3. DebugBar
Premium Designer Hard Crystal Snap-on Case for Apple iPod Touch 2, Touch 3, 3rd Generation 8GB, 32GB, 64GB - Cool Black Rainbow Peace Print
I use it because it provides ability to grab screen shot’s of the website and color picker in a easy access way via toolbar on top. Get the DebugBar.
4. Nikhil’s Web Development Helper
It provides ability to capture all the http request, ability for javascript debugging.
HOT Geneva Black Ceramic Silicone Fashion Watch with Crystal Accents ~ As Seen on The Blind Side Movie
Get Nikhil’s web development helper.
Well these are all the tools that help me in my web development activity. Am I missing some tools? please help me find them.

Tuesday, September 22, 2009

Scrap the Mac, Leave the OS

This is the true story of a man’s journey beyond the hardware and into the OS….. Join me on a fantastic adventure of greedy, deception, and virtual machines. It’s simple I want to eliminate my mini mac and run osx in VMware so that I can install xcode iphone sdk. Is it possible? VERY! and I will explain.

I always see on forums, people pissed there isn’t an xcode release for windows.

Well if your not invited to the party, crash it. There are two options on the table. One download OSx86 and install a dual boot of windows vista & OSx. Two try to get VMware to run OSx86. I choose option number two because I did not want the hassle of dual booting. I want instant joy….

Before I begin I should state that you should buy a licensed copy of OSx if you intend on keeping it installed and plan on using it. This tutorial is purely for educational purposes and does not include any software.

In order to run the iPhone Xcode SDK you need 10.5.5 or greater with iTunes 8. You could install OSx86 stright through vmware. But why reinvent the wheel. A simple torrent search of “MacOS 10.5.5 VMWARE image” will land you exactly what you need.

Once downloaded you’re going to want to boot the VMware image. This version booted really quick and wasn’t clunky and slow like the other vmware images. I do run a quad core and was able to dedicate 2 processors to it and 1.5 gig of memory. I’m sure that made some difference but should be two different on a solo core.

All you really need to do is download the iPhone SDK through the apple website. At that point everything should be all good.

Desktop Resolution Fix if you get annoyed by the 1024 x 768. Its nice running OSx at the same resolution as your desktop and just full screen it