Overblog Follow this blog
Administration Create my blog
Balavardhan Reddy Narani

Posts with #asp.net tag

ASP.NET

December 29 2011 , Written by Balavardhan Reddy Published on #ASP.Net

 

 

 

 

 

ASP.NET

   ASP.NET, the next version of ASP, is a programming framework used to create enterprise-class Web Applications. These applications are accessble on a global basis leading to effecient information management. The advantages ASP.NET offers is more than just the next version of ASP.

 

Why ASP.NET?

Since 1995, Microsoft has been constantly working to shift it's focus from Windows-based platforms to the Internet. As a result, Microsoft introduced ASP (Active Server Pages) in November 1996. ASP offered the efficiency of ISAPI applications along with a new level of simplicity that made it easy to understand and use. However, ASP script was an interpreted script and consisted unstructured code and was difficult to debug and maintain. As the web consists of many different technologies, software integrationfor Web development was complicated and required to understand many different technologies. Also, as applications grew bigger in size and became more complex, thenumber of lines of source code in ASP applications increased dramatically and was hard to maintain. Therefore, an architecture was needed that would allow development of Web applications in a structured and consistent way.

The .NET Framework was introduced with a vision to create globally distributed software with Internet functionality and interoperability. The .NET Framework consists of many class libraries, includes multiple language support and a common execution platform. It's a very flexible foundation on which many different types of top class applications can be developed that do different things. Developing Internet applications with the .NET Framework is very easy. ASP.NET is built into this framework, we can create ASP.NET applications using any of the built-in languages.

Unlike ASP, ASP.NET uses the Common Language Runtime (CLR) provided by the .NET Framework. This CLR manages execution of the code we write. ASP.NET code is a compiled CLR code instead of  interpreted code (ASP). CLR also allows objects written in different languages to interact with each other. The CLR makes developement of Web applications simple.

Advantages Using ASP.NET

  • ASP.NET drastically reduces the amount of code required to build large applications
  • ASP.NET makes development simpler and easier to maintain with an event-driven, server-side programming model
  • ASP.NET pages are easy to write and maintain because the source code and HTML are together
  • The source code is executed on the server. The pages have lots of power and flexibility by this approach
  • The source code is compiled the first time the page is requested. Execution is fast as the Web Server compiles the page the first time it is requested. The server saves the compiled version of the page for use next time the page is requested
  • The HTML produced by the ASP.NET page is sent back to the browser. The application source code you write is not sent and is not easily stolen
  • ASP.NET makes for easy deployment. There is no need to register components because the configuration information is built-in
  • The Web server continuously monitors the pages, components and applications running on it. If it noticies memory leaks, infinite loops, other illegal software or activities, it seamlessly kills those activities and restarts itself
  • ASP.NET validates information (validation controls) entered by the user without writing a single line of code
  • ASP.NET easily works with ADO .NET using data-binding and page formatting features
  • ASP.NET applications run fater and counters large volumes of users without performance problems

Client-Side Scripting

Javascript and VBScript and generally used for Client-side scripting. Client-side scripting executes in the browser after the page is loaded. Using client-side scripting you can add some cool features to your page. Both, HTML and the script are together in the same file and the script is download as part of the page which anyone can view. A client-side script runs only on a browser that supports scripting and specifically the scripting language that is used. Since the script is in the same file as the HTML and as it executes on the machine you use, the page may take longer time to download.

Server-Side Scripting

ASP.NET is purely server-side technology. ASP.NET code executes on the server before it is sent to the browser. The code that is sent back to the browser is pure HTML and not ASP.NET code. Like client-side scripting, ASP.NET code is similar in a way that it allows you to write your code alongside HTML. Unlike client-side scripting, ASP.NET code is executed on the server and not in the browser. The script that you write alongside your HTML is not sent back to the browser and that prevents others from stealing the code you developed.

ASP.NET Features

ASP.NET is not just a simple upgrade or the latest version of ASP. ASP.NET combines unprecedented developer productivity with performance, reliability, and deployment. ASP.NET redesigns the whole process. It's still easy to grasp for new comers but it provides many new ways of managing projects. Below are the features of ASP.NET.

