Tuesday, August 16, 2011

Exporting XML in a C# ASP .NET Web Application

XML (extensible markup language) is a popular format of data for importing and exporting between different applications designed using different programming languages. Since XML uses a standardized format of data, applications can easily parse the XML data to pull out specific fields, blocks, and even write their own XML files. XML is especially useful as a protocol for communicating over the Internet with applications

using (System.IO.MemoryStream stream = new System.IO.MemoryStream())

{

// Create an XML document. Write our specific values into the document.

System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.ASCII);

// Write the XML document header.

xmlWriter.WriteStartDocument();

// Write our first XML header.

xmlWriter.WriteStartElement("WebApplications");

// Write an element representing a single web application object.

xmlWriter.WriteStartElement("WebApplication");

// Write child element data for our web application object.

xmlWriter.WriteElementString("Date", DateTime.Now.ToString());

xmlWriter.WriteElementString("Programmer", "Primary Objects");

xmlWriter.WriteElementString("Name", "Hello World");

xmlWriter.WriteElementString("Language", "C# ASP .NET");

xmlWriter.WriteElementString("Status", "Complete");

// End the element WebApplication

xmlWriter.WriteEndElement();

// End the document WebApplications

xmlWriter.WriteEndElement();

// Finalize the XML document by writing any required closing tag.

xmlWriter.WriteEndDocument();

// To be safe, flush the document to the memory stream.

xmlWriter.Flush();

// Convert the memory stream to an array of bytes.

byte[] byteArray = stream.ToArray();

// Send the XML file to the web browser for download.

Response.Clear();

Response.AppendHeader("Content-Disposition", "filename=MyExportedFile.xml");

Response.AppendHeader("Content-Length", byteArray.Length.ToString());

Response.ContentType = "application/octet-stream";

Response.BinaryWrite(byteArray);

xmlWriter.Close();

}

Friday, August 12, 2011

Creating Crystal reports in ASP.NET

Create a new website and right click on

solution explorer >

add new Item

Select Crystal Report

In the dialog box choose blank report

 



 

Now click on Crystal Report Menu in Visual Studio 2010 and select Database Expert

 



 

Select OLE DB under "Create New Connection" and select Data Provider.

 



 

Click on Next, In Next Screen provide Server name and credential. And select Database.

 



 

Now from Database field, drag and drop fields as required in the report.

 

Add New ASPX Page and drag Crystal Report viewer  on the form.

Click on smart tag of Report Viewer and choose report source and click on finish.

Here is the HTML markup.

<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"

AutoDataBind="True" GroupTreeImagesFolderUrl="" Height="1202px"

ReportSourceID="CrystalReportSource1" ToolbarImagesFolderUrl=""

ToolPanelWidth="200px" Width="1104px" />

<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">

<Report FileName="CrystalReport.rpt">

</Report>

</CR:CrystalReportSource>

 

Add following code in Page_load,

 

protected void Page_Load(object sender, EventArgs e)

{

ReportDocument crystalReport = new ReportDocument();

crystalReport.Load(Server.MapPath("CrystalReport.rpt"));

CrystalReportViewer1.ReportSource = crystalReport;

}

 

 

Thursday, June 16, 2011

Cloud Storage global war

It’s been a “Cloud” a buzzing word nowadays, since Apple introduce its icloud in iOS 5 before few days…

It’s been a busy time for cloud storage and music services and Apple’s launch onto the scene with Apple iCloud has officially declared it global war.

http://www.pocket-lint.com/news/40364/icloud-google-music-dropbox-skydrive-amazon-cloud-player

But did you know that iCloud is using Micrososft azure and amazons cloud service????

http://www.infiniteapple.net/is-icloud-utilizing-microsoft-azure-and-amazons-cloud-services

I have tried to find something about Microsoft Live Skydrive

Windows Live SkyDrive (initially Windows Live Folders) is part of Microsoft's Windows Live range of online services. SkyDrive is a File hosting service that allows users to upload files to a cloud storage and then access them from a Web browser. It uses Windows Live ID to control access to the user's files, allowing them to keep the files private, share with contacts, or make the files public. Publicly-shared files do not require a Windows Live ID to access.

 

The service offers 25 GB of free personal storage, with individual files limited to 50 MB. A Silverlight-based tool can be installed to allow drag-and-drop uploading from any Silverlight enabled browser such as Windows Explorer on a Windows machine or Safari on a Apple Macintosh computer. Up to five files can be uploaded each time if the tool has not been installed.

You can access skydrive from here...

http://explore.live.com/windows-live-skydrive

 

icloud information can be accessed from here,

http://www.apple.com/icloud/what-is.html

Its been my little attempt to dig on cloud storage.

It’s good that every giant is coming with their own cloud storage product with their own fancy names…. But the big question would be how secure is cloud storage??

Monday, April 4, 2011

How To See Last Modified Date of Objects in SQL Server 2008

declare @day as int
set @day = 12
select * from
(SELECT [name],create_date,modify_date,'table' type1,1 order1 FROM sys.tables
union
SELECT [name],create_date,modify_date,'view' type1,2 order1 FROM sys.views
union
SELECT [name],create_date,modify_date,'trigger' type1,5 order1 FROM sys.triggers
union
SELECT [name],create_date,modify_date,'sp' type1,3 order1 FROM sys.procedures
WHERE [type] = 'P' AND is_ms_shipped = 0 AND [name] NOT LIKE 'sp[_]%diagram%'
union
select [name],create_date,modify_date,'fn' type1,4 order1 from sys.objects where type_desc like '%function%')
as modify_table
where datediff(dd,modify_date,getdate())<@day
ORDER BY order1,modify_date DESC

Wednesday, March 23, 2011

Move ViewState to the bottom of the page

If you move your viewstate from the top of the page to the bottom, you will get better search engine spidering.

 

Step 1 :

Create a class file in App_code folder of your application and name it as "PageBase.cs". Copy following code to the class file.

 

using System.IO;

using System.Web.UI;

 

namespace WebPageBase

