-->

Friday, April 18, 2014

Add months in existing date example in ASP.NET

Introduction

Using AddMonths method  you can add months in integer, Object will be updated with new date. This method is used where you want to calculate date after some months. Like Library management project. Lets take an simple example


<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
        runat="server"
        onclick="Button1_Click"
        Text="Click"
        BackColor="#99CCFF" />  
    </div>
        <asp:Label ID="Label1"
        runat="server"
        BackColor="Yellow"></asp:Label>
    </form>
CodeBhindeCode-
 protected void Button1_Click(object sender, EventArgs e)  
        {        
            DateTime now = DateTime.Now;        
            DateTime after3Months = now.AddMonths(3);
            Label1.Text = "now = " + now.ToLongDateString();
            Label1.Text += "<br /><br />after added 3 months to now= ";
            Label1.Text += after3Months.ToLongDateString();

        }
OutPut
 Add months in existing date example in ASP.NET

Example of Array.Copy ( ) method in ASP.NET

Introduction

If you want to run array until at specified position, you can simply use copy ( ) method. In this method define some parameters. Like array name, index where you want to start from,ending index etc.
<form id="form1" runat="server">

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click"
        BackColor="#99CCFF" />
    <div>  
        <asp:Label ID="Label1" runat="server" BackColor="Yellow"></asp:Label>  
    </div>
    </form>