Easy Programming Model 

ASP.NET makes building real world Web applications dramatically easier. ASP.NET server controls enable an 
HTML-like style of declarative programming that let you build great pages with far less code than with classic ASP.  Displaying data, validating user input, and uploading files are all amazingly easy. Best of all, ASP.NET pages work in all browsers including Netscape, Opera, AOL, and Internet Explorer.

Flexible Language Options  

ASP.NET lets you leverage your current programming language skills.  Unlike classic ASP, which supports only interpreted VBScript and JScript, ASP.NET now supports more than 25 .NET languages (built-in support for VB.NET, C#, and JScript.NET), giving you unprecedented flexibility in your choice of language.

Great Tool Support 

You can harness the full power of ASP.NET using any text editor, even Notepad.  But Visual Studio .NET adds the productivity of Visual Basic-style development to the Web. Now you can visually design ASP.NET Web Forms using familiar drag-drop-doubleclick techniques, and enjoy full-fledged code support including statement completion and color-coding. VS.NET also provides integrated support for debugging and deploying ASP.NET Web applications. The Enterprise versions of Visual Studio .NET deliver life-cycle features to help organizations plan, analyze, design, build, test, and coordinate teams that develop ASP.NET Web applications.  These include UML class modeling, database modeling (conceptual, logical, and physical models), testing tools (functional, performance and scalability), and enterprise frameworks and templates, all available within the integrated Visual Studio .NET environment.

Rich Class Framework 

Application features that used to be hard to implement, or required a 3rd-party component, can now be added in just a few lines of code using the .NET Framework.  The .NET Framework offers over 4500 classes that encapsulate rich functionality like XML, data access, file upload, regular expressions, image generation, performance monitoring and logging, transactions, message queuing, SMTP mail, and much more. With Improved Performance and Scalability ASP.NET lets you use serve more users with the same hardware.

Compiled execution 

ASP.NET is much faster than classic ASP, while preserving the "just hit save" update model of ASP.  However, no explicit compile step is required. ASP.NET will automatically detect any changes, dynamically compile the files if needed, and store the compiled results to reuse for subsequent requests. Dynamic compilation ensures that your application is always up to date, and compiled execution makes it fast.  Most applications migrated from classic 
ASP see a 3x to 5x increase in pages served.

Rich output caching

ASP.NET output caching can dramatically improve the performance and scalability of your application. When output caching is enabled on a page, ASP.NET executes the page just once, and saves the result in memory in addition to sending it to the user.  When another user requests the same page, ASP.NET serves the cached result from memory without re-executing the page. Output caching is configurable, and can be used to cache individual regions or an entire page. Output caching can dramatically improve the performance of data-driven pages by eliminating the need to query the database on every request.

Web-Farm Session State

ASP.NET session state lets you share session data user-specific state values across all machines in your Web farm.  Now a user can hit different servers in the Web farm over multiple requests and still have full access to her session.  And since business components created with the .NET Framework are free-threaded, you no longer need to worry about thread affinity.

Enhanced Reliability

ASP.NET ensures that your application is always available to your users.

Memory Leak, DeadLock and Crash Protection 

ASP.NET automatically detects and recovers from errors like deadlocks and memory leaks to ensure your application is always available to your users.  For example, say that your application has a small memory leak, and that after a week the leak has tied up a significant percentage of your server's virtual memory. ASP.NET will detect this condition, automatically start up another copy of the ASP.NET worker process, and direct all new requests to the new process. Once the old process has finished processing its pending requests, it is gracefully disposed and the leaked memory is released. Automatically, without administrator intervention or any interruption of service, ASP.NET has recovered from the error.   

Easy Deployment

ASP.NET takes the pain out of deploying server applications. "No touch" application deployment. ASP.NET dramatically simplifies installation of your application. With ASP.NET, you can deploy an entire application as easily as an HTML page, just copy it to the server.  No need to run regsvr32 to register any components, and configuration settings are stored in an XML file within the application.

Dynamic update of running application 

ASP.NET now lets you update compiled components without restarting the web server. In the past with classic COM components, the developer would have to restart the web server each time he deployed an update.  With ASP.NET, you simply copy the component over the existing DLL, ASP.NET will automatically detect the change and start using the new code.

Easy Migration Path 

You don't have to migrate your existing applications to start using ASP.NET. ASP.NET runs on IIS side-by-side with classic ASP on Windows 2000 and Windows XP platforms. Your existing ASP applications continue to be processed by ASP.DLL, while new ASP.NET pages are processed by the new ASP.NET engine. You can migrate application by application, or single pages.  And ASP.NET even lets you continue to use your existing classic COM business components. 

XML Web Services 

XML Web services allow applications to communicate and share data over the Internet, regardless of operating system or programming language. ASP.NET makes exposing and calling XML Web Services simple. Any class can be converted into an XML Web Service with just a few lines of code, and can be called by any SOAP client.  Likewise, ASP.NET makes it incredibly easy to call XML Web Services from your application. No knowledge of networking, XML, or SOAP is required.

Mobile Web Device Support 

ASP.NET Mobile Controls let you easily target cell phones, PDAs and over 80 mobile Web devices. You write your application just once, and the mobile controls automatically generate WAP/WML, HTML, or iMode as required by the requesting device. 

What is ASP.NET?

Microsoft ASP.NET is a server side technology that enables programmers to build dynamic Web sites, web applications, and XML Web services. It is a part of the .NET based environment and is built on the Common Language Runtime (CLR) . So programmers can write ASP.NET code using any .NET compatible language.

Which is the latest version of ASP.NET? What were the previous versions released?

The latest version of ASP.NET is 4.0. There have been 3 versions of ASP.NET released as of date. They are as follows :

ASP.NET 1.0 – Released on January 16, 2002.

ASP.NET 1.1 – Released on April 24, 2003.

ASP.NET 2.0 – Released on November 7, 2005.

Additionally, ASP.NET 3.5 is tentatively to be released by the end of the 2007.

Explain the Event Life cycle of ASP.NET 2.0?

The events occur in the following sequence. Its best to turn on tracing(<% @Page Trace=”true”%>) and track the flow of events :

PreInit – This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.

Init – Each control in the control collection is initialized.

Init Complete* - Page is initialized and the process is completed.

PreLoad* - This event is called before the loading of the page is completed.

Load – This event is raised for the Page and then all child controls. The controls properties and view state can be accessed at this stage. This event indicates that the controls have been fully loaded.

LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.

PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.

PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.

SaveStateComplete* - In this event, the current state of the control is completely saved to the ViewState.

Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.

The events marked with * have been introduced in ASP.NET 2.0.

You have created an ASP.NET Application. How will you run it?

With ASP.NET 2.0, Visual Studio comes with an inbuilt ASP.NET Development Server to test your pages. It functions as a local Web server. The only limitation is that remote machines cannot access pages running on this local server. The second option is to deploy a Web application to a computer running IIS version 5 or 6 or 7.

Explain the AutoPostBack feature in ASP.NET?

AutoPostBack allows a control to automatically postback when an event is fired. For eg: If we have a Button control and want the event to be posted to the server for processing, we can set AutoPostBack = True on the button.

How do you disable AutoPostBack?

Hence the AutoPostBack can be disabled on an ASP.NET page by disabling AutoPostBack on all the controls of a page. AutoPostBack is caused by a control on the page.

What are the different code models available in ASP.NET 2.0?

There are 2 code models available in ASP.NET 2.0. One is the single-file page and the other one is the code behind page.

Which base class does the web form inherit from?

Page class in the System.Web.UI namespace.

Which are the new special folders that are introduced in ASP.NET 2.0?

There are seven new folders introduced in ASP.NET 2.0 :

\App_Browsers folder – Holds browser definitions(.brower) files which identify the browser and their capabilities.

\App_Code folder – Contains source code (.cs, .vb) files which are automatically compiled when placed in this folder. Additionally placing web service files generates a proxy class(out of .wsdl) and a typed dataset (out of .xsd).

\App_Data folder – Contains data store files like .mdf (Sql Express files), .mdb, XML files etc. This folder also stores the local db to maintain membership and role information.

\App_GlobalResources folder – Contains assembly resource files (.resx) which when placed in this folder are compiled automatically. In earlier versions, we were required to manually use the resgen.exe tool to compile resource files. These files can be accessed globally in the application.

\App_LocalResources folder – Contains assembly resource files (.resx) which can be used by a specific page or control.

\App_Themes folder – This folder contains .css and .skin files that define the appearance of web pages and controls.

\App_WebReferences folder – Replaces the previously used Web References folder. This folder contains the .disco, .wsdl, .xsd files that get generated when accessing remote web services.

Explain the ViewState in ASP.NET?

Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is the means of storing the state of server side controls between postbacks. The information is stored in HTML hidden fields. In other words, it is a snapshot of the contents of a page.

You can disable viewstate by a control by setting the EnableViewState property to false.

What does the EnableViewState property signify?

EnableViewState saves the state of an object in a page between postbacks. Objects are saved in a Base64 encoded string. If you do not need to store the page, turn it off as it adds to the page size.

There is an excellent article by Peter Bromberg to understand Viewstate in depth.

Explain the ASP.NET Page Directives?

Page directives configure the runtime environment that will execute the page. The complete list of directives is as follows:

@ Assembly - Links an assembly to the current page or user control declaratively.

@ Control - Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).

