6 February 2013

Custom Controls in Asp.net

Now we are going to discuss about how to create a custom web control in ASP.NET. 
How do we create and use them in ASP.NET web site application? As we know, a custom control is a control made by the user for a specific purpose and later we can use it in our application. 
In this article we are going to see how we can create and implement a custom web control. Now we are going to make a required valid Textbox value which checks that the Text box has the value or not, if not then it will give an error that it cannot not be empty. This web control will inherit from the Textbox web control, and will automatically add a required field validator at run-time. We will just define an Instance of the required field validator.
Let see how we create and use it:
Step 1: Now create a web server control application
  • First go to File->New->Project->ASP.NET Server Control
  • Name it as Valid Text box
takeservercontrol_app.gif
Step 2: Code of the Class to validate the Textbox's Text
Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ValidTextBox
{
  [DefaultProperty("ch")]
  [ToolboxData("<{0}:ValidTextBox1 runat=server></{0}:ValidTextBox1>")]
public class ValidTextBox1 : TextBox { 
   [Bindable(true)]
   [Category("Appearance")]
   [DefaultValue("")]
   [Localizable(true)]
public  string ch
 {
   get    {
     String s = (String)ViewState["ch"];
     return ((s == null) ? "[" + this.ID + "]" : s);
    }
   set    {
     ViewState["ch"] = value;
    }
  }
   private RequiredFieldValidator rfv;
   public string NotValid;
   public string C_Script = "true";
protected override void On_Init(EventArgs e)
    {
      rfv = new RequiredFieldValidator();
      rfv.ControlToValidate = this.ID;
      rfv.ErrorMessage = this.NotValid;
      rfv.EnableClientScript = (this.C_Script.ToLower() != "false");
      Controls.Add(rfv);
    }
protected override void RenderContents(HtmlTextWriter op)
  {
   op.Write(ch);
   base.RenderContents(op);
   rfv.RenderControl(op);
  } 
 }
}
Code Description : Here we are using a class name ValidTextBox1 which inherits from the Textbox Class. 
In this class we have to make some methods like On_init()  which shows how we create a instance of required field validator control. Now we see that the [DefaultProperty("ch")] which specify default attribute of the Control. 
Now we have to make the two property name as Not Valid and C_Script which are public and used to validate the text in the Text box and shows the script will be true. The [ToolboxData]  specifies the format string for the element. The string becomes the control's markup when the control is double-clicked in the toolbox or dragged from the toolbox onto the design surface.
Step 3: Now we have to add a namespace and an assembly information to the AssemblyInfo.cs file.
  • Firstly you have to add a namespace at the top of the page named as System.Web.UI.
  • Secondly you have to write an assembly at the end of the page given below.
 [assembly: TagPrefix("ValidTextBox","asp Sample")].
after_step-3.gif
Step 4: Now you have to build the project it will be build succeeded.
Step 5: Now open new file and project name it ASP.NET Website
after_step_5.gif
Step 6: Click Ok.
  • Now Right click on Solution Explorer and add Existing project
  • Now Right click on the Website project and add a reference
after_step_6.gif
Step 7: Now you will add a control to the Toolbox.
  • Go to the Toolbox
  • Right click on any Toolbox control and select Choose item
  • it will show a window with .NET Component
  • Add a component name as ValidTextBox1 it will look like below. 
after_step7.gif
Step 8: Now The Control will appear in the Toolbox as seen in the figure given below.
after_step_8.gif
Step 9: Now drag and drop the Custom control to the .aspx page and run it.
Output :
output.gif

Calling User - Defined Function in Stored Procedure

Creating a User-Defined Scalar Function in SQL Server
Now create a function named MultiplyofTwoNumber with the two parameters number1 and number2 returning one parameter named result. Both parameters have the same type, int. The function looks as in the following:
Create FUNCTION [dbo].[MultiplyofTwoNumber]
(
       @Number1 int,
       @Number2 int
)
RETURNS int
AS
BEGIN
       -- Declare the return variable here
       DECLARE @Result int
       SELECT @Result = @Number1 * @Number2;
       -- Return the result of the function
       RETURN @Result