{

public class PageBase : System.Web.UI.Page

{

/// This method overrides the Render() method for the page and moves the ViewState

/// from its default location at the top of the page to the bottom of the page. This

/// results in better search engine spidering.

 

protected override void Render(System.Web.UI.HtmlTextWriter writer)

{

// Obtain the HTML rendered by the instance.

StringWriter sw = new StringWriter();

HtmlTextWriter hw = new HtmlTextWriter(sw);

base.Render(hw);

string html = sw.ToString();

 

// Hose the writers we don't need anymore.

hw.Close();

sw.Close();

 

// Find the viewstate.

int start = html.IndexOf(@"<input type=""hidden"" name=""__VIEWSTATE""" );

// If we find it, then move it.

if (start > -1)

{

int end = html.IndexOf("/>", start) + 2;

 

string strviewstate = html.Substring(start, end - start);

html = html.Remove(start, end - start);

 

// Find the end of the form and insert it there.

int formend = html.IndexOf(@"</form>") - 1;

html = html.Insert(formend, strviewstate);

}

 

// Send the results back into the writer provided.

writer.Write(html);

}

}

}

 

 

Step 2 :

Inherit your aspx pages from the base class.

 

public partial class Page : WebPageBase.PageBase

{

// Your code here

}

Wednesday, March 16, 2011