@ Implements - Indicates that a page or user control implements a specified .NET Framework interface declaratively.

@ Import - Imports a namespace into a page or user control explicitly.

@ Master - Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.

@ MasterType - Defines the class or virtual path used to type the Master property of a page.

@ OutputCache - Controls the output caching policies of a page or user control declaratively.

@ Page - Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.

@ PreviousPageType - Creates a strongly typed reference to the source page from the target of a cross-page posting.

@ Reference - Links a page, user control, or COM control to the current page or user control declaratively.

@ Register - Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control.

This list has been taken from here.

Explain the Validation Controls used in ASP.NET 2.0?

Validation controls allows you to validate a control against a set of rules. There are 6 different validation controls used in ASP.NET 2.0.

RequiredFieldValidator – Checks if the control is not empty when the form is submitted.

CompareValidator – Compares the value of one control to another using a comparison operator (equal, less than, greater than etc).

RangeValidator – Checks whether a value falls within a given range of number, date or string.

RegularExpressionValidator – Confirms that the value of a control matches a pattern defined by a regular expression. Eg: Email validation.

CustomValidator – Calls your own custom validation logic to perform validations that cannot be handled by the built in validators.

ValidationSummary – Show a summary of errors raised by each control on the page on a specific spot or in a message box.

How do you indentify that the page is post back?