END

Creating a Stored Procedure in SQL Server

A function can be called in a select statement as well as in a stored procedure. Since a function call would return a value we need to store the return value in a variable. Now creating a stored procedure which calls a function named MultiplyofTwoNumber; see:

Create PROCEDURE [dbo].[callingFunction]
(
@FirstNumber int,
@SecondNumber int
)
AS
begin
declare @setval int
select dbo.[MultiplyofTwoNumber](@FirstNumber, @SecondNumber)
end

Now, we can execute the procedure with duplicate values to check how to call a function from a stored procedure; see:

USE [registration]
GO
DECLARE  @return_value int
EXEC  @return_value = [dbo].[callingFunction]
       @FirstNumber = 3,
    @SecondNumber = 4

Microsoft .NET Framework 3.5 vs .NET Framework 4.0


.NET framework 3.5 and 4.0 are two versions of the Microsoft .NET framework. Microsoft always comes up with various applications and frameworks so that the application development is more advanced and enhanced. Microsoft .NET Framework is a framework which is designed for Windows operating system. It has a large library and supports various programming languages. It also supports interoperability and NET library is available to all programming languages which are supported by .NET. In year 2007, .NET 3.5 was released which had included more features that .NET 2.0 and .NET 3.0 could not stay in the industry for long time as it has various issues. However, .NET 4.0 was released in April 2010.
.NET 3.5 Framework

Microsoft .NET 3.5 Framework has various technologies which are able to help application developers solve the issues while developing applications. Some technologies were available in .NET 3.0 while some other technologies have been added in .NET 3.5. Some of the new technologies are mentioned as below:

 ASP.NET AJAX- The technology supports creation of web applications with much more advanced features. It is much easier for developers to develop AJAX applications.

 Language- Integrated Query- With the introduction of LINQ; the developers can create and maintain .NET Framework applications that can work well with the data.

 Windows Communication Foundation- In .NET 3.5 Framework, various challenges are addressed via Windows Communication Foundation (WCF) which is service-oriented approach.

.NET 4.0 Framework

.NET 4.0 Framework will work side by side along with older versions of .NET. The applications which run with older versions will continue to run with this version. In this version, there are new features that have been implemented are as follows:

• The CLR (Common Language Runtime) and Base Class Library (BCL) have been improved.

• New Numeric types and memory mapped files have also been introduced.

• Data Access and Modeling Improvements

• Enhancements in ASP.NET

• Improved Windows Presentation Foundation(WPF)

• Various dynamic features such as entity templates, new query filters and validation features.

• Task Parallel Support and Parallel Loop Support


.Net Framework 3.5 vs 4.0

           Difference between ASP.NET 3.5 and ASP.NET 4.0
ASP.NET 3.5
ASP.NET 4.0
Whether Client data can be directly accessed ?
In ASP.NET 3.5, the data from the client side cannot be directly accessed. The client side data can only be accessed using script manager’s Page methods,
interface named ICallbackEventHandler
or by using the component
XMLHttpHandler.
Whether Client data can be directly accessed ?
In ASP.NET 4, the data from the client side can be directly accessed using client data view and client data context objects.

Following methods are available in ASP.NET 4.0 to access Client data directly,
1) Client data controls
2) Client templates
3) Client data context
Whether we can set MetaTags (Keywords,Description) in the Page Directive?
In ASP.NET 3.5, two meta tags can be used, one with name as keywords and other with name as description to record the keywords and description for SEO purpose.

Please look atMetaTags for ASP.NET 3.5
Whether we can set MetaTags (Keywords,Description) in the Page Directive?
The meta keywords and meta
description is really useful for SEO
optimization of the web page. In
ASP.NET 4, the keywords and
description can be included as part of page directive itself.

