Pages

Wednesday, 24 October 2012

Define Dependencies Between Cached Items

  • To add an item that has a dependency on a file to the cache
  1. You can add an item with a dependency to the cache by using the dependencies parameter in the Cache.Add or Cache.Insert method. The following example demonstrates using the Insert method to add an item with a dependency on an XML file to the cache:                           
    Visual basic
     
         Cache.Insert("MyData1", connectionString, new CacheDependency(Server.MapPath
("~\myConfig.xml")))
          C#
         Cache.Insert("MyData1", connectionString, new CacheDependency(Server.MapPath
("~\myConfig.xml")));
  • To add an item that has a dependency on another cache item to the cache
  1. You can also add an item that depends on another object in the cache to the cache,as shown in the following example:
       Visual Basic 
         Dim sDependencies As String(1)
         sDependencies(0) = "OriginalItem"
        Dim dependency As CacheDependency = New CacheDependency(Nothing, sDependencies)
        Cache.Insert("DependentItem", "This item depends on OriginalItem", dependency)
      C#
         string[] sDependencies = new string[1];
         sDependencies(0) = "OriginalItem";
         CacheDependency dependency = new CacheDependency(null, sDependencies);
        Cache.Insert("DependentItem", "This item depends on OriginalItem", dependency);

Saturday, 25 February 2012

Bind TreeView Control with an SqlDataSource in ASP.NET

       An exciting control included in the ASP.NET toolbox is the TreeView control.Because the TreeView can display only hierarchical data,it can be bound only to the XmlDataSource and SiteMapDataSource controls.The following code can bind a TreeView control to a SiteMapDataSource control to generate navigation for your page.
      < form id = " form1 " runat = " server " >
               <div>
                         < asp: TreeView ID="TreeView1" Runat="server"
                                    DtaSourceID="SiteMapDataSource1">
                         </asp:TreeView>
                         <asp:SiteMapDataSource ID="SiteMapDataSource1" Runat="server" />
                </div>
      </form>
                       
                                    

Thursday, 23 February 2012

Attaching SQL Server Cache Dependencies in ASP.NET

         In addition to changing settings in the OutputCache directive to activate SQL Server cache invalidation,you can also set the SQL Server cache invalidation programmatically,which can set as follows.
VB
Dim myDependency As SqlCacheDependency = New SqlCacheDependency("Nortwind","Customers")
Response.AddCacheDependency(myDependency)
Response.Cache.SetValidUtilExpires(true)
Response.Cache.SetExpires(DateTime.Now.AddMinutes(60))
Response.Cache.SetCacheability(HttpCacheability.Public)
C#
SqlCacheDependency myDependency = new SqlCacheDependency( " Northwind " , " Customers " ) ;
Response.AddCacheDependency( myDependency ) ;
Response.Cache.SetValidUntilExpires( true ) ;
Response.Cache.SetExpires(DateTime.Now.AddNinutes(60)) ;
Response.Cache.SetCacheability(HttpCacheability.Public) ;
         You first create an instance of the SqlCacheDependency object,assigning it the value of the database and the table at the same time.The SqlCacheDependency class takes the following parameters;
                 SqlCacheDependency ( databseEntryName As String,tablename As String)
         You use this parameter construction if you working with SQL Server 7.0 or with SQL Server 2000.If you working with SQL Server 2005 use the following;
                 SqlCacheDependency(sqlCmd As System.Data.SqlClient.SqlCommand)
         After the SqlCacheDependency class is in place ,you add the dependency to the Cache object and set some of the properties of the Cache object as well.You can do this either programmatically or through the OutputCache directive.

Tuesday, 21 February 2012

Programmatically Assign Master page in ASP.NET

        To accomplish this you have to use the Page.MasterPageFile property through Page_PreInit event.The Page_PreInit event is the earliest point in which you can access the Page lifecycle.For this reason,this is where you need to assign any master page that is used by any content pages.The Page_PreInit is an important event to make this,it can set as follows;