By checking the IsPostBack property. If IsPostBack is True, the page has been posted back.

What are Master Pages?

Master pages is a template that is used to create web pages with a consistent layout throughout your application. Master Pages contains content placeholders to hold page specific content. When a page is requested, the contents of a Master page are merged with the content page, thereby giving a consistent layout.

How is a Master Page different from an ASP.NET page?

The MasterPage has a @Master top directive and contains ContentPlaceHolder server controls. It is quiet similar to an ASP.NET page.

How do you attach an exisiting page to a Master page?

By using the MasterPageFile attribute in the @Page directive and removing some markup.

How do you set the title of an ASP.NET page that is attached to a Master Page?

By using the Title property of the @Page directive in the content page. Eg:

<@Page MasterPageFile="Sample.master" Title="I hold content" %>

What is a nested master page? How do you create them?

A Nested master page is a master page associated with another master page. To create a nested master page, set the MasterPageFile attribute of the @Master directive to the name of the .master file of the base master page.

What are Themes?

Themes are a collection of CSS files, .skin files, and images. They are text based style definitions and are very similar to CSS, in that they provide a common look and feel throughout the website.

What are skins?

A theme contains one or more skin files. A skin is simply a text file with a .skin extension and contains definition of styles applied to server controls in an ASP.NET page. For eg:

<asp:button runat="server" BackColor="blue" BorderColor="Gray" Font-Bold ="true" ForeColor="white"/>

Defines a skin that will be applied to all buttons throughout to give it a consistent look and feel.

What is the difference between Skins and Css files?

Css is applied to HTML controls whereas skins are applied to server controls.

What is a User Control?

User controls are reusable controls, similar to web pages. They cannot be accessed directly.

Explain briefly the steps in creating a user control?

· Create a file with .ascx extension and place the @Control directive at top of the page.

· Included the user control in a Web Forms page using a @Register directive

What is a Custom Control?

Custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox.

What are the differences between user and custom controls?

User controls are easier to create in comparison to custom controls, however user controls can be less convenient to use in advanced scenarios.

User controls have limited support for consumers who use a visual design tool whereas custom controls have full visual design tool support for consumers.

A separate copy of the user control is required in each application that uses it whereas only a single copy of the custom control is required, in the global assembly cache, which makes maintenance easier.

A user control cannot be added to the Toolbox in Visual Studio whereas custom controls can be added to the Toolbox in Visual Studio.

User controls are good for static layout whereas custom controls are good for dynamic layout.

Where do you store your connection string information?

The connection string can be stored in configuration files (web.config).

What is the difference between ‘Web.config’ and ‘Machine.config’?

Web.config files are used to apply configuration settings to a particular web application whereas machine.config file is used to apply configuration settings for all the websites on a web server.

Web.config files are located in the application's root directory or inside a folder situated in a lower hierarchy. The machine.config is located in the Windows directory Microsoft.Net\Framework\Version\CONFIG.

There can be multiple web.config files in an application nested at different hierarchies. However there can be only one machine.config file on a web server.

What is the difference between Server.Transfer and Response.Redirect?

Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.

Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages.

Response.Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.

Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas Server.Transfer retains the original url in the browser. It just replaces the contents of the previous page with the new one.

What method do you use to explicitly kill a users session?

Session.Abandon().

What is a webservice?

Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.


 

 

 

 

 

 

 

Read more

ASP.NET Important Topics

December 29 2011 , Written by Balavardhan Reddy Published on #ASP.Net

1) Asp.net Page Life Cycle & Page Architecture.

2) Assemblies.

3) User Controls & Custom Controls.

4) Gridview Control.

5) Themes, Skins and Style Sheets.

6) Master Pages.

7) Site Maps.

8) State Management.

9) Security(Web.config)

    (Authentication & Authorization)

     i) Forms Authentication

    ii) Windows Authentication

    iii) Passport Authentication.

10) Caching

     - Output Caching

     - Data Caching

     - Fragment Caching.

Read more

.text { mso-number-format:\@;..."> Export Gridview data to Excel

February 18 2010 , Written by Balavardhan Reddy Published on #ASP.Net

i)  Get the Data from the Database and Bind it to the Gridview
ii) Set Gridview Allowpaging property to "False"

Write the below code to export the entire Gridview data to Excel sheet


 private void ExportGridView()
        {
                string style = @"<style> .text { mso-number-format:\@; } </style> ";
                string attachment = "attachment; filename=Contacts.xls";
                Response.ClearContent();
                Response.AddHeader("content-disposition", attachment);
                Response.ContentType = "application/ms-excel";
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
          
                // Create a form to contain the grid
                HtmlForm frm = new HtmlForm();
                VerificationTrackingGridView.Parent.Controls.Add(frm);
                frm.Attributes["runat"] = "server";
                frm.Controls.Add(VerificationTrackingGridView);
                frm.RenderControl(htw);

                Response.Write(style);
                Response.Write(sw.ToString());
                Response.End();

        }
Read more

Dotnet 3.5 New features

February 18 2010 , Written by Balavardhan Reddy Published on #ASP.Net

