Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Tuesday, February 26, 2013

Jquery code doesn't work after paging

i have written below code in my header page


<script type="text/javascript" src="fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script type="text/javascript" src="fancybox/jquery.fancybox-1.3.4.pack.js"></script>

<link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.3.4.css" media="screen" />

<script type="text/javascript">
        $(document).ready(function() {
            $(".various3").fancybox({
                'width'                : 1000,
                'height'            : 580,
                'autoScale'            : true,
                'autoSize'          : false,
                'transitionIn'        : 'none',
                'transitionOut'        : 'none',
                'autoDimensions': false,
                'type'                : 'iframe'
               
            });
        });
    </script>

This works fine.. but when i do paging then code written doesn't work.

i am resolved the that issues with little bit changes in my following code.

code is given below.

<script type="text/javascript">
    $(document).ready(function () {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(showtpopup);
        showtpopup();
    });
    function showtpopup() {
        $(".various3").fancybox({
                'width'                : 1000,
                'height'            : 580,
                'autoScale'            : true,
                'autoSize'          : false,
                'transitionIn'        : 'none',
                'transitionOut'        : 'none',
                'autoDimensions': false,
                'type'                : 'iframe'
        });
    }
</script>


Thats work fine. 

Wednesday, February 20, 2013

Garbage Collection in .NET


Introduction

Garbage collection is a process of releasing the memory used by the objects, which are no longer referenced. This is done in  different ways and different manners in various platforms and languages. We will see how garbage collection is being done in .NET.

Garbage Collection basis

  • Almost every program uses resources such as database connection, file system objects etc. In order to make use of these things some resources should be available to us.
  • First we allocate a block of memory in the managed memory by using the new keyword. (This will emit thenewobj instruction in the Microsoft intermediate language code generated from C#, VB.NET, Jscript.NET or any other .NET compliance language).
  • Use the constructor of the class to set the initial state of the object.
  • Use the resources by accessing the type’s members.
  • At last CLEAR THE MEMORY.
When we look at these steps, it seems to be a very simple process to do with. But how many of us do that without forgetting to release the memory block. C++ programmers will agree with me. C++ has got a special member function called Destructor. It has the same name of the constructor or the class with the ‘~’ (tilde) symbol to start with. This is a special kind of function which will be called every time by the system when ever the system finds that object will not be used any more by the program. (When the scope and lifetime of the object goes off).
But how many times have programmers forgotten to release the memory. Or how many times the programmers try to access the memory which was cleaned.
These two are the serious bugs, which will lead us to memory leak and commonly occurring. In order to overcome these things the concept of automatic memory management has come. Automatic memory management or Automatic garbage collection is a process by which the system will automatically take care of the memory used by unwanted objects (we call them as garbage) to be released. Hurrah….. Thanks to Microsoft's Automatic Garbagecollection mechanism.

Automatic Garbage Collection in .NET

When Microsoft planned to go for a new generation platform called .NET with the new generation language called C#, their first intention is to make a language which is developer friendly to learn and use it with having rich set of APIs to support end users as well. So they put a great thought in Garbage Collection and come out with this model of automatic garbage collection in .NET.
They implemented garbage collector as a separate thread. This thread will be running always at the back end. Some of us may think, running a separate thread will make extra overhead. Yes. It is right. That is why the garbagecollector thread is given the lowest priority. But when system finds there is no space in the managed heap (managed heap is nothing but a bunch of memory allocated for the program at run time), then garbage collector thread will be given REALTIME priority (REALTIME priority is the highest priority in Windows) and collect all the un wanted objects.

How does Garbage collector locate Garbage

When an program is loaded in the memory there will be a bunch of memory allocated for that particular program alone and loaded with the memory. This bunch of memory is called Managed Heap in .NET world. This amount of memory will only be used when an object is to be loaded in to the memory for that particular program.
This memory is separated in to three parts.
  • Generation Zero.
  • Generation One and
  • Generation Two.
Generation ZeroGeneration OneGeneration Two
Figure 1.1 Managed Heap Structure.
Ideally Generation zero will be in smaller size, Generation one will be in medium size and Generation two will be larger.
When we try to create an object by using NEW keyword in the high level languages. It will simply emit newobj in to the MSIL file. (newobj is a Microsoft Intermediate Language instruction to create a new type). When newobjexecutes, the system will,
  • Calculate the number of bytes required for the object or type to be loaded in to the managed heap.
  • Add the bytes required for an object’s overhead. Each object has two overhead fields: a method table pointer and a SyncBlockIndex. On a 32-bit system, each of these fields requires 32 bits, adding 8 bytes to each object. On a 64-bit system, each is 64 bits, adding 16 bytes to each object.
  • The CLR then checks that the bytes required to allocate the object are available in the reserved region (committing storage if necessary). IF the object fits, it is allocated at the address pointed to by NextObjPtr. The type’s constructor is called (passing NextObjPtr) for the this parameter), and the newobj MSIL instruction (or the new operator) returns the address of the object. Just before the address is returned, NextObjPtr is advanced past the object and indicates the address where the next object will be placed in the heap.
  • These processes will happen at the Generation zero level.