VB
Protected Sub Page_PreInit(ByVal sender As object,ByVal e As System.EventArgs)
       Page.MasterPageFile = "~/MyMasterPage.master" ;
End Sub
C#
protected void Page_PreInit(object sender , EventArgs e)
{
       Page.MasterPageFile = "~/MyMasterPage.master" ;
}

Enabling theame in the Entire application in ASP.NET

              In addition to apply an ASP.NET theme to your ASP.NET pages using the Theme attribute within the Page directive,you can alse apply it at an application level from the Web.config file .It can set as folows;

<?xml version = "1.0" encoding = "UTF-8" ?>
<configuration>
         <system.web>
                   <pages theme = "GalexyTheme" />
         </system.web>
</configuration>
              If you specify the theme in Web.Config file,you don't need to define the theme again in the Page directive of your ASP.NET pages.This theme is applied automatically to each and every page within your application

Show Current Date and Time in ASP.NET

            Developers generally like to include some of their own custom JavaScript function in their ASP.NET pages.You have a couple of ways to do this.The first is to apply JavaScript directly to the controls on your ASP.NET pages.For example,look at a simple Label control that displays current Date and Time on Page Load.
VB 
     Protected Sub Page_Load(ByVal sender As object,ByVal e As System.EventArgs)
           Label1.Text = DateTime.Now.ToString( ) ;
     End Sub
C#
     protected void Page_Load(object sender,EventArgs e)
     {
            Label1.Text = DateTime.Now.ToString( ) ;
     }
              This little bit of code displays the current date and time on the page of the end user.

Monday, 20 February 2012

Get ID of the Dynamicaly created Button in ASP.NET

      Let the dynamically calling function be Btn_Click,then the ID of the clicked button can use as like the following;
        protected void Btn_Click(object sender,EventArgs e)
        {
                //Assign the id to the string ButtonID
               string ButtonID = ((Button)sender).ID.ToString( ) ;
               //Set ID to Label1's Text property
               Label1.Text  = ButtonID.ToString( ) ;
        }