New Improvements in Dotnet 3.5 and VS 2008:
    Below is the queck summary lis of sever of new improvements of Dotnet 3.5, there is lot of more thing, I haven't had chance to add them

  • Multi Targetting
    • VS 2008 supports to create the applications with different Dotnet Framework versions, whenever you createting a New Project on VS 2008, it will shows you select the framework version for that project.
  • Rich Web Designer and CSS Support, Split view mode
    • To design a Web Page in VS 2005 have only 2 view modes i.e. Source (shows the HTML code) and Design (design mode of the Page). In the VS 2008 we have 3 view modes Source, Design and Split (like Dreamweaver software)
  • CSS style Manager
    •  VS 2008 supports a new tool window inside the IDE called "Manage Styles".  This shows all of the CSS stylesheets, and their corresponding rules, for the page you are currently editing.  It can be used both when you are in design-view, as well as when you are in source view on a page
  • Fullly Nested Master Page support
    • The good news is that VS 2008 fully supports nested master pages, and makes using them super easy.  Going forward I recommend that almost all ASP.NET projects should advantage of this feature - since it can add tremendous flexibility to the UI of your projects.
  • Javascript Intelisence
    • One of the things you'll notice immediately when you start typing within a script block is the richer support that Visual Studio 2008 now has for JavaScript keywords and language features
    • Obviously you get full intellisense support within external JavaScript files, just like you do within script blocks inside .htm and .aspx files.
  • Java script Debugging
    • One of the other JavaScript features that in VS 2008 is the much-improved support for JavaScript debugging.
      VS 2008 makes this much better by adding new support that allows you to set client-side JavaScript breakpoints directly within your server-side .aspx and .master source files
  • Creating Re-Usable ASP.NET AJAX Behaviors, Controls and Libraries
  • Automatic Properties
    • (get and set Properties), Object Initializers (set the Properties values), and Collection Initializers (List collection initialization)
    • One of the things that I think we will really love that are some of the new language features and improvements that are coming to both VB and C#.  These language changes are going to improve our development experience in both subtle and dramatic ways, and will really improve productivity and reduce the amount of code we need to type.
  • Extension Methods
    • Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type
    • Ex :
      public static class myclass
      {
          public static Dataview tablesort(Datatable dt, string sortcolumn, string sortdirection)
          {
              dt.DefaultView.sort = sortcolumn + " " + sortdirection
              return dt.DefaultView
          }
         
         Public bool emptyornot(string st_text)
         {
             if(st_text == "" || st_text == NULL)
                return false;
             else
               return true;
         }
      }

      public class mainclass
      {
          public void bindgrid()
          {
              DataTable dt = getdata();
              gv_details.Datasource = dt.tablesort(dt, ViewState["sortColumn"].ToString(), ViewState["sortDirection"].ToString());
              dv_details.Databind();
          }

          public void validate()
          {
               bool result = txtuname.emptyornot();
          }
      }

  • Lambda Expressions
    • Provide a complete functinal syntax of writing for anonymous methods, these are useful when writing LINQ expressions
    • Ex : Class :

      public class address
      {
          public string hno {get; set;}
          public string street{get; set;}
          public string city {get; set;}
          public int pinno {get; set;}
      }


      add data

      List <address> addresses = new List<address>
      {
          new address {hno = "18/a/1",street="3/1",city ="Hyd",pinno =500080}
          new address {hno = "10/s/3",street="2/a/1",city ="Hyd",pinno =500004}
          new address {hno = "102/r/1",street="5",city ="Secbad",pinno =500102}
      };


      IEnumerable<address> result = addresses.where(a => a.city == "Hyd");

      here (a => a.city == "Hyd") is Lamda Expression, using this Lamda expression to specify the filter to use when retriving the address
      In C# a lambda expression is syntactically written as a parameter list, followed by a => token, and then followed by the expression


      Query Syntax (LINQ : Language Integrated Query )

      It's declarative shorthand for expressing the queries using LINQ query operators. It offers a syntax that increases the readability and clarity of expressing query in the code, and it can be easy to read and write correctly.


      public class address
      {
          public string hno {get; set;}
          public string street{get; set;}
          public string city {get; set;}
          public int pinno {get; set;}
      }


      add data

      List <address> addresses = new List<address>
      {
          new address {hno = "18/a/1",street="3/1",city ="Hyd",pinno =500080}
          new address {hno = "10/s/3",street="2/a/1",city ="Hyd",pinno =500004}
          new address {hno = "102/r/1",street="5",city ="Secbad",pinno =500102}
      };


      Qury syntax to fetch the address which have city startwith "H" and also sort by pinno

      IEnumerable<address> result = from a in addresses
                      where a.city.Startswith("H")
                      Orderby a.pinno descending
                      select a;

      from the above code, that want to perform a "LINQ" query aginnext the addreee collection, so that we used ther parameter "a" to represent the each item of Address.

      public class newaddress
      {
          public string fuladdress {get; set;}
          public int pinno {get; set;}
      }

      IEnumerable<address> result = from a in addresses
                      where a.city.Startswith("H")
                      Orderby a.pinno descending
                      select new newaddress {
                      fuladdress  = a.hno +", "+ a.street +", "+a.city,
                      pinno = a.pinno};  
       
  • Anonymous Types
    • Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

      we've introduced the "var" keyword, we can start to use it to refer to anonymous types.

      var addresses = new {hno = "18-10/2", street="3/1",city="Hyd",pinno=500080 }

      when ever use the addresses. then the hno,street,city,pinno properties appeared autometically for the addresses. the type of these properties is Anonymous