ABC 
Figure 1.2 Allocating objects in the Managed Heap
When Generation Zero is full and it does not have enough space to occupy other objects but still the program wants to allocate some more memory for some other objects, then the garbage collector will be given the REALTIME priority and will come in to picture.
Now the garbage collector will come and check all the objects in the Generation Zero level. If an object’s scope and lifetime goes off then the system will automatically mark it for garbage collection.

Note:

Here in the process the object is just marked and not collected. Garbage collector will only collect the object and free the memory.
Garbage collector will come and start examining all the objects in the level Generation Zero right from the beginning. If it finds any object marked for garbage collection, it will simply remove those objects from the memory.
Here comes the important part. Now let us refer the figure 1.2 above. There are three objects in the managed heap. If A and C are not marked but B has lost it scope and lifetime. So B should be marked for garbage collection. So object B will be collected and the managed heap will look like this.
A C 
Figure 1.3 Memory Structure after Sweep
But do remember that the system will come and allocate the new objects only at the last. It does not see in between. So it is the job of garbage collector to compact the memory structure after collecting the objects. It does that also. So the memory would be looking like as shown below now.
AC 
Figure 1.4 Memory Structure after Compact
But garbage collector does not come to end after doing this. It will look which are all the objects survive after the sweep (collection). Those objects will be moved to Generation One and now the Generation Zero is empty for filling new objects.
If Generation One does not have space for objects from Generation Zero, then the process happened in Generation Zero will happen in Generation one as well. This is the same case with Generation Two also.
You may have a doubt, all the generations are filled with the referred objects and still system or our program wants to allocate some objects, then what will happen? If so, then the MemoryOutofRangeException will be thrown.

Modal Popup not working in Google Chrome

Add the below script 



<script type="text/javascript">
function pageLoad() {
if (typeof (Sys.Browser.WebKit) == "undefined") {
Sys.Browser.WebKit = {};
}
if (navigator.userAgent.indexOf("WebKit/") > -1) {
Sys.Browser.agent = Sys.Browser.WebKit;
Sys.Browser.version = parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
Sys.Browser.name = "WebKit";
}
}
</script>

Monday, February 18, 2013

The MVC Programming Model


MVC is one of three ASP.NET programming models.
MVC is a framework for building web applications using a MVC (Model View Controller) design:
  • The Model represents the application core (for instance a list of database records).
  • The View displays the data (the database records).
  • The Controller handles the input (to the database records).
The MVC model also provides full control over HTML, CSS, and JavaScript.

MVC
The MVC model defines web
applications with 3 logic layers:

The business layer (Model logic)
The display layer (View logic)
The input control (Controller logic)
The Model is the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.
The View is the parts of the application that handles the display of the data.
Most often the views are created from the model data.
The Controller is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the model.
The MVC separation helps you manage complex applications, because you can focus on one aspect a time. For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.
The MVC separation also simplifies group development. Different developers can work on the view, the controller logic, and the business logic in parallel.

Web Forms vs MVC

The MVC programming model is a lighter alternative to traditional ASP.NET (Web Forms). It is a lightweight, highly testable framework, integrated with all existing ASP.NET features, such as Master Pages, Security, and Authentication.

Visual Studio Express 2012/2010