Please look at MetaTags for ASP.NET 4.0
Whether ViewState can be applied at the Control level ?
ASP.NET 3.5 EnableViewState property cannot be used to apply ViewState at the Control level.It is mainly used at the page level.Its default value is True and its acceptable values ae True and False.
Whether ViewState can be applied at the Control level ?
In ASP.NET 4, ViewState mechanism is improved to set ViewState at the Contol level besides at the page level set by EnableViewState property in ASP.NET 3.5 .Its default value is Inherit and acceptable values areEnabled,Disabled and Inherit.
How ASP.NET 3.5 identifies ClientID ?
In ASP.NET 3.5, ClientId property has to be used to find the dynamically generated client id.
How ASP.NET 4.0 identifies ClientID ?
In ASP.NET 4, a property called
ClientIDMode is newly introduced to identify and record the ClientId easily.

ClientIDMode has following values.
AutoID – Same as ASP.NET 3.5
Static – There won’t be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control’s ID generation is the same as its parent. 


The default value of ClientIDMode for a page isPredictable. The default value of ClientIDMode for a control is Inherit. Because the default for controls isInherit, the default generation mode is Predictable.
Whether permanent redirection is possible or not ?
There is no RedirectPermanent() method available in ASP.NET 3.5.
Redirect method is less useful than the RedirectPermanent method. It will cause search engine results to be less current, and this can also impact performance because visitors will not be accessing the best URL. Redirect may be most useful for login pages or more complex situations.
Whether permanent redirection is possible or not ?
ASP.Net 4.0 introduced a new URL redirection method RedirectPermanent() which avoids round trips.

We can implement this as shown below:
RedirectPermanent("/newpath/newpage.aspx");
RedirectPermanent returns a 301 HTTP response—it redirects permanently to another location. Search engines such as Google and Bing will change their indexes to point to the new page directly. To call RedirectPermanent you will need to get the Response object from the HttpContext.
Then, you can call RedirectPermanent: if you pass false as the second parameter, you can perform further actions and avoid an exception.
Output Caching Enhancement:
OutPut Cache in ASP.Net 3.5 has a limitation - generated content always has to be stored in memory, and on servers that are experiencing heavy traffic, the memory consumed by output caching can compete with memory demands from other portions of a Web application.
Output Caching Enhancement:
ASP.NET 4 adds an extensibility point to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. This makes it possible to create custom output-cache providers for diverse persistence mechanisms, which can include local or remote disks, cloud storage, and distributed cache engines.

In order to know how to implement Custom Output Caching, please refer to the following URL,

QueryExtender Control for filtering the data returned by EntityDataSource and LinqDataSource controls:
There is no QueryExtender control available in ASP.NET 3.5 to filter the data returned by DataSource Controls( EntityDataSource and LinqDataSource).It has to explicitly use 'Where clause' in the data source.
QueryExtender Control for filtering the data returned by EntityDataSource and LinqDataSource controls:
QueryExtender Control is an add-on to the DataSource Controls: EntityDataSource and LinqDataSource. QueryExtender is used to filter the data returned by these controls. As the QueryExtender control relies on LINQ, the filter is applied on the database server before the data is sent to the page, which results in very efficient operations.

i.e., QueryExtender Control is intended to be used to create filters for data that is retrieved from a data source, without using an explicit Where clause in the data source. The control can be used to filter data in the markup of a Web page by using declarative syntax.

Please look at QueryExtender Control in ASP.NET 4.0

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.

5 February 2013

Reverse as string using for loop

using System;

namespace ProgramCall
{
    class StringReverse
    {
        static void Main()
        {

            string Str, Revstr = ""
            Console.Write("Enter A String : ");
            Str = Console.ReadLine();

            for (int i = Str.Length - 1; i >= 0; i--)
            {

                Revstr = Revstr + Str[i];
            }

            Console.WriteLine("Reverse  String  Is  {0}", Revstr);
            Console.ReadLine();
        }
    }
}