Read more

Auto Complete TextBox with JQuery

November 26 2009 , Written by Balavardhan Reddy Published on #ASP.Net

Please find the Auto Complete Text box sample with JQuery and ASP.Net

http://files.myopera.com/Balu.narani/files/jqAutotext.rar

Read more

Change the Background Row Color of the GridView control using MouseEvents without postback

August 25 2009 , Written by Balavardhan Reddy Published on #ASP.Net

Change the Background Row Color of the GridView control using MouseEvents without postback


Change BackGround Color of a Row in Gridview when user moves mouse on a particular selecting Row, without postback.

You need write the code in RowDataBound Event of Gridview,

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

}



In this RowDataBound event add onmouseover and onmouseout Events.

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='blue'");

e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");

}



when the user Moves Mouseover or MouseOut on Gridview the Particular selecting Row on gridview changes the BackGround Color without postback.

--
Read more

How to Access ViewState Across Pages

August 25 2009 , Written by Balavardhan Reddy Published on #ASP.Net

Access ViewState Across Pages

We can access the viewstate variables across pages. This is possible when we use Cross Page Posting or Server.transfer to redirect the other pages

Ex :
Here I have created two aspx pages named:

   1. First.aspx: This page sets the ViewState variable and transfers the user to another page by using the Server.transfer.
   2. Second.aspx: This page accesses the ViewState variable of First.aspx page.

First.aspx :

public partial class First : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ViewState["Page1"] = "My First page";
        Server.Transfer("Second.aspx");
    }

    public StateBag FirstViewState()
    {
        return ViewState;
    }
}



StateBag class: This class is the primary storage mechanism for all HTML and Web server controls. It stores attribute/value pairs as strings associated with the control. It tracks changes to these attributes only after the OnInit method is executed for a page request, and saves the changes to the page's or control's viewstate.


Second.aspx :

public partial class Second : System.Web.UI.Page
{
    private StateBag firstPageViewstate
    {
        get
        {
            StateBag returnValue = null;
            if (PreviousPage != null)
            {
                Object objPreviousPage = (Object)PreviousPage;
                MethodInfo objMethod = objPreviousPage.GetType().GetMethod                                             ("FirstViewState");
                return (StateBag)objMethod.Invoke(objPreviousPage, null);
            }
            return returnValue;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null)
        {
            if firstPageViewstate != null)
            {
                Label1.Text = firstPageViewstate["Page1"].ToString();
            }
        }
    }
}