ASP.Net 4.0 Enahanced Feature


  • Web.config changes



    In .Net Framework 4.0, the major configuration elements have been moved to the machine.config file, and applications now inherit these settings. This allows web.config file to be empty or contains 2 or 3 customized entry.



    • Permanently Redirecting a Page




      . In ASP.NET, developers have traditionally handled requests to old URLs by using by using the Response.Redirect method to forward a request to the new URL. However, the Redirect method issues an HTTP 302 Found (temporary redirect) response, which results in an extra HTTP round trip when users attempt to access the old URLs.

      ASP.NET 4 adds a new RedirectPermanent helper method that makes it easy to issue HTTP 301 Moved Permanently responses, as in the following example:

      • RedirectPermanent(“Newpage.aspx”);




      • Compression of Session


      ASP.NET provides two default options for storing session state across a Web farm: a session-state provider that invokes an out-of-process session-state server, and a session-state provider that stores data in a Microsoft SQL Server database. Because both options involve storing state information outside a Web application's worker process, session state has to be serialized before it is sent to remote storage. Depending on how much information a developer saves in session state, the size of the serialized data can grow quite large.

      ASP.NET 4 introduces a new compression option for both kinds of out-of-process session-state providers. When the compressionEnabled configuration option shown in the following example is set to true, ASP.NET will compress (and decompress) serialized session state by using the .NET Framework System.IO.Compression.GZipStream class

      <sessionState mode="SqlServer"

      sqlConnectionString="data source=servername;Initial Catalog=aspnetstate"

      allowCustomSqlDatabase="true" compressionEnabled="true" />



      • Expanding the Range of Allowable URLs




        ASP.NET 4 introduces new options for expanding the size of application URLs. Previous versions of ASP.NET constrained URL path lengths to 260 characters, based on the NTFS file-path limit. In ASP.NET 4, you have the option to increase (or decrease) this limit as appropriate for your applications, using two new httpRuntime configuration attributes. The following example shows these new attributes.

        ASP.NET 4 also enables you to configure the characters that are used by the URL character check.

        When ASP.NET finds an invalid character in the path portion of a URL, it rejects the request and issues an HTTP 400 error.

        <httpRuntime maxRequestPathLength="260" maxQueryStringLength="2048"

        requestPathInvalidChars="&lt;,&gt;,*,%,&amp;,:,\,?" />



        • CSS Friendly Menu control




          Menu control will Render in <ul> and <li> instead of table. You can specify its property Renderingmode="list"

          1. Performance Monitoring for Individual Applications in a Single Worker Process


          In order to increase the number of Web sites that can be hosted on a single server, many hosters run multiple ASP.NET applications in a single worker process. However, if multiple applications use a single shared worker process, it is difficult for server administrators to identify an individual application that is experiencing problems.

          ASP.NET 4 leverages new resource-monitoring functionality introduced by the CLR. To enable this functionality, you can add the following XML configuration snippet to the aspnet.config configuration file.

          <?xml version="1.0" encoding="UTF-8" ?>

          <configuration>

          <runtime>

          <appDomainResourceMonitoring enabled="true"/>

          </runtime>

          </configuration>

          When the appDomainResourceMonitoring feature has been enabled, two new performance counters are available in the "ASP.NET Applications" performance category: % Managed Processor Time and Managed Memory Used. Both of these performance counters use the new CLR application-domain resource management feature to track estimated CPU time and managed memory utilization of individual ASP.NET applications. As a result, with ASP.NET 4, administrators now have a more granular view into the resource consumption of individual applications running in a single worker process.



          • Multi-Targeting




            You can create an application that targets a specific version of the .NET Framework. In ASP.NET 4, a new attribute in the compilation element of the Web.config file lets you target the .NET Framework 4 and later. If you explicitly target the .NET Framework 4, and if you include optional elements in the Web.config file such as the entries for system.codedom, these elements must be correct for the .NET Framework 4. (If you do not explicitly target the .NET Framework 4, the target framework is inferred from the lack of an entry in the Web.config file.)

            The following example shows the use of the targetFramework attribute in the compilation element of the Web.config file.

            <compilation targetFramework="4.0"/>



            • jQuery Included




              When you create a new website or project, a Scripts folder containing the following 3 files is created:

              • jQuery-1.4.1.js – The human-readable, unminified version of the jQuery library.

              • jQuery-14.1.min.js – The minified version of the jQuery library.

              • jQuery-1.4.1-vsdoc.js – The Intellisense documentation file for the jQuery library.


              Include the unminified version of jQuery while developing an application. Include the minified version of jQuery for production applications.

              In the past, if you used the ASP.NET ScriptManger then you were required to load the entire monolithic ASP.NET Ajax Library. By taking advantage of the new ScriptManager.AjaxFrameworkMode property, you can control exactly which components of the ASP.NET Ajax Library are loaded and load only the components of the ASP.NET Ajax Library that you need.

              • ScriptManager Explicit Scripts


              The ScriptManager.AjaxFrameworkMode property can be set to the following values:

              • Enabled -- Specifies that the ScriptManager control automatically includes the MicrosoftAjax.js script file, which is a combined script file of every core framework script (legacy behavior).

              • Disabled -- Specifies that all Microsoft Ajax script features are disabled and that the ScriptManager control does not reference any scripts automatically.

              • Explicit -- Specifies that you will explicitly include script references to individual framework core script file that your page requires, and that you will include references to the dependencies that each script file requires.


              For example, if you set the AjaxFrameworkMode property to the value Explicit then you can specify the particular ASP.NET Ajax component scripts that you need:

              <asp:ScriptManager ID="sm1" AjaxFrameworkMode="Explicit" runat="server">

              <Scripts>

              <asp:ScriptReference Name="MicrosoftAjaxCore.js" />

              <asp:ScriptReference Name="MicrosoftAjaxComponentModel.js" />

              <asp:ScriptReference Name="MicrosoftAjaxSerialization.js" />

              <asp:ScriptReference Name="MicrosoftAjaxNetwork.js" />

              </Scripts>

              </asp:ScriptManager>

              • Setting Meta Tags with the Page.MetaKeywords and Page.MetaDescription Properties


              ASP.NET 4 adds two properties to the Page class, MetaKeywords and MetaDescription. These two properties represent corresponding meta tags in your page, as shown in the following example:

              <head id="Head1" runat="server">

              <title>Untitled Page</title>

              <meta name="keywords" content="These, are, my, keywords" />

              <meta name="description" content="This is the description of my page" />

              </head>

              These two properties work the same way that the page’s Title property does.

              1. Enabling View State for Individual Controls


              The ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit. Enabled enables view state for that control and for any child controls that are set to Inherit or that have nothing set. Disabled disables view state, and Inherit specifies that the control uses the ViewStateMode setting from the parent control.

              1. Changes to Browser Capabilities


              ASP.NET determines the capabilities of the browser that a user is using to browse your site by using a feature called browser capabilities. Browser capabilities are represented by the HttpBrowserCapabilities object

              For example, you can use the HttpBrowserCapabilities object to determine whether the type and version of the current browser supports a particular version of JavaScript. Or, you can use the HttpBrowserCapabilities object to determine whether the request originated from a mobile device.



              • Setting Client IDs




                The id attribute in HTML that is rendered for Web server controls is generated based on the ClientID property of the control. Until ASP.NET 4, the algorithm for generating the id attribute from the ClientID property has been to concatenate the naming container (if any) with the ID, and in the case of repeated controls (as in data controls), to add a prefix and a sequential number. While this has always guaranteed that the IDs of controls in the page are unique, the algorithm has resulted in control IDs that were not predictable, and were therefore difficult to reference in client script.

                The new ClientIDMode property lets you specify more precisely how the client ID is generated for controls. You can set the ClientIDMode property for any control, including for the page. Possible settings are the following:

                • AutoID – This is equivalent to the algorithm for generating ClientID property values that was used in earlier versions of ASP.NET.

                • Static – This specifies that the ClientID value will be the same as the ID without concatenating the IDs of parent naming containers. This can be useful in Web user controls. Because a Web user control can be located on different pages and in different container controls, it can be difficult to write client script for controls that use the AutoID algorithm because you cannot predict what the ID values will be.

                • Predictable – This option is primarily for use in data controls that use repeating templates. It concatenates the ID properties of the control's naming containers, but generated ClientID values do not contain strings like "ctlxxx". This setting works in conjunction with the ClientIDRowSuffix property of the control. You set the ClientIDRowSuffix property to the name of a data field, and the value of that field is used as the suffix for the generated ClientID value. Typically you would use the primary key of a data record as the ClientIDRowSuffix value.

                • Inherit – This setting is the default behavior for controls; it specifies that a control's ID generation is the same as its parent.


                In some scenarios, such as when you are using master pages, controls can end up with IDs like those in the following rendered HTML:

                ctl00$ContentPlaceHolder1$ParentPanel$NamingPanel1$TextBox1

                This ID is guaranteed to be unique in the page, but is unnecessarily long for most purposes.The easiest way to reduce the length of the rendered ID is by setting the ClientIDMode property as shown in the following example:

                <tc:NamingPanel runat="server" ID="NamingPanel1" ClientIDMode="Predictable">

                <asp:TextBox ID="TextBox1" runat="server" Text="Hello!"></asp:TextBox>

                </tc:NamingPanel>

                • ASP.NET Chart Control


                .NET Framework 4 release includes following feature of chart.

                • 35 distinct chart types.

                • An unlimited number of chart areas, titles, legends, and annotations.

                • A wide variety of appearance settings for all chart elements.

                • 3-D support for most chart types.

                • Smart data labels that can automatically fit around data points.

                • Strip lines, scale breaks, and logarithmic scaling.

                • More than 50 financial and statistical formulas for data analysis and transformation.

                • Simple binding and manipulation of chart data.

                • Support for common data formats such as dates, times, and currency.

                • Support for interactivity and event-driven customization, including client click events using Ajax.

                • State management.

                • Binary streaming.



                • ListView Control Enhancements


                The ListView control has been made easier to use in ASP.NET 4. The earlier version of the control required that you specify a layout template that contained a server control with a known ID. The following markup shows a typical example of how to use the ListView control in ASP.NET 3.5.

                <asp:ListView ID="ListView1" runat="server">

                <LayoutTemplate>

                <asp:PlaceHolder ID="ItemPlaceHolder" runat="server"></asp:PlaceHolder>

                </LayoutTemplate>

                <ItemTemplate>

                <% Eval("LastName")%>

                </ItemTemplate>

                </asp:ListView>

                In ASP.NET 4, the ListView control does not require a layout template. The markup shown in the previous example can be replaced with the following markup:

                <asp:ListView ID="ListView1" runat="server">

                <ItemTemplate>

                <% Eval("LastName")%>

                </ItemTemplate>

                </asp:ListView>



                • CheckBoxList and RadioButtonList Control Enhancements




                  In ASP.NET 3.5, you can specify layout for the CheckBoxList and RadioButtonList using the following two settings:

                  • Flow. The control renders span elements to contain its content.

                  • Table. The control renders a table element to contain its content.


                  In ASP.NET 4, the CheckBoxList and RadioButtonList controls support the following new values for the RepeatLayout property:

                  • OrderedList – The content is rendered as li elements within an ol element.

                  • UnorderedList – The content is rendered as li elements within a ul element.



                  • Default Hashing Algorithm is changed to HMACSHA256


                  ASP.NET uses both encryption and hashing algorithms to help secure data such as forms authentication cookies and view state. By default, ASP.NET 4 now uses the HMACSHA256 algorithm for hash operations on cookies and view state. Earlier versions of ASP.NET used the older HMACSHA1 algorithm.

                  Wednesday, February 2, 2011

                  10 Principal for keeping Your Programming code clean

                  A common issue in almost every profession that can drive people completely insane is having to continue from what somebody else started. The main reason for this being the fact that everyone has different ways of working, and sometimes these self-induced habits can be just downright messy.



                  In order to make code look cleaner, and thus, support team work (meaning that somebody else might need to work with what was coded before), there are certain considerations that should be taken into account.



                  1. Revise Your Logic Before Coding


                  Before blindly typing into the debugger of choice, some flow diagrams or written pseudo-code might come in handy to previously verify the logic behind those lines of code. Writing it down first can clarify many doubts or insecurities about complex functionality, and therefore save a lot of time. But most importantly, helping you get it right faster will also help you avoid all the messy code replacements and additions that tamper with the following principles.



                  2. Clearly Expose the Structure of the Page


                  Working with main containers is useful, but working with main containers with a representative ID is even more useful. Consider the following starting scenario:












                  1

                  2

                  3

                  4

                  5

                  6

                  7

                  8

                  9

                  10

                  11

                  12

                  13

                  14

                  15

                  16
                  <div id="main-container">

                  <div id="header">

                  <div id="logo">...</div>

                  <div id="main-menu">...</div>

                  </div>

                  <div id="content">

                  <div id="left-column">...</div>
                  <div id="center-column">...</div>

                  <div id="right-column">...</div>

                  </div>

                  <div id="footer">

                  <div id="footer-menu">...</div>

                  <div id="disclaimer">...</div>

                  </div>

                  </div>


                  The structure appears evident, thanks to the DIV containers that are concretely named after their destined content. Not only will it be simpler to start adding code, but it'll also be perfectly transparent for someone who tries to add or remove something afterward. This structuring method, however, should be aided by the next statement.


                   3. Use the Correct Indentation


                  Supporting the previous pronouncement on structure, indentation distinctly displays the opening and closing points of each element used. If every line of code is glued to the left side of the screen, it'll be very hard to distinguish the exact place where an element is closed. Therefore, it'll mess up the effort made at designing a complete structure, since it won't be noticeable afterward.


                   4. Write Explanatory Comments


                  Underestimating the value of good comments is disregarding a very effective way of code documentation. It's easy, fast, and very straight-to-the-point, since it's done right then and there when it's needed.


                  Comments are also efficient considering the fact that they can be read at the exact moment of doubt. They can, however, be overused. And that brings us to the next recommendation.


                   5. Avoid Abusing Comments


                  Comments aren't to be treated lightly. When commenting on code, the current functionality is explained in terms of variables and results. What comments are NOT made for is:




                  • Writing explanatory notes to self (e.g. /* Will finish this later... */).

                  • Blaming stuff on other people (e.g. /* John coded this. Ask him. */).

                  • Writing vague statements (e.g. /* This is another math function. */).

                  • Erasing chunks of code. Sometimes people are not sure of erasing things and it's not absolutely evil to comment that code instead.


                  What's not right is to just leave it afterwards. It'll be terribly confusing. If the code will be documented via embedded comments, the team members need to make sure those comments are there for a reason.

                  Examples of good comment use are:




                  • Authoring specifications (e.g. /* Coded by John, November 13th 2010 */).

                  • Detailed statements on the functionality of a method or procedure (e.g. /* This function validates the login form with the aid of the e-mail check function */).

                  • Quick notifications or labels that state where a recent change was made (e.g. /* Added e-mail validation procedure */).


                  6. Avoid Extremely Large Functions

                  In the process of adding functionality to an application, its coded methods tend to grow accordingly. One can come across functions that consist of up to a hundred lines of code, and this tends to become confusing.


                  A better practice would be to break up large functions into smaller ones. Some procedures may even be repeating themselves amongst the rest of the functions conforming the whole application process. The team could make better use of those repeated procedures through separate functions. This, however, should have been avoided from the beginning if the first recommendation was carried out correctly.


                   7. Use Naming Standards for Functions and Variables


                  Whenever a variable or a function is created, its name should be descriptive enough as to give a general idea of what it does or what it's for.


                  There are companies that have their own pre-established naming standards


                  (e.g. The prefix 'int_' for any numeric variables), but there are also many companies in which the employees do not keep these standards. Laziness makes people work double the time during future redesigns, so everyone needs to start learning how to get rid of it.


                   8. Treat Changes with Caution


                  The correct appliance of changes summarizes a lot of what has been previously said, like commenting meaningfully and not disrupting indentations. Nevertheless, it needs to be emphasized. Whenever there's a need for adding, removing, or changing something, there should also be an awareness of not meddling with previous efforts for maintaining the code clean and ordered.


                  This mainly involves:




                  • Keeping the correct indentations (e.g. when inserting an IF clause, its contents' indentations will be augmented).

                  • Commenting on the modification made or broadening the existing comments.

                  • Respecting standards in use.


                   

                  9. Avoid Indiscriminate Mixing of Coding Languages


                  In-line CSS styling and scattered JavaScript tags with short procedures within them are very good examples of incorrect mixing of coding languages throughout your development process. Ignoring this principle will result in huge element tags with an embedded STYLE property, lots of interruptions in the flow of the structure because of embedded functions, and of course lots and lots of confusion.


                  Even with the addition of comments, it'll still look like everything and nothing at the same time. Having the appropriate divisions between different coding languages will give order to the logic applied. This brings us, though, to the next consideration.


                   10. Summarize Your Imports


                  Even though it is much better to have additional coding languages imported from different files, this shouldn't be abused. If there are too many style sheets, they can probably be summarized into one or two.


                  This won't only save space and make things look cleaner, but it will also save loading time. Each imported file is an HTTP request that tampers with the performance of your application. So apart from being a consideration for tidiness, it is also a consideration for efficiency.

                  Saturday, January 22, 2011

                  IIS in depth

                  Web server is used when we want to host the application on a centralized location and wanted to access from many locations. Web server is responsible for handle all the requests that are coming from clients, process them and provide the responses.

                   
                   

                  What is IIS ?

                  IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it's own ASP.NET Process Engine  to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and  process it and send response back to clients.

                   
                   


                   
                   

                   
                   

                  Worker Process:  Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.  All the ASP.Net functionality runs under the scope of worker process.  When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.

                  Application Pool: Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availability for any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn't not impact other web application as they they are configured into different application pools.

                   
                   

                  Application Pool with multiple worker process is called "Web Garden".

                   
                   

                  Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now let's have look how IIS process the request when a new request comes up from client.

                  If we look into the IIS 6.0 Architecture, we can divided them into Two Layer

                   
                   

                  1.    Kernel Mode

                  2.    User Mode

                   
                   

                  Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS.  So whenever a request comes from Client to Server, it will hit HTTP.SYS First.

                   
                   


                   
                   

                  Now, HTTP.SYS is Responsible for pass the request to particular Application pool. Now here is one question, How HTTP.SYS comes to know where to send the request?  This is not a random pickup. Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it's registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web application, it checks for the Application Pool and based on the application pool it send the request.

                   
                   


                  So, this was the first steps of IIS Request Processing.

                  Till now, Client Requested for some information and request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to send. Now, let's see how this request moves from HTTP.SYS to Application Pool.

                  In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to the respective application pool.

                   
                   


                  When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process "w3wp.exe" looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.  

                  Note : Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.


                  When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.


                  When this methods called, a new instance of HTTPContext is been created.  Which is accessible using HTTPContext.Current  Properties. This object still remains alive during life time of object request.  Using HttpContext.Current we can access some other objects like Request, Response, Session etc.


                  After that HttpRuntime load an HttpApplication object with the help of  HttpApplicationFactory class.. Each and every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication.

                  Now, the concept comes called "HTTPPipeline". It is called a pipeline because it contains a set of HttpModules ( For Both Web.config and Machine.config level) that intercept the request on its way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We can also create our own HTTPModule if we need to handle anything during upcoming request and response.


                  HTTP Handlers are the endpoints in the HTTP pipeline. All request that are passing through the HTTPModule should reached to HTTPHandler.  Then  HTTP Handler  generates the output for the requested resource. So, when we requesting for any aspx web pages,   it returns the corresponding HTML output.

                  All the request now passes from  httpModule to  respective HTTPHandler then method and the ASP.NET Page life cycle starts.  This ends the IIS Request processing and start the ASP.NET Page Lifecycle.


                  Conclusion

                  When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to respective  Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.

                  This was just overview of IIS Request Processing to let Beginner's know how the request get processed in backend.  If you want to learn in details please check the link for Reference and further Study section.

                   
                   

                  The web server process that was being debugged has been terminated by Internet Information Services (IIS)

                  By default, debugging a website or web project within Visual Studio bring up the built-in server of Visual Studio. But, we do have a problem to change the server to an IIS instance. I recently switched to debugging on IIS on my Windows 7. Debugging works fine. The only problem is that if your code hit some breakpoint and if you leave the program in 'break' mode for more than 90 seconds, Visual Studio shows the following message:


                   




                   


                   


                  After a bit tweaking around in the new IIS interface, I got the solution:




                  • Open Internet Information Services (IIS) Manager.

                  • From the server tree (the item with the name as the server name), choose Application Pools.

                  • Choose the Application Pool corresponding to your testing IIS website (usually it has the same name as your IIS website)

                  • Right-click and choose Advanced Settings.


                  • From the Process Model node, change the Ping Maximum Response Time (seconds) to a comfortably higher value (I have set the value to 900 seconds which is 15 minutes).

                     


                  Alternatively, you can also set the Ping Enabled property to False.

                  Apparently what happens is that the server keeps pinging the worker process and waits for a response. When in debugging mode, the worker process is affectively suspended, which results in the ping not being responded.


                   


                   

                  Thursday, January 13, 2011

                  Bypass specific IP from rendering google analytics code

                  To bypass specific IP from rendering google analytics code, follow the following steps.



                  1. List the IP which you wants to bypass from rendering into your web application, and add in web.config file

                    e.g. <add key="ByPassUrl" value="101.101.101.100"/>


                  2. Create a Usercontrol and named "GoogleAnalytics.ascx" replace your google analytics code with "<google analytics code here>".

                    <%@Control Language="C#" AutoEventWireup="true" CodeFile="GoogleAnalytics.ascx.cs"
                    Inherits="Include_GoogleAnalytics"%>


                    <script type="text/javascript">


                    <% if (ConfigurationManager.AppSettings["showGoogleAnalytics"] == "True") {%>


                    <% if (!strByPassUrl.Contains(requestUrl)) {%>


                    var _gaq = _gaq || [];


                    _gaq.push(['_setAccount', '<google analytics code here>']);


                    _gaq.push(['_trackPageview']);


                    (function() {


                    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;


                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';


                    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);


                    })();


                    <% } %>


                    <% } %>


                    </script>


                     


                  3. Declare following 2 public variable in "GoogleAnalytics.ascx.cs" file

                    public string requestUrl = HttpContext.Current.Request.UserHostAddress.ToString();
                    public
                    string strByPassUrl = clsCommon.value("ByPassUrl");


                  4. Add "GoogleAnalytics" user control in master page of the application within <Head></Head> tag.

                    <head runat="server">


                    <uc2:GoogleAnalytics ID="GoogleAnalytics1" runat="server"/>


                    </head>


                  Note :- 1) Before Copying Google analytics code verify with google analytics script, provided in google analytics account.

                  2) check if "showGoogleAnalytics" key is present in web.config file.

                  Thursday, December 30, 2010

                  Generating Random Strings of Characters in SQL

                  The following Transact SQL procedure can be used to generate a random string of characters. As such it can be used to for example generate a default password for a user. The specific characters that are used to generate the string can be specified, so it can be customised (e.g. to only create passwords of digits or lower cased letters). The length of the generated random string can also be specified.

                  It is recommended that this SQL procedure be used as a stored procedure.

                  Using as a Stored Procedure


                  The following stored procedure creates a random string of characters of a length specified by the parameter @Length:
                  CREATE PROCEDURE sp_GeneratePassword
                  (
                  @Length int
                  )
                  AS
                  DECLARE @RandomID varchar(32)
                  DECLARE @counter smallint
                  DECLARE @RandomNumber float
                  DECLARE @RandomNumberInt tinyint
                  DECLARE @CurrentCharacter varchar(1)
                  DECLARE @ValidCharacters varchar(255)

                  SET @ValidCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+&$'

                  DECLARE @ValidCharactersLength int
                  SET @ValidCharactersLength = len(@ValidCharacters)
                  SET @CurrentCharacter = ''
                  SET @RandomNumber = 0
                  SET @RandomNumberInt = 0
                  SET @RandomID = ''
                  SET NOCOUNT ON
                  SET @counter = 1

                  WHILE @counter < (@Length + 1)
                  BEGIN
                  SET @RandomNumber = Rand()
                  SET @RandomNumberInt = Convert(tinyint, ((@ValidCharactersLength - 1) * @RandomNumber + 1))
                  SELECT @CurrentCharacter = SUBSTRING(@ValidCharacters, @RandomNumberInt, 1)
                  SET @counter = @counter + 1

                  SET @RandomID = @RandomID + @CurrentCharacter
                  END

                  SELECT @RandomID AS 'Password'
                  GO

                  Wednesday, December 15, 2010

                  Extension Methods

                  The .NET Framework employs the concept of sealed classes. A sealed class is a class that cannot be inherited from. But, what if we want to extend these classes? Based on the meaning of sealed it's not possible. Compound the technical inability to extend sealed classes with classes that are defined as the result of a LINQ query, called projections, and there is no opportunity to extend.

                  Another desire that class designers have is to avoid deep inheritance trees. Generally using inheritance to add a capability or two is undesirable because it leads to deep inheritance trees that are difficult to comprehend and maintain.


                  To overcome some of these challenges Microsoft introduced the extension method. Extension methods are defined in separate static classes as static methods and the first argument of the method is the extended type. The extended type—the first argument—is modified with the keyword this. Although an extension method is a static method in a static class, extension methods have member method semantics. That is, extension methods are called is if they were a member of the extended class, a regular member method.


                  Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.



                  Extension method are only in scope when you explicitly import the namespace into your source code with "using" directive.


                  namespace ExtensionMethods
                  {
                  public static class ExtensionsClass
                  {
                  public static string Reverse(this String strReverse)
                  {
                  char[] charArray = new char[strReverse.Length];
                  int len = strReverse.Length - 1;
                  for (int i = 0; i <= len; i++)
                  {
                  charArray[i] = strReverse[len - i];
                  }
                  return new string(charArray);
                  }
                  }
                  }

                  using ExtensionMethods;
                  protected void Page_Load(object sender, EventArgs e)
                  {
                  string str = "Hello Extension Methods";
                  string strReverse = str.Reverse();
                  }

                  Thursday, November 18, 2010

                  Finding Geolocation information from ip address in asp.net

                  Ip is the internet protocol for communication between nodes.

                  Ip is used to identify a host and address the location. If we need to identify the user

                  who are all accessing our website and store the ip address in our database is very simple and very easier.

                  This is the way to track the users ip address. Fetch a client's ip address as soon as he access our web site in asp.net.

                  Some of them may use a proxy ip address. But we can get their ip address with this simple code.

                  Add following namespace in page
                  using System.Net;

                  string ipAddress ="";

                  //Get the Host Name
                  string hostName = Dns.GetHostName();

                  //Get The Ip Host Entry
                  IPHostEntry ipHostEntry = Dns.GetHostEntry(hostName);

                  //Get The Ip Address From The Ip Host Entry Address List
                  IPAddress[] ipAddress = ipHostEntry.AddressList;

                  ipAddress = ipAddress[ipAddress.Length - 1].ToString();

                  To get the Geolocation of IP address you can use the various
                  API which would gives you result in various different format(csv,xml)

                  http://www.ipinfodb.com/ip_location_api.php

                  You can get Geolocation information from

                  http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false

                  Response comes in XML format. using xml deserialize, I deserialize the response.

                  [XmlRootAttribute(ElementName = "Response", IsNullable = false)]

                  public class IPLocator
                  {
                  private string longitude;
                  public string Longitude
                  {
                  get { return longitude; }
                  set { longitude = value; }
                  }

                  private string latitude;
                  public string Latitude
                  {
                  get { return latitude; }
                  set { latitude = value; }
                  }
                  private string zip;
                  public string Zip
                  {
                  get { return zip; }
                  set { zip = value; }
                  }

                  private string ip;
                  public string IP
                  {
                  get { return ip; }
                  set { ip = value; }
                  }
                  }

                  After deserialization IPLocater class bind All properties of requested IP Address.

                  Binding Class is return IPLocater class.

                  Code of IPDetals Class
                  public IPLocator GetData(string ipAddress)
                  {
                  IPLocator ipLoc = new IPLocator();
                  try
                  {
                  //apiKey can be generated from below link

                  //http://www.ipinfodb.com/ip_location_api.php

                  string apiKey = "anykey";
                  string path = "http://api.ipinfodb.com/v2/ip_query.php?key=" + apiKey + "&ip=" + ipAddress + "&timezone=false";

                  WebClient client = new WebClient();
                  string[] eResult = client.DownloadString(path).ToString().Split(',');

                  if (eResult.Length > 0)
                  ipLoc = (IPLocator)Deserialize(eResult[0].ToString());
                  }
                  catch
                  { }

                  return ipLoc;
                  }

                  //Desrialize XML String
                  private Object Deserialize(String pXmlizedString)
                  {
                  XmlSerializer xs = new XmlSerializer(typeof(IPLocator));

                  MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));

                  XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                  return xs.Deserialize(memoryStream);

                  }

                  //String to UTF8ByteArray

                  private Byte[] StringToUTF8ByteArray(String pXmlString)
                  {

                  UTF8Encoding encoding = new UTF8Encoding();
                  Byte[] byteArray = encoding.GetBytes(pXmlString);
                  return byteArray;
                  }
                  }

                  //You can get the Geolocation infoamation here

                  string ipAddress = HttpContext.Current.Request.UserHostAddress;

                  IPDetails ipDetails=new IPDetails ();
                  IPLocator ipLocater = ipDetails.GetData(ipAddress);
                  Response.Write(ipLocater.CountryName);

                  Tuesday, October 26, 2010

                  Windows Communication Foundation in Framework 4.0

                  Windows Communication Foundation (WCF) provides the following improvements:

                  • Configuration-based activation: Removes the requirement for having an .svc file.
                  • System.Web.Routing integration: Gives you more control over your service's URL by allowing the use of extensionless URLs.
                  • Multiple IIS site bindings support: Allows you to have multiple base addresses with the same protocol on the same Web site.
                  • Routing Service: Allows you to route messages based on content.
                  • Support for WS-Discovery: Allows you to create and search for discoverable services.
                  • Standard endpoints: Predefined endpoints that allow you to specify only certain properties.
                  • Workflow services: Integrates WCF and WF by providing activities to send and receive messages, the ability to correlate messages based on content, and a workflow service host.
                  • WCF REST features:
                    • Web HTTP caching: Allows caching of Web HTTP service responses.
                    • Web HTTP formats support: Allows you to dynamically determine the best format for a service operation to respond in.
                    • Web HTTP services help page: Provides an automatic help page for Web HTTP services, similar to the WCF service help page.
                    • Web HTTP error handling: Allows Web HTTP Services to return error information in the same format as the operation.
                    • Web HTTP cross-domain JavaScript support: Allows use of JSON Padding (JSONP).
                  • Simplified configuration: Reduces the amount of configuration a service requires

                  WCF Architecture

                  The following figure illustrates the major components of WCF.


                   
                   

                  Contracts

                  Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

                  Service contracts

                  - Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

                  Data contract

                  - It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

                  Message Contract

                  - Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

                  Policies and Binding

                  - Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

                  Service Runtime

                  - It contains the behaviors that occur during runtime of service.

                  • Throttling Behavior- Controls how many messages are processed.
                  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
                  • Metadata Behavior - Tells how and whether metadata is available to outside world.
                  • Instance Behavior - Specifies how many instance of the service has to be created while running.
                  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
                  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.

                  Messaging

                  - Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

                  • Transport Channels
                    Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
                  • Protocol Channels
                    Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

                  Activation and Hosting

                  - Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

                  • IIS
                    Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
                  • Windows Activation Service
                    (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
                  • Self-Hosting
                    WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
                  • Windows Service
                    WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

                  Friday, October 15, 2010

                  Introducing $(document).ready()

                  This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
                  $(document).ready(function() {
                  // put all your jQuery goodness in here.
                  });

                  The $(document).ready() function has a ton of advantages over other ways of getting events to work. First of all, you don't have to put any "behavioral" markup in the HTML. You can separate all of your JavaScript/jQuery into a separate file where it's easier to maintain and where it can stay out of the way of the content. I never did like seeing all those "javascript:void()" messages in the status bar when I would hover over a link. That's what happens when you attach the event directly inside an <a href> tag.

                  On some pages that use traditional JavaScript, you'll see an "onload" attribute in the <body> tag. The problem with this is that it's limited to only one function. Oh yeah, and it adds "behavioral" markup to the content again. Jeremy Keith's excellent book, DOM Scripting, showed me how to create an addLoadEvent function to a separate JavaScript file that allows for multiple functions to be loaded inside it. But it requires a fair amount of code for something that should be rather straightforward. Also, it triggers those events when the window loads, which leads me to another advantage of $(document).ready().

                  With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads. Everything that you stick inside its brackets is ready to go at the earliest possible moment — as soon as the DOM is registered by the browser, which allows for some nice hiding and showing effects and other stuff immediately when the user first sees the page elements.

                  Tuesday, October 5, 2010

                  Endpoints: Address, Bindings, and Contracts

                  WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.

                  All the WCF communications are take place through end point. End point consists of three components which are known as ‘ABC’: ‘A’ for Address, ‘B’ for Binding and ‘C’ for Contracts.

                  Address


                  Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g

                  http://localhost/MyService/TestCalculator.svc

                  Binding


                  Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.

                  A binding has several characteristics, including the following:

                  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.

                  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).

                  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability


                  The following table gives some list of protocols supported by WCF binding.











































                  BindingDescription
                  BasicHttpBindingBasic Web service communication. No security by default
                  WSHttpBindingWeb services with WS-* support. Supports transactions
                  WSDualHttpBindingWeb services with duplex contract and transaction support
                  WSFederationHttpBindingWeb services with federated security. Supports transactions
                  MsmqIntegrationBindingCommunication directly with MSMQ applications. Supports transactions
                  NetMsmqBindingCommunication between WCF applications by using queuing. Supports transactions
                  NetNamedPipeBindingCommunication between WCF applications on same computer. Supports duplex contracts and transactions
                  NetPeerTcpBindingCommunication between computers across peer-to-peer services. Supports duplex contracts
                  NetTcpBindingCommunication between WCF applications across computers. Supports duplex contracts and transactions

                  Contract


                  Contracts specifies the info for how the service is implemented and what it offers. Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

                  Example:


                  Endpoints will be mentioned in the web.config file on the created service.
                  <system.serviceModel>
                  <services>
                        <service
                          behaviorConfiguration="TestServiceBehavior">
                         <endpoint
                           address="http://localhost/MyService/TestCalculator.svc" contract="ITestService"
                            binding="wsHttpBinding"/>
                        </service>
                      </services>
                      <behaviors>
                        <serviceBehaviors>
                          <behavior>
                            <serviceMetadata httpGetEnabled="True"/>
                            <serviceDebug includeExceptionDetailInFaults="true" />
                          </behavior>
                        </serviceBehaviors>
                      </behaviors>
                    </system.serviceModel>

                  Thursday, September 30, 2010

                  Difference between WCF and Web service

                  Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service.The main feature of WCF is it's security.
                  WCF = Web services + .Net Remoting + MSMQ + (COM+)
















































                  FeaturesWeb ServiceWCF
                  HostingIt can be hosted in IISIt can be hosted in IIS,

                  windows activation service (WAS),

                  Self-hosting,

                  Managed Windows service
                  Programming[WebService] attribute has to be added to the class[ServiceContraact] attribute has to be added to the class
                  Model[WebMethod] attribute represents the method exposed to client[OperationContract] attribute represents the method exposed to client
                  OperationOne-way, Request- Response are the different operations supported in web serviceOne-Way, Request-Response, Duplex are different type of operations supported in WCF
                  XMLSystem.Xml.serialization name space is used for serializationSystem.Runtime.Serialization namespace is used for serialization
                  EncodingXML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, CustomXML 1.0, MTOM, Binary, Custom
                  TransportsIt Can be accessed only over HTTPCan be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
                  ProtocolsSecuritySecurity, Reliable messaging, Transactions

                  Thursday, September 16, 2010

                  Delegates

                  Delegates is also known as Type Safe pointer.

                  To understand type Safe Pointer, you need to understand call back function used in C++. Call back function is generally implemented in Business Tier in 3-tier architecture. Once business logic is implemented, it requires memory address of the function or method to use it. This memory address does not have any information of Method signature, so it can be called as it is not Type Safe.

                  But Delegates has the feature of callback in Safe way, as it take cares of signature information.

                  How to define delegate,

                  Public Delegate Sub MakeDelegate (ByVal EmployeeID As String)

                  We are declaring public delegate, so it can be accessed from anywhere in the application.

                  Here we are going to define a Employee class which uses the delegates and method.
                  Public Class Employee
                      Public FirstName As String
                      Public LastName As String
                   
                      Public Sub ValidEmployee (ByVal objDelegate As MakeDelegate, _
                                                  ByVal EmployeeID As String)
                          If EmployeeID.StartsWith ("MKT") Then
                              objDelegate.Invoke(EmployeeID)
                          End If
                      End Sub
                  End Class

                  The method ValidEmployee is going to accept the EmployeeID and a Delegate Object of type "MakeDelegate" as the parameters and validate whether it is a Starting with E1 and invoke the Delegate Object accordingly.

                  Dim objEmployee As Employee = New Employee()

                          Dim objDelegate As MakeDelegate
                          objDelegate = AddressOf NotifyEmployee
                   
                          objEmployee .FirstName = txtFirstName.Text
                          objEmployee.LastName = txtLastName.Text
                   

                  objEmployee.ValidateEmployee(objDelegate, txtEmployeeID.Text)

                  We assign the local procedure "NotifyEmployee", which is declared and defined inside the Windows Form Class to the Delegate Object.
                  Private Sub NotifyEmployee(ByVal EmployeeID As String)

                  MsgBox("This Employee is from Marketing Department") End Sub

                  Once we assign the instance of the Delegate, we must provide the address of a method implementation with a matching method signature.

                  Serialization in the .NET Framework

                  Serialization in .NET allows the programmer to take an instance of an object and convert it into a format that is easily transmittable over the network, or even stored in a database or file system. This object will actually be an instance of a custom type, including any properties or fields you may have set.

                  The first step in any serialization process is to take the instance of the object and convert it to a memory stream. From there we have the ability to perform any number of operations with (file IO, database IO, etc.).

                  There are 2 types of serialization. Binary serialization and xml serialization

                  Core Serialization Methods

                  #region Binary Serializers

                  public static System.IO.MemoryStream SerializeBinary(object request) {

                  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =

                  new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                  System.IO.MemoryStream memStream = new System.IO.MemoryStream();

                  serializer.Serialize(memStream, request);

                  return memStream;

                  }



                  public static object DeSerializeBinary(System.IO.MemoryStream memStream) {

                  memStream.Position=0;

                  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =

                  new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                  object newobj = deserializer.Deserialize(memStream);

                  memStream.Close();

                  return newobj;

                  }

                  #endregion


                  #region XML Serializers
                   
                  public static System.IO.MemoryStream SerializeSOAP(object request) {
                    System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =
                    new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
                    System.IO.MemoryStream memStream = new System.IO.MemoryStream();
                    serializer.Serialize(memStream, request);
                    return memStream;
                  }
                   
                  public static object DeSerializeSOAP(System.IO.MemoryStream memStream) {
                    object sr;
                    System.Runtime.Serialization.Formatters.Soap.SoapFormatter deserializer =
                    new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
                    memStream.Position=0;
                    sr = deserializer.Deserialize(memStream);
                    memStream.Close();
                    return sr;
                  }
                  #endregion