Code behind code
 protected void Button1_Click(object sender, EventArgs e)
    {
        {
            string[] Fruits = new string[]
        {
            "Apple",
            "Banana",
            "Mango",
            "Orange",  
        };
            Label1.Text = "Fruits array: <br />";
            foreach (string s in Fruits)
            {
                Label1.Text += s + "<br />";
            }        
            int length = 3;          
            int index = 1;
            string[] copiedarray = new string[length];
            Array.Copy(Fruits, index, copiedarray, 0, length);
            Label1.Text += "<br /> New array from Fruits array [index no 1 to 3]:<br />";
            foreach (string s in copiedarray)
            {
                Label1.Text += s + "<br />";
            }
        }
OutPut-

Wednesday, April 16, 2014

Computer Programming : How to change data without postback in ASP.NET

News From Computer Programming: In ASP.NET you can't change the data without post-back, if you want to change data without post back, you can use AJAX technology. In previous article we have already learned more about AJAX like, How to install AJAX control Toolkit to the Toolbox or many more. Today we will learn How to update your GridView data in every seconds, for this you can use Timer control.
The Timer control is used for updating contents of the UpdatePanel control at predefined intervals. Single Timer control can refresh  more than one UpdatePanel control simultaneously. The Timer control  has an Interval property for defining the timer limit after which the content gets refreshed. When this interval limit gets over, the Tick event is raised . You can handle this event for updating the content values defined in the UpdatePanel control. The Timer control can be used either inside the UpdatePanel control or outside the UpdatePanel control. Now, let's try to understand the UpdatePanel control in both ways.

Timer control Inside the UpdatePanel Control

To use the Timer control inside the UpdatePanel control, drag and drop from the Toolbox as a sub-element of the <ContentTemplate>tag and follow the following steps:
1. Set the interval property of the Timer control as 1000 that equal to 1 second as it takes value in milliseconds.
2.Now, double-click the Timer control in design mode. It will generate event handler function in the code-behind file to handle the Tick event.

Timer Control Outside the UpdatePanel Control

You can use the Timer control outside the UpdatePanel control. This approach is appropriate when there are more than one UpatePanel control in the same Web page and you need to use same Timer control for all or some of them. To do so, you need to perform some changes in your application. However, these changes will not affect the output of your application. First, drag-and-drop the Timer control from the toolbox. Drop it after the ScriptManager control and before the UpdatePanel control; and configure its properties in the following way:
The ScriptManager Tag:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>


The Timer control outside the UpdatePanel control and after the ScriptManager Tag:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:Timer ID="Timer1" runat="server" Interval ="1000" OnTick ="Timer1_Tick"></asp:Timer>
Configure the UpdatePanel Control's <Triggers> Element for referencing the timer control in the following way:

   <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID ="Timer1" EventName ="Tick" />
            </Triggers>
        </asp:UpdatePanel>
Lets take a simple example to update GridView Data:
Step-1 : Add ScriptManager and UpdatePanel control after Form tag
Step-2 : Add Content template inside UpdatePanel Control.  
Step-3 : Add Timer control inside ContentTemplate with Tick event and Interval property.
Step-4 : Also add GridView control inside the Content Template.
Step-5 : Bind GridView Control in Tick event.
 Complete Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">



        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
       
       
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
           <ContentTemplate>



               <asp:Timer ID="Timer1" runat="server" Interval ="1000" OnTick ="Timer1_Tick"></asp:Timer>



               <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
                   <Columns>
                       <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
                       <asp:BoundField DataField="Name " HeaderText="Name " SortExpression="Name " />
                       <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                   </Columns>
               </asp:GridView>

               <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
           </ContentTemplate>
        </asp:UpdatePanel>
    <div>
   
    </div>
    </form>
</body>
</html>
Code File
 protected void Timer1_Tick(object sender, EventArgs e)
    {
        GridView1.DataBind();
    } 
Output
Computer Programming : How to update data, without postback
in above snap, if you change data in database table from server explorer, output affected on browser. 

How to make Custom error page in asp.net

If the error isn't properly handled anywhere ,it generates an ugly error message that your visitor will see -- you don't want this to happen

So add a custom error page to your site that your visitor will see in case an unhandled error happens. That page will politely ask the visitor to come back later.

Report the error once again , so the Administrator knows that this serious error gets to the visitor and needs to be taken care of as soon as possible.

Steps to follow for add custom error page:

  1. In Solution Explorer , Double-click web.config and add the following element as a child of the                     
<system.web>
      <customErrors mode ="RemoteOnly"  defaultRedirect ="errorpage.aspx" />

Note : If you want to handle errors using status code then specifies status code in <error> tag. Like

<customErrors mode ="On" defaultRedirect ="http://www.google.com">
      <error statusCode ="404" redirect ="errorpage.aspx"/>     
      
    </customErrors>


2. Add a new web form to your application's root , named errorpage.aspx . This form should not use a Master page , to make sure nothing gets in the way of displaying out simple error . The page also doesn't need a code-behind file

Note: After this change , remote clients will be forwarded to errorpage.aspx when unhandled exceptions are thrown ; however on the local machine you will still receive detailed error information . if you want to see the same error message as your visitors , set mode to On instead of RemoteOnly

3. Write some message into your errorpage.aspx like


<%@ Page Language="C#" %>

<!DOCTYPE html>


<script runat="server">


</script>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   Your requested generated an error message 
        we apolgize for the inconvenience.

    </div>

    </form>
</body>
</html>

4. Test your application by generating error 

How to make Custom webserver control in asp.net

How to make custom server control in asp.net
First draw picture of the custom server control in mind, after make custom control. Suppose we have a picture and we want to make server control of that picture.
Follow some steps for creating custom server control in asp.net

Step-1 : Open visual studio
Step-2:  Goto file-->new-->project-->select web in left pane-->select asp.net server control in middle pane
Step-3:  Write name of your project as 'customserver_control' and click on 'ok' button
Step-4:  After click on ok button you can see 'ServerControl1.cs' file is appear
Step-5:  Change  c# file name as 'customtextbutton' control
Step-6:  Remove this code, which is mentioned below from your c# file

[Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null)? "[" + this.ID + "]" : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(Text);
        }

Step-7: Replace your code with mentioned below code.
[ToolboxData("<{0}:customtextbutton runat=server></{0}:customtextbutton>")]
Note: class name or tag name are same

Step-8: Design CreateChildControls() override method in the class with some statements, which is mentioned below.
Step-9: Now,Your code look like

Label l1:
        TextBox User_txt;
Label l1;