Visual Studio Express is a free version of Microsoft Visual Studio.
Visual Studio Express is a development tool tailor made for MVC (and Web Forms).
Visual Studio Express contains:
  • MVC and Web Forms
  • Drag-and-drop web controls and web components
  • A web server language (Razor using VB or C#)
  • A web server (IIS Express)
  • A database server (SQL Server Compact)
  • A full web development framework (ASP.NET)

Sunday, February 17, 2013

Difference between Asp.net SessionState and ViewState in C#, VB.NET


View State: 
  1. View state is maintained in page level only.
  2. View state of one page is not visible in another page.
  3. View state information stored in client only.
  4. View state persist the values of particular page in the client (browser) when post back operation done.
  5. View state used to persist page-instance-specific data. (Read more)


Session State: 
  1. Session state is maintained in session level.
  2. Session state value is available in all pages within a user session.
  3. Session state information stored in server.
  4. Session state persist the data of particular user in the server. This data available till user close the browser or session time completes.
  5. Session state used to persist the user-specific data on the server side. (Read more)   

Usage
  1.  If you want to access the information on different web pages, you can use SessionState
  2. If you want to access from the same page, then you can use Viewstate

 Security
  1.  Session state provides more security when compared with view state as the data value is stored in server side

What is the Difference between Const and Readonly


Const:

      1.    Const can only be initialized at the time of declaration of the field.
      2.    Const values will evaluate at compile time only.
      3.    Const value can’t be changed these will be same at all the time.
      4.    This type of fields are required when one of the field values remains constant throughout the system like Pi will remain same in your Maths Class.

Read-only:

     1.    The value will be initialized either declaration time or the constructor of the class allowing you to pass the value at run time.
      2.    Read only values will evaluate at runtime only.

Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice in asp.net or how to create webservice and how to use webservice in asp.net


What is Web Service?

Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as
  • HTTP
  • XML
  • SOAP
Advantages of Web Service

Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Examples for Web Service

Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.

Stock Quote: You can display latest update of Share market with Stock Quote on your web site.

News Headline: You can display latest news update by using News Headline Web Service in your website.

In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Frequently used word with web services

What is SOAP?

SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.

What is WSDL? 

WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which those methods can be accessed and Data Types used.

What is UDDI?

UDDI allows you to find web services by connecting to a directory.

What is Discovery or .Disco Files?

Discovery files are used to group common services together on a web server. Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service. Disco File contains URL for the WSDL, URL for the documentation and URL to which SOAP messages should be sent.

Before start creating web service first create one table in your database and give name UserInformationin my code I am using same name and enter some dummy data for our testing purpose

Column Name
Data Type
Allow Nulls
UserId
Int(Set Identity=true)
No
UserName
Varchar(50)
Yes
FirstName
Varchar(50)
Yes
LastName
Varchar(50)
Yes
Location
Varchar(50)
Yes

Now we will see how to create new web service application in asp.net

Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Service



Now our new web service ready our webservice website like this



Now open your Service.cs file in web service website to write the code to get the user details from database

Before writing the WebMethod in Service.cs first add following namespaces


using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After adding namespaces write the following method GetUserDetails in Service.cs page

[WebMethod]
public XmlElement GetUserDetails(string userName)
{
SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like @userName+'%'", con);
cmd.Parameters.AddWithValue("@userName", userName);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
// Return the DataSet as an XmlElement.
XmlDataDocument xmldata = new XmlDataDocument(ds);
XmlElement xmlElement = xmldata.DocumentElement;
return xmlElement;
}

Here we need to remember one point that is adding [WebMethod] before method definition because we need to access web method pulically otherwise it’s not possible to access method publically. If you observe above code I converted dataset to XmlElement t because sometimes we will get error like return type dataset invalid type it must be either an IListSource, IEnumerable, or IDataSource to avoid this error I converted dataset to XmlElement.

Here we need to set the database connection in web.config because here I am getting database connection from web.config


<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
Now run your web service it would be like this


Our web service is working fine now we need to know how we can use webservice in our application? Before to know about using web service in application first Deploy your webservice application in your local system if you want to know how to deploy application in your local system check this link deploy application in local system

How to Use Web service in web application?

By using this webservice we can get the user details based on username. For that first create one new web application

Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Site


After creation of new website right click on solution explorer and choose “Add web reference” that would be like this

After select Add Web reference option one window will open like this 



Now enter your locally deployed web service link and click Go button after that your web service will found and window will looks like this


 

Now click on Add Reference button web service will add successfully. Now open your Default.aspx page and design like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Getting Data from WebService</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<b>Enter UserName:</b>
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvUserDetails" runat="server" EmptyDataText="No Record Found">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
Now in code behind add following namespaces

using System.Data;
using System.Xml;


After adding namespaces write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindUserDetails("");
}
}
protected void BindUserDetails(string userName)
{
localhost.Service objUserDetails = new localhost.Service();
DataSet dsresult = new DataSet();
XmlElement exelement = objUserDetails.GetUserDetails(userName);
if(exelement!=null)
{
XmlNodeReader nodereader = new XmlNodeReader(exelement);
dsresult.ReadXml(nodereader, XmlReadMode.Auto);
gvUserDetails.DataSource = dsresult;
gvUserDetails.DataBind();
}
else
{
gvUserDetails.DataSource = null;
gvUserDetails.DataBind();   
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindUserDetails(txtUserName.Text);
}
Now run your application and check output