Thursday, November 24, 2011

How to Store Viewstate to Persistence Medium



In this article we will discuss about How to store ViewState of a Page/Control on server or a custom data store like sql server or file.
As you all know ViewState is stored as part of html sent to your browser in form of hidden field. This is the default behavior of asp.net framework. Starting asp.net 2.0 you have more control over how & where view state should be stored? First of all let’s understand the reason behind not sending viewstate to client:-
1.)    ViewState can be tempered with on client side with tools like firebug, fiddler etc.
2.)    ViewState makes page bulky and page loading process becomes slow.

Asp.net 2.0 introduced two methods which help us out in this process:-
1.)    LoadPageStateFromPersistenceMedium
2.)    SavePageStateToPersistenceMedium
LoadPageStateFromPersistenceMedium loads viewstate data from your custom storage.
SavePageStateToPersistenceMedium saves viewstate data to persistence medium.
So let’s try to understand this with an example
1.   Create an empty website in visual studio
2.   Add a page say Default.aspx
3.   Write below code in aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<asp:DropDownList ID="DropDownList1" runat="server">
asp:DropDownList>
td>
tr>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
td>
tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
td>
tr>
table>
div>
form>
body>
html>

4. In code behind file write below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ListItem> items = new List<ListItem>();
items.Add(new ListItem("1"));
items.Add(new ListItem("2"));
items.Add(new ListItem("3"));
DropDownList1.DataSource = items;
DropDownList1.DataBind();
}
}
protected override object LoadPageStateFromPersistenceMedium()
{
if (Session["DefaultPageViewState"] != null)
{
       string viewStateString = Session["DefaultPageViewState"] as string;
TextReader reader = new StringReader(viewStateString);
LosFormatter formatter = new LosFormatter();
object state = formatter.Deserialize(reader);
return state;
}
else
return base.LoadPageStateFromPersistenceMedium();
//return null;
}
protected override void SavePageStateToPersistenceMedium(object state)
{
LosFormatter formatter = new LosFormatter();
StringWriter writer = new StringWriter();
formatter.Serialize(writer, state);
Session["DefaultPageViewState"] = writer.ToString();
}
}
Open page in browser and page loads up with values in dropdown list.



Right click page and click View Source. See highlighted portion below..The viewstate field is empty.

Click the button to perform postback. You will see the dropdown still loads with data i.e. ViewState has been persisted and is working fine.
Just to cross check if our code is actually working. Comment out code in LoadPageStateFromPersistenceMedium method and return null instead. Again compile and run the code. Page will open fine first time but now click on postback , you will see dropdown losing data since it was stored in viewstate.

Sunday, October 30, 2011

how to get name of procedure where word like tablename, column name have been used in Oracle

SQL> select distinct name from user_source where upper(type)='PROCEDURE' and upp
er(text) like '%TABLENAME%';

NAME
------------------------------
SP_ABC
SP_BCD
SP_XYZ
SP_LMD
SP_WEEK_ABC
SP_WEEK_XYZ

Friday, October 28, 2011

How to count no of rows in a Textarea in javascript

function rowcount()
{ 
var area = document.getElementById("hist");
var text = area.value.replace(/\s+$/g, "");
var split = text.split("\n");
return split.length;
}

Thursday, August 18, 2011

How to get that particular table is being used in any procedure, trigger etc...?

select * from user_source where upper(text) like '%REVENUE_EMP_DTLS_WEEK_REPORT%'

Monday, June 27, 2011

What is the difference between hiding and overriding for casting related matters?

When you use virtual+new, the method definition of base class is hided by the definition provided in child class (called method hiding) . In this case, method of the class, whose object is created, will be called.
class Program
    {
        static void Main(string[] args)
        {
            Base obj1 = new Base();
            Child obj2 = new Child();
            Base obj3 = obj2 as Child;
            obj1.foo();
            obj2.foo();
            obj3.foo();  //Will give output Base
        }
    }

    public class Base
    {
        public virtual void foo()
        {
            Console.WriteLine("Base");
        }
    }

    public class Child : Base
    {
        public new void foo()
        {
            Console.WriteLine("Child");
        }
    }


In second case, where you want to use virtual+override, Thats method overriding. In this case child class function will be called when you create object using casting.
class Program
    {
        static void Main(string[] args)
        {
            Base obj1 = new Base();
            Child obj2 = new Child();
            Base obj3 = obj2 as Child;
            obj1.foo();
            obj2.foo();
            obj3.foo();  // output will be "Child"
        }
    }

    public class Base
    {
        public virtual void foo()
        {
            Console.WriteLine("Base");
        }
    }

    public class Child : Base
    {
        public override void foo()
        {
            Console.WriteLine("Child");
        }
    }


You can also combine both method overriding and hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }

            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }

Why does TextBox retains its value after multiple postbacks even if we set the EnableViewState property of the TextBox to False?

The reason being is ASP.NET uses this primitive to update the control's value. ASP.NET uses IPostBackDataHandler  for the controls that load the data from the form collection.
Actually all the controls which implement IPostbackdatahandler, implement the method LoadPostData and
RaisePostDataChangedEvent. But here the key method is LoadPostData, which returns true if the posted value is changed from earlier value and updates it with posted value, else it returns false.

As from the Page Life Cycle, we can see LoadPostData is called after the LoadViewState, whether viewstate is on or not,  it gets populated from the posted data. That's why the data get persisted even if viewstate is set to off for few controls. Following is the complete list of the controls, those implement IPostBackDataHandler.
  •  CheckBox
  •  CheckBoxList
  •  DropDownList
  •  HtmlInputCheckBox
  •  HtmlInputFile
  •  HtmlInputHidden
  •  HtmlInputImage
  •  HtmlInputRadioButton
  •  HtmlInputText
  •  HtmlSelect
  •  HtmlTextArea
  •  ImageButton
  •  ListBox
  •  RadioButtonList
  •  TextBox

Tuesday, June 21, 2011

Can we overload methods in WCF Service or Web Service?

Yes for a WCF Service use the Name property of OperationContractAttribute class
example:
[ServiceContract]
interface ddd
{
[OperationContract(Name = "one")]
int calc(int a,int b);

[OperationContract(Name = "two")]
double calc(double a,double b);
}

1)For a Web Service use the MessageName property of WebMethodAttribute class
2)Please comment the following line in the .cs file of the Web Service
//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[WebMethod]
public string HelloWorld(string a) {
return "Hello"+" "+a;
}
[WebMethod(MessageName="second")]
public string HelloWorld()
{
return "Hello second";
}