protected override void CreateChildControls()
        {
                l1=new Label();
                l1.ID = "label1";
                l1.Text = "User_Name";
                User_txt = new TextBox();
                User_txt.ID = "usrtxt";
                User_txt.Text = string.Empty;
this.controls.add(l1);
this.controls.add(User_txt);


        }

Step-11: Take override  Render(HtmlTextWriter writer) method  for rendering the object onto the browser
Step-12: write this code inside this method
protected override void Render(HtmlTextWriter writer)
        {
            l1.RenderControl(writer);
            User_txt.RenderControl(writer);


        }

Step-13: Build this project

Now how to use .dll or .exe file in your web application

Step-1: click file-->new-->project-->selct web in left pane-->asp.net web form
Step-2: Right click on tool box and choose new item
Step-3: Browser your project .dll file and add your control onto your toolbox.

Monday, April 14, 2014

LINQ Partitioning operators in ASP.NET

Introduction

The Partitioning operators in LINQ are used to divide an input sequence into two sections, without rearranging the elements, and then returning the result set with one of the sections that satisfies the given condition. The Take, Skip, TakeWhile, and SkipWhile clauses are referred to as the Partitioning operators. The Take clause takes the elements up to a specified position in a sequence. The TakeWhile clause takes the elements based on the specified function until an element does not satisfy the given condition.
The syntax of the Take clause is:
For C#
public static IEnumerabIe<T> Take<T>( this IEnumerabIe<T> source, int count);
The syntax of the Skip clause is:
For C#
public static IEnumerable<T> Skip<T>( this IEnumerab!e<T> source, int count);

Let's take an simple example
<div>
    
        <asp:ListBox ID="ListBox1" runat="server" Height="134px" Width="197px">
        </asp:ListBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text=" Partitioning Operator Linq" />
    
    </div>

Code Behind code

protected void Button1_Click(object sender, EventArgs e)
    {
        string[] fruits = { "apple", "banana", "pineapple", "papaya", "blueberry", "cheery" };
        int size = 5;
        int pages = (int)Math.Ceiling(fruits.Count() / (double)size);
        for (int page = 0; page <pages; page++)
        {
            ListBox1.Items.Add("page " + page + ":");
            var names = (from p in fruits
                         orderby p descending
                         select p).Skip(page * size).Take(size);
            foreach (var name in names)
            {
                ListBox1.Items.Add(name);
            }
            
        }
             
    }
 Code Generate the following output
LINQ Partitioning operators in ASP.NET

How to Use ViewModel in Asp.Net MVC

ViewModel is used to specify the fields which may be required in create, edit or list the data on a strongly typed view. Asp.Net MVC uses these type of classes in which each field may contains specific validation rules using data annotations. These validation rules may be used for any type of data like DateTime, String or Integer.

Basically, Models are used to create database in Entity Framework and may be used to access database using the same name of classes. To differentiate the model with views programmer have to use ViewModel to interact view to make them strongly typed.

According to our previous article, Student Model have a list of field i.e. Id (primary key), name, age and city. In a view, we want to show only name and city then we have to create a view model with only these two fields and some validation rules like written below:

public class StudentViewModel
{
[Display(Name="Student Name")]
[Required(ErrorMessage="Name Required")]
public string Name { get; set; }

[Display(Name = "Student City")]
[Required(ErrorMessage = "City Required")]
public string City { get; set; }
}
Open our controller and write an action type of HttpGet with some line of code to return just a blank view model of type StudentViewModel.
public ActionResult StudentVM()
{
StudentViewModel svm = new StudentViewModel();
return View(svm);
}
Add a strongly typed view to select particular options listed in the below image:

How to Use ViewModel in Asp.Net MVC

The view page which is automatically creates as strongly typed, when run in the browser, have the display name for each field set in the ViewModel. When create button is clicked without any value, both of them show the error messages assigned previously in the ViewModel.

How to Use ViewModel in Asp.Net MVC

So ViewModels are used to organize and manage data in strongly typed view with more flexible way than other complex ways like Models or ViewBag etc.

© Copyright 2013 Computer Programming | All Right Reserved