Using Previous Page, we can find the controls of the previous page. For example, one can access Label control placed in ViewStateContainer Page in current Page.




--
Read more

Execute particular javascript method only once, while Page onLoad only in an ASP.NET

August 5 2009 , Written by Balavardhan Reddy Published on #ASP.Net


We can execute Javascript method only once while asp.net page Loading only. We can validate the Asp.Net page IsPostBack event in Javascript method.
ASP.NET Master/Content Page scenario and have declared a javascript onload, then the script gets executed every on every postback.

However if you would like to execute it only once during the first postback, then here's how to do so:
write below code in MasterPage


<script type="text/javascript">

function invokeMeMaster() {

var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';

if (chkPostBack == 'false') {

alert('Only the first time');

}
}



window.onload = function() { invokeMeMaster(); };

</script>



The code determines if there is a postback in Javascript and then executes code based on the result. Hence the alert popup is shown only once.
Read more

Display an Image or Custom message for EmptyData in an ASP.NET GridView

August 5 2009 , Written by Balavardhan Reddy Published on #ASP.Net

Some times we will get Empty Dataset or Data table from the Database to bind the Gridview. At this point of time we can  display Custom message or an Image in GridView .

The GridView’s EmptyDataText property allows you display a message when there are no results returned from the GridView control’s data source.



Ex:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox ID="cb_chkall" runat="server" />
            </HeaderTemplate>
            <ItemTemplate>
                 <asp:CheckBox ID="cb_active" runat="server" />
            </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
             <ItemTemplate>
                  <asp:Label ID="lbl_msg" runat="server" text="Msg"></asp:Label>
              </ItemTemplate>
          </asp:TemplateField>
        
<asp:TemplateField>
             <ItemTemplate>
                  <asp:Label ID="lbl_Name" runat="server" text=
'<%#Eval("Name")%>'>                   </asp:Label>
              </ItemTemplate>
          </asp:TemplateField>
    </Columns>
    <EmptyDataTemplate>
       <Asp:Image id="img_nodata" AlternateText="No Records Found" runat="server"
        ImageURl="Images/nodata.jpg" />
    </EmptyDataTemplate>
</asp:GridView>





By the Above smaple, if there is no records in your Data Source, It can display nodata.Jpg image inside the GridView control




--
Read more

Display Alert or Tooltip text On MouseOver In an ASP.NET GridView

August 5 2009 , Written by Balavardhan Reddy Published on #ASP.Net


We can display a Alert message or Tool tip text in an ASP.NET GridView on MouseOver, to display these we needs to handle the RowDataBound event of GridView.

The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.

Ex:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox ID="cb_chkall" runat="server" />
            </HeaderTemplate>
            <ItemTemplate>
                 <asp:CheckBox ID="cb_active" runat="server" />
            </ItemTemplate>
         </asp:TemplateField>
         <asp:TemplateField>
             <ItemTemplate>
                  <asp:Label ID="lbl_msg" runat="server" text="Msg"></asp:Label>
              </ItemTemplate>
          </asp:TemplateField>
        
<asp:TemplateField>
             <ItemTemplate>
                  <asp:Label ID="lbl_Name" runat="server" text=
'<%#Eval("Name")%>'>                   </asp:Label>
              </ItemTemplate>
          </asp:TemplateField>

    </Columns>
</asp:GridView>

Row Data Bound Event

Displaying tootip text or Alert message when you placed mouse on Particular columns

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         CheckBox cb;
         Label lb;
         cb = (CheckBox)e.Row.FindControl("cb_active");
         lb = (Label)e.Row.FindControl("lbl_msg");

         cb.Attributes.Add("onmouseover", cb.ToolTip = "Check to add");
         lb.Attributes.Add("onmouseover", "alert('Show your Message here')");
               
      }
}



Displaying Alert Message when you placed mouse on Particular Row



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if ( e.Row.RowType == DataControlRowType.DataRow )
     {
          e.Row.Attributes.Add("onmouseover", "alert('Display some message');");
     }
}





--
Read more
1 2 3 4 > >>