Dynamically adding Row To Table in ASP.NET(C# code)

The following code will create Rows dynamically in an ASP.NET table control,if this code is attached in a loop then that will create multiple rows,Try and enjoy the code
protected void Page_Load(object sender,EventArgs e)
{
       //Initializes new Table Row object
       TableRow tr = new TableRow( ) ;
       //Initializes new table Cell object
       TableCell fname = new TableCell( ) ;
       fname.Text = "hai" ;
       //Adds Cell to Row
       tr.Cells.Add(fname) ;
       TableCell lname = new TableCell( ) ;
       lname.Text = "how are you?" ;
       tr.Cells.Add(lname) ;
       //Adds Row to Table
       Table1.Rows.Add(tr) ;
}

ASP.NET Code To Implement a Login Process

LoginProcess
Login Pgae Default.aspx

First of all Import the SQL Client Fucnctions and Features using the following code
using System.Data.SqlClient ;
Add the follwing Code to set the Login Buttons Click Event function,that checks the UserName and password which you entered with the data in the database,if they are matching then the page get navigated into Welcome.aspx
//When the Login Button clicks ,then the following function clls and Execuits the process
protected void LoginBtn_Click(object sender, EventArgs e)
{
      string sp = ConfigurationManager.ConnectionStrings["ConnectDB"].ConnectionString ;
      string query = "SELECT * FROM Users WHERE id = @id AND pass = @pass " ;
      SqlConnection con = new SqlConnection ( sp ) ;
      SqlCommand cmd = new SqlCommand ( query , con ) ;
      con.Open ( ) ;
      cmd.Parameters.Add(new SqlParameter( "@id" , UsrNameTB.Text ) ) ;
      cmd.Parameters.Add(new SqlParameter( "@pass" , PasswordTB.Text ) ) ;
      SqlDataReader dr = cmd.ExecuitReader ( ) ;
      if( dr.Read( ) )
      {
              string id = dr[ "id" ].ToString( ) ;
              Response.Redirect( "Welcome.aspx?name="+id );
      }
      else
      {
               Label3.Text = "LoginFailed " ;
      }
}
If the login Process is a success then the page redirected io Welcome.aspx,In the Welcome.aspx the following code will set a welcome messege for the user who loged in.

protected void Page_Load(object sender, EventArgs e)
 {
             WelcomeLbl.Text = " Welcome: " + Request.QueryString[ "name" ].ToString( ) ;
 }



Count the Visitor level in ASP.NET using C# code

//Add the following call in Global.asax file
void application_start(object sender,EventArgs e)
{
       Application["vcount"] = 0;
}
void session_start(object sender,EventArgs e)
{
       Session["ucount"] = 0;
       Application.Lock( );
       Application["vcount"] = (int)Application["vcount"] + 1;
       Application.Unlock( );
       Session["ucount"] = Application["vcount"];
}
//Then add the following in the page Load part
protected void Page_Load(object sender, EventArgs e)

{
         Label1.Text = "You are Visitor No:" + Session["ucount"].ToString( ) ;
         Label2.Text = "Total Visitors:" + Application["vcount"].ToString( ) ;
 }

Using Alternative Coding Methods in ASP by C# Code


         When writing applications you have many ways to perform the same task. In some cases, performing the task in a particular way has a benefit. For example, if you use a specific approach, the code might run faster, be more reliable, or provide additional security. However,developers often use an approach to coding that’s simply comfortable or familiar.
           The btnLINQ_Click() event handler could use several different methods to obtain the same results—none of which is superior to any other. For example, instead of converting the outputto an array before displaying the message box, you could create the array directly as part of the LINQ statement like this:

private void btnLINQ_Click(object sender, EventArgs e)
{
              // Create the query.
              var Output = (from String TheEntry in TestArray select TheEntry.Substring(0, 3)).ToArray<String>();
              // Display one of the results.
              MessageBox.Show(Output[2]);
}

           This approach would work best if you need the array form of Output in several different places. In fact, you don’t have to convert Output to an array at all. You can use the ElementAt() method instead like this:

private void btnLINQ_Click(object sender, EventArgs e)
{
              // Create the query.
              var Output = from String TheEntry in TestArrayselect TheEntry.Substring(0, 3);
              // Display one of the results.
              MessageBox.Show(Output.ElementAt<String>(2));
}

This approach might be a little less readable than the approach used in the previous example,
but the results are precisely the same. The point is that all three methods work and it’s up to you to choose which method works best for you.





Adding Custom Web Server Control to a Page in ASP.NET

Creating a Custom Web Server Control
          The Custom Web server controls are classes,and they can be compiled into their own assemblies or included in a larger assembly with other controls and classes used by your application.
           One of the first steps in the development process  is to decide from which class you will derive your control.If the controil is very similar to an existing Web Server Control,such as a text box with some extra functionality,your control could inherit from that control.You typically override the Render method to modify the HTML that is sent to the browser.If your control will have entirely new functionality,you should derive it from the Control class
Adding Custom Web Control in Page
          To use a Web server control on a Web Page,add a <%@ Register  %> directive to the page,as in the following example:
   <%@ Register TagPrefix = " MySite " Namespace = " MySiteControls .Controls " %>
         Alternatively,you can register the control in the Web.Config file for the application,using the 
< control > tag.In this way ,you can register the control for all pages in the applicatio
< system.web >
        < pages >
                < controls >
                          < add tagPrefix = " MySite " Namespace = " MySiteControls .Controls " />
                </ controls >
        </ pages >
</ system.web >
         When the control is registered,it can be used on the Web page as like;
< MySite : ProductSelector  id = "ProductSelector1" runat = "server" />

Adding Client Script Dynamicaly in ASP.NET

If the client script depends on information that is available only at run time,you cannot add it declaratively at design time.For this situation, ASP.NET enables you to generate and render client side code at run time.To do this ,use the System.Web.UI.ClientScriptManager class.The following example adds a script that will execute in the browser when the user attempts to submit the form back to the Web Server.

VB
Sub page_Load( )
       Dim scriptText As String
       scriptText = "return Confirm('Do you want to submit the page? ')"
       ClientScript.RegisterOnSubmitStatement(Me.GetType( ). _
              ConfirmSubmit , scriptText)
End Sub

C#
void Page_Load( )
{
       String scriptText = "return confirm('Do you want to submit the page?')" ;
       ClientScript.RegisterOnSubmitStatement(this.GetType( ),ConfirmSubmit , scriptText ) ;
}

Saturday, 18 February 2012

Enabling Users to Personalize Themes in ASP.NET 2.0

You can use themes to enable the users to further personalize your application.If you store the name of the preffered theme for user in the user's ASP.NET profile,you can programatically set this theme as each page loads.You must set the theme during the Page_PreInit event handler or earlier,
VB
Sub Page_preInit(ByVal sender As Object , _ByVal e As System.EventArgs) _
            handles Me.PreInit
       Page.Theme = Profile.PreReferredTheme
End Sub
C#
void Page_PreInit(object sender , EventArgs e)
{
           Page.Theme = Profile.PreReferredTheme ;
}

Updating the Configuration for a Web Application in ASP.NET 2.0

            After You have opened a configuration file,you can query the various sections of the file,change their properties,and modify configuration values.You can use the Save method to write changes back to the configuration file.The following example shows how to enable the debug featuer

VB


Dim compilation as System.Web.Configuration.CompilationSection
compilation = CType(config.GetSection( " system.web/compilation " ). _
    System.Web.Configuration.CompilationSection )
compilation.Debug  = True
compilation.Save( )

C#


System.Web.Configuration.CompilationSection compilation ;
compilation  = config.GetSection ( " system.web/compilation " ) as
        System.Web.Configuration.CompilationSection ;
compilation.Debug = true ;
compilation.Save( ) ;

ASP.NET code for Uploading the file content into a stream object

               One nice feature of the FileUpload control is that it not only gives you the capability to save the file to disk,but it also lets you place the contents file into a Stream object.You do this by using the FileContent property as ;

VB
Dim myStream As System.IO.Stream
myStream = FileUpload1.FileContent

C#
System.IO.Stream myStream ;
myStream = FileUpload1.FileContent ;

                 In thios short example,an instance of the Stream object is created.Then,using the FileUpload control's FileContent property,the content of the uploaded file is placed into the object.This is possible because the FileContent  property returns a Stream object.

ASP.NET Code ForChanging File-Size Limitations In web.config file

           The end users might never encounder an issue with the file upload process in your application,but you should be aware that some limitations exist.When users work through the process of uploading files,a size restriction is actually sent to the server for uploading.The default size limitation is 4MB(4096kb),the transfer fails if a user tries to upload a  file that that is larger than 4096kb.
            The default allowable file size is dictated by the actual request size permitted to the Web Server(4096kb).You can change this setting in the web.config file like as shown below,

< httpRuntime
    idleTime = "15 "
    executionTimeout = " 90 "
    maxRequestLength = " 4096 "
    useFullyQualifiedRedirectUrl = " False "
    minFreeThreads = " 8 "
    minLocalRequestFreeThreads = " 4 "
    appRequestQueueLimit = " 100 "
/>
          You can do a lot with the < httpRuntime > section of the web.config file , but two properties - the maxRequestLength and executionTimeout properties are interesting.

Friday, 17 February 2012

Upload file using the new FileUpload control in ASP.NET

          In ASP.NET you could upload files using the HTML FileUpload server control.This control put an <input type = " file " > element on your Web page to enable the end user to upload files to the server.To use the file ,however,you had to make a couple of modifications to the page.For example , you were required to add enctype = " multipart/form-data " to the page's <form> element.
           ASP.NET introduces a new FileUpload server control that makes the process of uploading files to a server even simpler.When giving a page the capability to upload files ,you simplay include the new < asp : FileUpload > control and ASP.NET thake care of the rest,including adding the enctype attribute to the page's < form > element
The following code shows the Uploading files using the new FileUpload control

VB


<script runat = " server ">
          protected Sub Button1_Click( ByVal sender As object , ByVal e As System.EventArgs )
                  if FileUpload1.hasFile Then
                         Try
                                 FileUpload1.SaveAs (" C:\Uploads\" & _
                                        FileUpload1.FileName )
                                 Label1.Text = "File Name: " & _
                                        FileUpload1.PostedFile.FileName & "<br>" & _
                                        "File Size: " & _
                                        FileUpload1.PostedFile.ContentLength & " kb<br> " & _
                                        "Content type : " & _
                                        FileUpload1.PostedFile.ContentType
                          Catch ex As Exception
                                 Label1.Text = "ERROR: " & ex.Message.ToString( )
                           End Try
                   Else
                            Label1.Text = "You have not specified a file. "
                    End If
           End Sub
</script>

< html xmlns = "http:/www.w3.org/1999/xhtml " >
< head runat  = "server " >
         < title > FileUpload Server control </ title >
</ head >
< body >
         < form id = "form1" runat = "server" >
                 < asp : FileUpload ID = "FileUpload1" Runat = "server" />
                 p >
                 < asp : Button  ID = "Botton1"  Runat  = "server"  Text  = "Upload"
                            OnClick  = "Button1_Click" />
                 < / p >< p >
                 < asp : Label  ID = " Label1 " Runat  = "server" ></ asp : Label ></ p
          </ form >
</ body >
</ html




C#


< script runat = "server " >
          protected void Button1_Click(object sender, EventArgs e)
          {
                      if (FileUpload1.HasFile )
                      {
                              try
                              {
                                      FileUpload1.SaveAs( "C:\\Uploads\\" + FileUpload1.FileName);
                                      Label1.Text = "File Name: " + FileUpload1.PostedFile.FileName + "<br>" +                      
                                              FileUpload1.PostedFile.ContentLength + "kb<br>" + "Content Type: " +                              
                                              FileUpload1.PostedFile.ContentType;
                               }
                               catch (Exception ex)
                               {
                                        Label1.Text = "ERROR:" + ex.Message.ToString();
                                }
                       }
                       else
                       {
                               Label1.Text = "You hav not specified a file";
                        }
           }
</ scripts >

ASP.NET code to Control how a day is rendered in a calender (C# Code)

Day Render is used to set the speciality of the day in a calender...in order to remember a perticular day,or as a reminder for the day,Hope this cod may helpfull to you...
protected void Calender1_DayRender(object sender, DayRenderEventArgs e)
{
         e.Cell.VerticalAlign = VertivcalAlign.top ;
         if ( e.Day.DayNumber.Text = = " 25 " )
         {
                e.Cell.Controlls.Add ( new LiteralConrol ( "<p>User Group Meeting </p>" ) ) ;
                e.Cell.BorderColor  = System.Drawing.Color.Black ;
                e.BorderWidth = 1 ;
                e.Cell.BorderStyle = BorderStyle.Solid ;
                e.Cell.BackColor = System.Drawing.Color.LightGray ;
         }
}

Dynamicaly generate DropDownList Control from Array(C# Code)

Here is a block of C# code which generates DropDownList control from an array when the button clicks.

protected void Button1_Click(object sender,EventArgs e)
{
        //Defines car Array
        string CarArray = new string { "Ford" , "Honda" , "BMW" , "Maruthi" };
        //Defines car AirplaneArray
        string AirplaneArray = new string { " Boing 777 " , " Boing 747 " , " Boing 737 " };
        //Defines car  Train Array
        string TrainArray = new string { " Bullet Train" , " Amtrack " , " Tram " };
        if ( DropDownList1.SelectedValue = =  "Car" )
        {

               //Sets CarArray as datasource

               DropDownList2.DataSource = CarArray ;
        }
        else if (DropDownList1.SelectedValue = = "Airplane" )
        {
                //Sets AirplaneArray as datasource
                DropDownList2.DataSource = AirplaneArray ;
        }
        else
        {
               //Sets  TrainArray Array as datasource
               DropDownlList2.DataSource = TrainArray ;
        }
        //Binds the datasource with the control and generate the dropdown list
        DropDownList2.DataBind( );
        DropDownList2.Visible = true ;
}

ASP Code to Make a Database Connection(C# code.)

In order to make a database Connection First of all we need to set Connection string,Here the connection may set by a connection string or by the database name..And a query which retrieves the data from the databse or send data to the tables in the databse,The following code estblishes such an example for databse connectivity in  ASP.NET 2.0 usin C# code..

using System.Data.SqlClient ;

protected void Page_Load(object sender, EventArgs e)
{
        //Establishes Dtabse Connection in a string 
        string sp1  = ConfigurationManager.ConnectionStrings[ "ConnectionString" ].ConnectionString ;
        //Connects to the Server database
        SqlConnection con  =  new SqlConnection(sp1) ;
        //Openss the Connection
        con.Open();
        //Sets the Query to fetch data from databse,this may insert,delete or update query
        string query  =  "select * from maintable where name='alfred'" ;
        SqlCommand cmd  =  new SqlCommand(query, con) ;
        //If the query is reader then SqldataReader,if update or delete then it must be DataAdapter and                      
        statement become cmd.ExecuitNonQuery
        SqlDataReader dr  =  cmd.ExecuteReader() ;
        if(dr.Resd())
        {
               Label1.Text  =  "success" ;
        }
        else
        {
               Label1.Tex t  =  "failed" ;
         }
 }


Tuesday, 31 January 2012

Changing the ImageUrl property dynamicaly in ASP.NET

The Image server control enables you to work with the images that appears on your Web Page
from the server side code .It's a simple server control,but it can giv you the power to determine
how your images are displayed on the browser screen.A typical image control is constructed in the following manner.
<asp:Image ID="Image1" Runat="server" ImageUrl="~/MyImage1.gif" />
The following example shows how to change the ImageUrl property of the image control dynamicaly.
VB
<script runat="server">
   Protected Sub Button1_Click(ByVal sender As Object ,ByVal e As System.EventArgs)
                Image1.ImageUrl="~/MyImage2.gif"
   End Sub
</script>
C#
protected void Button1_Click(object sender , EventArgs e)
{
        Image1.ImageUrl = "~/MyImage2.gif ";
}
            

Adding Items to ListBox Control in ASP.NET

To add items to the collection,the following synatax can be usefull
        ListBox1.Items.Add(TextBox1.Text);
You can also add instances of the ListItem object to get different values for the item name and value
VB
    ListBox1.Items.Add(New ListItem("Olivine","MG2SI04"));
C#
    ListBox1.Items.Add(New ListItem("Olivine","MG2SI04"));
The example adds a new instance of the ListItem object,adding not only the textual name of the item,but the
value of the item.It produces the following results in the browser:
          <option value="MG2SI04">Olivine</option>

ASP.NET(C#) code to change the unique identifier of the anonymous User

//Code that change the Unique identification of the anonymous user is like the code below..try this..

public void AnonymousIdentification_OnCreate(object sender, AnonymousIdentificationEventArgs e)
    {
        e.AnonymousID = "Bubbles" + DateTime.Now();
    }