Wednesday, 13 April 2016

View State in ASP.Net

Web Applications work on HTTP protocol. HTTP protocol is a stateless protocol, meaning it does not retain state between user requests. Let's understand the stateless nature of the HTTP protocol with an example.

Create a new asp.net web application project. Drag and drop a TextBox and a Button control onto the webform. Change the Text property of the Button control to Click Me.

At this point, double click the button control, which should generate the event handler in the code behind file.

Modify the code behind file, so the code in WebForm1 class looks as shown below.

1. In the scope of WebForm1 class, we are creating an integer variable ClicksCount which is initialized to ZERO.
2. On the Page_Load() event handler, we are setting the Text property of TextBox1 to ZERO. We do this initialization, only, when the request is an initial GET request.
3. In the Button1_Click() event, we are incrementing the value of the ClicksCount by 1, and then assigning the value to the Text property of TextBox1.
public partial class WebForm1 : System.Web.UI.Page
{
    int ClicksCount = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "0";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ClicksCount = ClicksCount + 1;
        TextBox1.Text = ClicksCount.ToString();
    }
}

So what actually happens when you make a GET request for this WebForm1?
When we compile this project an assembly is generated. Since the name of the project is ViewStateDemo, the name of the assembly will be ViewStateDemo.dll. So when a request is made for WebForm1, The application's assembly(ViewStateDemo.dll) creates an instance (object), of WebForm1, initializes ClicksCount to ZERO, and set's the TextBox1.Text to ZERO. As this is the initial GET request, the Button1_Click() event will not be executed. At this point the web server, generates the HTML to respond to the request, and posts that response back to the browser. It then immediately destroys the instance of the WebForm1.


The browser receives the HTML, and we should now see textbox set to ZERO.


<strong>What happens when we click the Button on WebForm1?</strong>
When we click the Button, the WebForm1 gets posted to the server. This is a PostBack request, NOT A GET REQUEST. So, when the webform is posted back, a new instance of this webform is created again, initializing the ClicksCount variable to ZERO. This time, the code that is wrapped between IF(!ISPOSTBACK) block is not executed. Button1_Click() event gets executed as this is a PostBack event. ClicksCount is incremented from 0 to 1. The value is then assigned to the Text Property of TextBox1. Generates the HTML, sends it to client and destroys the webform.



At this Point, we should see the value increased to 1.


What happens when we click the Button on WebForm1 again?
When you click the button for the second time, the webform gets posted back again. A new instance of WebForm1 is created. ClicksCount initialized to ZERO. In the Button1_Click() event, the value gets incremented to 1 and assigned to TextBox1. HTML gets generated and sends it to client and destroys the webform.


So, no matter how many times you click the Button, the value of the TextBox, will not move beyond 1.

Now, let's see, how to preserve the state between requests using ViewState variables. Re-write the code in WebForm1, as shown below.</pre>
<pre>public partial class WebForm1 : System.Web.UI.Page
{
    int ClicksCount = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "0";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if(ViewState["Clicks"] != null)
        {
            ClicksCount = (int)ViewState["Clicks"] + 1;
        }
        TextBox1.Text = ClicksCount.ToString(); ;
        ViewState["Clicks"] = ClicksCount;
    }
}
</pre>
<strong>Click the Button now,</strong> and the value gets incremented every time we click. So how is this possible now. It's possible because, we are using the ViewState variable Clicks to preserve the data between requests. The ViewState data, travels with every request and response between the client and the web server.

Now, let's try to achieve the same behaviour, without explicitly storing data in a ViewState variable. Modify the WebForm1 code as shown below.
<pre>public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "0";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        int ClicksCount = Convert.ToInt32(TextBox1.Text) + 1;
        TextBox1.Text = ClicksCount.ToString();
    }
}
</pre>
Upon clicking the Button, the value gets incremented correctly as expected. This is possible because, TextBox1 is an asp.net server control, that uses viewstate internally, to preserve data across postbacks.

Because Web forms have very short lifetimes, ASP.NET takes special steps to preserve the data entered in the controls on a Web form. Data entered in controls is sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load(), Button_Click(), and many more events, that occur after Page_Init() event. We will discuss about, all the events in the life cycle of a webform and the order in which they occur in a later video session.

On the other hand the HTML controls, do not retain state across post backs. Only ASP.NET server controls retains state. To prove this
1. Add a new webform to the web application project
2. Drag and Drop Input(Text) control from the HTML tab, in the ToolBox
3. Drag and Drop TextBox control from the Standard tab, in the ToolBox
4. Finally drag and drop a button
5. Set the newly added webform as the start page by right clicking on it, in the solution explorer
6. Run the project, by pressing CTRL + F5
7. Type "TEST" into both the controls (ASP.NET TextBox and the HTML TextBox), and press the button
8. You should see that, the value in the ASP.NET TextBox is preserved across postback, but not the value in the standard HTML textbox

An HTML control can be converted in ASP.NET server control, by adding runat="server" attribute in the HTML source as shown below.

An HTML control can be converted in ASP.NET server control, by adding runat="server" attribute in the HTML source as shown below.

&lt;input id="Text1" type="text" /&gt;

Now, if you type TEST and click the button, both controls now retain state across postback.

ViewState data is serialized into base64-encoded strings, and is stored in Hidden input field __ViewState. To view this hidden input field, right click on the browser and select "View Page Source" for google chrome. In internet explorer, right click and select "View Source"

Wednesday, 6 April 2016

How To Write Jquery for Modified Date in Application Pages

How To Write A Jquery for Last Modified Date in  Application Pages

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".related-title").click(function () {
                // alert("The paragraph was clicked.");
                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1; //January is 0!
                var yyyy = today.getFullYear();

                if (dd < 10) {
                    dd = '0' + dd
                }

                if (mm < 10) {
                    mm = '0' + mm
                }

                today = mm + '/' + dd + '/' + yyyy;
                //document.write(today);
               // var cookieValue = document.getElementById("dvRelatedlinks").value;
               // alert(cookieValue);

                document.getElementById("lblRelatedlinks").innerHTML = today;
            });


            $(".blog-title").click(function () {
                // alert("The paragraph was clicked.");
                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1; //January is 0!
                var yyyy = today.getFullYear();

                if (dd < 10) {
                    dd = '0' + dd
                }

                if (mm < 10) {
                    mm = '0' + mm
                }

                today = mm + '/' + dd + '/' + yyyy;
                //document.write(today);
                // var cookieValue = document.getElementById("dvRelatedlinks").value;
                // alert(cookieValue);

                document.getElementById("lblPoll").innerHTML = today;
            });

        });

       </script>
   

Saturday, 19 March 2016

PowerShell Scripts:




This script is very useful to know who created the list with created username and created date with time in any environment like Dev, QA and Prod using PowerShell.
Here we are having a list someone created long time back but as of now we don’t know who created this list, using below PowerShell script we can get it easily.

Add-PSSnapin microsoft.sharepoint.powershell
$web = Get-SPWeb "http://sharepointworldzblogspot.com/sites/sharepoint"
$list = $web.lists["listname"]
$listwhocreated = $list.Author
$listcreateddate = $list.Created
Write-Host "Created User Name:" $listwhocreated
Write-Host "Created Date:" $listcreateddate



How to Create Master Page Using Design Manager in SharePoint 2013

I have made this tutorial as many of my existing and coming tutorials start with deploying a custom master page to SharePoint 2013.
First you need to make sure you have a development enviroment that is running SharePoint 2013 and have Visual Studio 2012/13 installed.
  1. Start by creating a “Web Application” and a new Site Collection in Central Admin for this tutorial.
  2. Open Visual Studio and create a new project (SharePoint 2013 – Empty project)
  3. Choose Deploy as farm solution, or if you make this for Online then choose Sandbox.


  1. Screen Shot 2013-12-05 at 22.24.47
  2. When the project opens, click on the Project Name in the solution explorer and then set the property Site URL to the site collection you made.
  3. Now right click on the project and add a folder called FeatureElements
  4. Right click in the folder Feature Elements and add – > New Item, Under Visual C# -> SharePoint you create a new Module that you call MasterPages.
    Screen Shot 2013-12-05 at 21.35.19
  5. Remove the sample.txt
  6. Open your web browser and go to the site you created (http://xyz:57) and in there go to Settings -> Site Settings -> Master pages and page layouts. Find seattle.master and download a copy of that master page to you desktop.
  7. Rename the seattle.master to “MyCustom.master”. Now go back to VS and right click in the MasterPages module and take Open Folder in File Explorer. Copy your MyCustom.master to that folder.
  8. Go back to VS and In the Solution Explorer menu, click Show All Files. You can then see the MyCustom.master in the MasterPages Module. Right click and include in project.
  9. Open the Elements.xml that are in the MasterPages module and remove all code and replace with his code.

     
  10. Now go to the Features Folder and you will find Feature 1, Rename the feature to “Activate.Custom.Master”.
  11. Double click on the feature to open it and Change the Title to “Activate Custom Master”.
  12. Set Scope as  Site and make sure MasterPages are included, save and close.
    Screen Shot 2013-12-05 at 21.54.31
  13. Now right click on the feature and Add Event Receiver.
  14. The feature receiver will open (the Activate.Custom.EventReceiver.cs). If not Open it.
    The code under here will replace the default master page when you activate the feature and when you deactivate the feature it will restore to seattle.master.
  15. Delete every thing under “public class ActivateCustomEventReceiver : SPFeatureReceiver {” and paste in the following code under  the “{”
    (My code example will show the full Code, just so that you get the full picture. I have commented in the code what part you should copy. ) 
  16. Right click on the project and take Deploy. If every thing is working you should see your MyCustom.master if you go to your site and choose Settings -> Site Settings -> Master Page.
    Screen Shot 2013-12-05 at 22.19.42
  17. Your Project should look like this now. Good Luck!
    Screen Shot 2013-12-05 at 22.35.01