Wednesday, June 15, 2011

Maintaining Browser History for Ajax events through script manager in asp.net

In one of our project we have requirement of maintaining history of Ajax events. After doing some search on the web I have found one interesting capabilities of Script Manager control. I have found that there is one property called “EnableHistory” which will enable history for all the Ajax Event for which you have created the History Point. So Let’s first take a simple example with Ajax Tab and we are maintaining history of tab Navigation. To add the Ajax tab we first need the AjaxToolKit. So I have download the AjaxToolKit and Added Reference to my project like below.

Reference

Once I have done with adding reference I have written some asp.net HTML code to create Three tab and Also added a script manager like following which Enable history =”true” property and Navigate event. Like following.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
 CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
 <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
 <asp:ScriptManager id="scriptManager" runat="server" EnableHistory="true" OnNavigate="scriptManager_Navigate">
 </asp:ScriptManager>
 <asp:UpdatePanel ID="updatePanelTab" runat="server" ChildrenAsTriggers="true">
     <ContentTemplate>
         <asp:TabContainer ID="ajxTab" runat="server" ActiveTabIndex="0"  AutoPostBack="true" OnActiveTabChanged="ajxTab_ActiveTabChanged">
 <asp:TabPanel ID="homTab" runat="server" HeaderText="home" >
                     <ContentTemplate>
                         Home
                     </ContentTemplate>
 </asp:TabPanel>
  <asp:TabPanel ID="aboutUsTab" runat="server" HeaderText="About us" >
                     <ContentTemplate>
                         About Us
                     </ContentTemplate>
 </asp:TabPanel>
  <asp:TabPanel ID="contactUsTab" runat="server" HeaderText="Contact us" >
                     <ContentTemplate>
                         Contact us
                     </ContentTemplate>
 </asp:TabPanel>
 </asp:TabContainer>
     </ContentTemplate>
 </asp:UpdatePanel>

</asp:Content>

Here in the above Code I have created Three tabs Home,About us and Contact us and I have putted that in update panel and Also I have enabled “Autopostback” to true so whenever tab will be changed it will post back the page. So now let us do the server side part. Here I have written code in two events. First one is from the script manager navigate event which will fire when we navigate pages thorough browser history and another one is the ActiveTabChanged event which will fire when we change Tab. In Script manager navigate I have written code to select tab based on the state from navigate event. In ActiveTabchanged event I have written code to create navigation history point which will register that in browser history. Following is the code for that.

using System;
using System.Web.UI;

namespace WebApplication2
{
 public partial class _Default : System.Web.UI.Page
 {
     protected void scriptManager_Navigate(object sender, HistoryEventArgs e)
     {
         string state = e.State["historyPoint"];
         ajxTab.ActiveTabIndex = Convert.ToInt32(state);
     }

     protected void ajxTab_ActiveTabChanged(object sender, EventArgs e)
     {
        if(scriptManager.IsInAsyncPostBack && !scriptManager.IsNavigating)
        {
            scriptManager.AddHistoryPoint("historyPoint",ajxTab.ActiveTabIndex.ToString(),ajxTab.ActiveTab.HeaderText);
        }
     }
 }
}
So code is completed now lets run the application and Check it in browser. It will be loaded like below.
WithoutHistory

Now once you browse page with some tab you can see history is enabled in browser and you can go back and forward with browser navigations like following.

AfterHistory

So that’s it. Isn’t that cool? Stay tuned for more.. Hope you liked it. Till that Happy programming.

Shout it
kick it on DotNetKicks.com
Share:
Thursday, June 9, 2011

Finding Saturday,Sunday between date range in C#/ASP.NET

I know this post will sound basic to some of the people. But yesterday one of my reader asked me this question. So I decided to write this blog post . So lets first create a console application which will find the Saturday,Sunday between two dates just like following.

DateTimeConsoleApplication

Once you are ready with Console application. You need to write following code in that to find and print Saturday and Sunday between particular date range.

using System;

namespace DatimeApplication
{
   class Program
   {
       static void Main(string[] args)
       {
             DateTime startDate=new DateTime(2011,3,1);
             DateTime endDate = DateTime.Now;

             TimeSpan diff = endDate - startDate;
             int days = diff.Days;
             for (var i = 0; i <= days; i++)
             {
                 var testDate = startDate.AddDays(i);
                 switch (testDate.DayOfWeek)
                 {
                     case DayOfWeek.Saturday:
                     case DayOfWeek.Sunday:
                         Console.WriteLine(testDate.ToShortDateString());
                         break;
                 }
             }
           Console.ReadLine();
       }
   }
}
As you can see in above code I am finding Saturday and Sunday between 1st March 2011 and today. So I have taken two variables called startDate and endDate. After that I have got difference between them and then via for loop I am checking that day of week is Saturday or Sunday then I am printing that. Now lets run the application and lets check browser and Here you can see below output as expected.

Output

So as you can see it is very Easy. You can find any weekday that way. Hope you liked it. Stay tuned for more..

Shout it

kick it on DotNetKicks.com
Share:
Saturday, May 21, 2011

Delete with Dapper ORM and ASP.NET MVC 3

I have been writing few posts about Dapper ORM and ASP.NET MVC3 for data manipulation. In this post I am going to explain how we can delete the data with Dapper ORM. For your reference following are the links my previous posts.

Playing with dapper Micro ORM and ASP.NET MVC 3.0
Insert with Dapper Micro ORM and ASP.NET MVC 3
Edit/Update with dapper ORM and ASP.NET MVC 3

So to delete customer we need to have delete method in Our CustomerDB class so I have delete method into the CustomerDB class like following.

public bool Delete(int customerId)
{
try
{
    using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
    {
        sqlConnection.Open();
        string sqlQuery = "DELETE FROM [dbo].[Customer] WHERE CustomerId=@CustomerId";
        sqlConnection.Execute(sqlQuery, new {customerId});
        sqlConnection.Close();

    }
    return true;
}
catch (Exception exception)
{
    return false;
}
}
Now our delete method is ready It’s time to add ActionResult for Delete in Customer Controller like following. I have added two Action Result first will load simple delete with view and other action result will delete the data.
public ActionResult Delete(int id)
{
var customerEntities = new CustomerDB();
return View(customerEntities.GetCustomerByID(id));
}

//
// POST: /Customer/Delete/5

[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
    var customerEntities = new CustomerDB();
    customerEntities.Delete(id);
    return RedirectToAction("Index");


}
catch
{
    return View();
}
}
Now It’s time to add delete view. So I have added strongly typed view like following.

DeleteView

Now everything is ready with code. So it’s time to check functionality let’s run application with Ctrl + F5. It will load browser like following.

ViewBeforeDelete

Now I am clicking on delete it will load following screen to confirm deletion.

DeleteConfirmation

Once you clicked delete button it will redirect back to customer list and record is delete as you can see in below screen.

ViewAfterDelete

So that’s it. Its very easy.. Hope you liked it.. Stay tuned for more..

Shout it
kick it on DotNetKicks.com
Share:
Friday, May 20, 2011

Edit/Update with dapper ORM and ASP.NET MVC 3

In last two post I have already written about Getting data and adding data with Dapper Micro ORM. In this post I will explain how we can use the dapper ORM for data update. For reference following is the two post links for the Dapper ORM Series.
Playing with dapper Micro ORM and ASP.NET MVC 3.0
Insert with Dapper Micro ORM and ASP.NET MVC 3
Now as you we have already created CustomerDB Class. In this database operation class we will add two more methods GetCustomerById and Update to get Customer based on CustomerId passed and another one is for updating data. Following is modified Customer DB Code.
public class CustomerDB
{
  public string Connectionstring = @"Data Source=DotNetJalps\SQLExpress;Initial Catalog=CodeBase;Integrated Security=True";

  public IEnumerable<Customer> GetCustomers()
  {
      using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
      {
          sqlConnection.Open();
          var customer = sqlConnection.Query<Customer>("Select * from Customer");
          return customer;

      }
  }

  public Customer GetCustomerByID(int customerId)
  {
      using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
      {
          sqlConnection.Open();
          string strQuery = string.Format("Select * from Customer where CustomerId={0}", customerId);
          var customer = sqlConnection.Query<Customer>(strQuery).Single<Customer>();
          return customer;

      }
  }
  public bool Update( Customer customerEntity)
  {
      try
      {
          using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
          {
              sqlConnection.Open();
              string sqlQuery = "UPDATE [dbo].[Customer] SET [FirstName] =@FirstName, [LastName] =@LastName,[Address] =@Address,[City] = @City WHERE CustomerId=@CustomerId";
              sqlConnection.Execute(sqlQuery, new {
                                                      customerEntity.FirstName, customerEntity.LastName, customerEntity.Address, customerEntity.City, customerEntity.CustomerId
                                          });
              sqlConnection.Close();

          }
          return true;
      }
      catch (Exception exception)
      {
          return false;
      }
  }
  public string  Create(Customer customerEntity)
  {
      try
      {
          using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
          {
              sqlConnection.Open();
           
              string sqlQuery = "INSERT INTO [dbo].[Customer]([FirstName],[LastName],[Address],[City]) VALUES (@FirstName,@LastName,@Address,@City)";
              sqlConnection.Execute(sqlQuery,
                                    new
                                        {
                                            customerEntity.FirstName,
                                            customerEntity.LastName,
                                            customerEntity.Address,
                                            customerEntity.City
                                        });

             
              sqlConnection.Close();

          }
          return "Created";
      }
      catch (Exception ex)
      {
          return ex.Message;
      }

  }

}


Now It’s time to modify Customer Controller. I have added two more Action Result Result like following. One for fetching data and populating view and then another one for the updating data and redirecting it to Index action result. Just like following.
public ActionResult Edit(int id)
{

 var customerEntities = new CustomerDB();
 return View(customerEntities.GetCustomerByID(id));
}

//
// POST: /Customer/Edit/5

[HttpPost]
public ActionResult Edit( Customer customer)
{
 try
 {
     // TODO: Add update logic here
     var customerEntities = new CustomerDB();
     customerEntities.Update(customer);
     return RedirectToAction("Index");
 }
 catch
 {
     return View();
 }
}
So now our ActionResult is also ready now let’s add time to add Edit View for displaying current edit data. So go edit action result and right click->Add View-> Popup will appear for that. Now let’s create a strongly typed view like following.

EditView
So now we have created view and all other stuff its time to run our application. Let’s run it and go to Customer View like following.

View
Now I am going to click edit and above data will filled in Edit View.

Edit
Now After modifying data I have clicked save and as you can see in below screen data is modified.

ModifiedView
So that’s it. It’s very easy. Stay tuned for more.. Hope you liked it..

kick it on DotNetKicks.com
Shout it
Share:
Thursday, May 19, 2011

Insert with Dapper Micro ORM and ASP.NET MVC 3

As I have already posted about the how to fetch data in my earlier post for Dapper ORM. In this post I am going to explain how we can insert data with the dapper ORM. So let’s extend the earlier post project. As explained in earlier post I have already created a class called CustomerDB this class will contains all the operation with Dapper Micro ORM. So For inserting data let’s first create CREATE method like following in CutomerDB Class like following. In that I have create a simple Insert Query in string and then using connection.execute method to execute method. Following is code for that.
public class CustomerDB
{
  public string Connectionstring = @"Data Source=DotNetJalps\SQLExpress;Initial Catalog=CodeBase;Integrated Security=True";

  public IEnumerable<Customer> GetCustomers()
  {
      using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
      {
          sqlConnection.Open();
          var customer = sqlConnection.Query<Customer>("Select * from Customer");
          return customer;

      }
  }

   
  public string  Create(Customer customerEntity)
  {
      try
      {
          using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
          {
              sqlConnection.Open();
           
              string sqlQuery = "INSERT INTO [dbo].[Customer]([FirstName],[LastName],[Address],[City]) VALUES (@FirstName,@LastName,@Address,@City)";
              sqlConnection.Execute(sqlQuery,
                                    new
                                        {
                                            customerEntity.FirstName,
                                            customerEntity.LastName,
                                            customerEntity.Address,
                                            customerEntity.City
                                        });

              sqlConnection.Execute(sqlQuery);
              sqlConnection.Close();

          }
          return "Created";
      }
      catch (Exception ex)
      {
          return ex.Message;
      }

  }

}
Now we are ready with Create Method for database now let’s create two ActionResult for the Creating customer like following in Customer Controller like following.
public ActionResult Create()
{
return View();
}

//
// POST: /Customer/Create

[HttpPost]
public ActionResult Create(Customer customer)
{
try
{
    // TODO: Add insert logic here
    var customerEntities = new CustomerDB();
    customerEntities.Create(customer);
    return RedirectToAction("Index");
}
catch
{
    return View();
}
}
Now we are ready with the both ActionResult. First ActionResult will return simple view of Create which we are going to create now and another ActionResult Create will get customer object from the form submitted and will call our create method of CustomerDB Class. Now it’s time to create a view for adding customer. Right Click return view Statement in Create Action Result and Click Add View and Just Create view like following.

CreateView
That’s it now we are ready. Now let’s test it in browser. Like following.

AddNew
Now let’s click and create and then it will redirect us to customer list page like following. Where you can see the newly added details.

View
So that’s it. Its very easy to Insert data with Dapper Micro ORM. Hope you like it…Stat tuned for more.

Note: For reference of this post you can also see my first post called -Playing with dapper Micro ORM and ASP.NET MVC 3.0.
kick it on DotNetKicks.com
Shout it
Share:
Wednesday, May 18, 2011

Microsoft Community Techdays at Ahmedabad-11th June 2011

Microsoft community TechDays are great events organized by Microsoft and every time I like to be part of it. Now once again this event date is announced  by Microsoft and its going to happen 11th June 2011. I would love to part of it. It’s a free event so you don’t need to pay for it.  It’s a good chance to do some social networking with Microsoft MVPS and professionals like Jacob Sebastian, Pinal Dave, Harish Vaidyanathan. You will also learn lots of new things.

Following is agenda for this event.

AGENDA

09:30am - 10:00am
Registration


10:00am - 10:15am
Welcome Note


LightSwitch On The Cloud! by Mahesh Dhola
10:15am to 11:15pm
The session would give introduction to Visual Studio Light Switch followed by the demo. The demo would give insight of developing Light Switch application and deploying to the Microsoft cloud offerings Windows Azure.


SQL Server Performance Troubleshooting using Waits and Queues by Pinal Dave
11:15am to 12:15pm
Just like a horoscope, SQL Server Waits and Queues can reveal your past, explain your present and predict your future. SQL Server Performance Tuning uses the Waits and Queues as a proven method to identify the best opportunities to improve performance. A glance at Wait Types can tell where there is a bottleneck. Learn how to identify bottlenecks and potential resolutions in this fast paced, advanced performance tuning session.

12:15pm - 01:15pm
Lunch

HTML5 - Future of the Web by Harish Vaidyanathan
01:15pm to 02:15pm
HTML5 will change the Web as we know it today. Join this session to know what's happening behind-the-scenes of this hugely important specification. Get an overview of the new features in HTML5, CSS3, SVG & DOM specifications. Better understand what the open challenges are and where HTML5 is leading to in the future.

TSQL Worst Practices by Jacob Sebastian
02:15pm to 03:15pm
This is an interactive session filled with exciting demos where we will go over a number of "good looking" TSQL usages that are often quite "dangerous" by means of killing performance as well as producting uncorrect and unexpected results.

03:15pm - 03:30pm
Tea Break

ASP.NET Tips and Tricks by Tejas Shah
03:30pm to 04:30pm
The session will focus on understanding of Asp.Net fundamentals and tricks that can be used in development with Demo. This session also covers how to improve application performance.
Demo Extravaganza & Gifts by Community

04:30pm to 05:30pm
Various community speakers will present insight on upcoming technology and interesting demos.
Community session

05:30pm
Thank you Note


Note: The above agenda is subject to change.

I will be there. It will be great fun and learning experience. Hope to see you guys at that event.

Shout it

kick it on DotNetKicks.com
Share:
Monday, May 16, 2011

Playing with dapper Micro ORM and ASP.NET MVC 3.0

Some time ago Sam Saffron a lead developer from stackoverflow.com has made dapper micro ORM open source. This micro orm is specially developed for stackovewflow.com for keeping performance in mind. It’s very good single file which contains some cool functions which you can directly use in your browser. So I have decided to have a look into it. You can download dapper code from the following location it’s a single static class file called SQLMapper.

http://code.google.com/p/dapper-dot-net/

So once you download that file you can use that file into your project. So I have decided to create a sample application with asp.net mvc3. So I have created a simple asp.net mvc 3 project called DapperMVC. Now let’s first add that SQLMapper class file into our project at Model Folder like following.

SQLMapper

Now let’s first create sample table from which we will fetch the data with the help of dapper file. I have created sample customer table with following script.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customer](
 [CustomerId] [int] NOT NULL,
 [FirstName] [nvarchar](50) NULL,
 [LastName] [nvarchar](50) NULL,
 [Address] [nvarchar](256) NULL,
 [City] [nvarchar](50) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
 [CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Once I have created table I have populated some test data like following.

TestData

Now we are ready with database table Now its time to add a customer entity class. So I have created sample customer class with properties same as Database columns like following.

public class Customer
{
 public int CustomerId { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string Address { get; set; }
 public string City { get; set; }
}

Now we are done with the Customer Entity class then I have created a new class called CustomerDB and a created a GetCustomer Method where I have used Query Method of Dapper to select all customers with ‘select * from customer’ simple query. I know it’s not a best practice to write ‘select * from customer’ but this is just for demo purpose so I have written like this. Query method accepts query as parameter and returns IEnumerable<T> where T is any valid class. In our case it will be Customer which we have just created before. Following is the code for CustomerDB Class.

using System.Collections.Generic;

public class CustomerDB
{
 public string Connectionstring=@"Data Source=DotNetJalps\SQLExpress;Initial Catalog=CodeBase;Integrated Security=True";

 public  IEnumerable<Customer> GetCustomers()
 {
     using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
     {
         sqlConnection.Open();
         var customer = sqlConnection.Query<Customer>("Select * from Customer");
         return customer;

     }
 }

}

Now we are ready with our model classes now It’s time to Create a Controller so I have created a Customer Controller like following.

CustomerController

It will create customer controller in controller folder with by default ActionResult Index. I have modified Action Result just like to following to return customerEntities with IndexView.

public class CustomerController : Controller
{
 //
 // GET: /Customer/

 public ActionResult Index()
 {
     var customerEntities = new CustomerDB();
     return View(customerEntities.GetCustomers());

 }

}

Now we are ready with our Customer Controller and now it’s time to create a view from the customer entities. So I have just right clicked customer entities and Create a View like following.

AddingView

It will popup the following dialogbox where I have selected Razor View with Strongly Typed View. Also I have selected Customer Model class customer and selected list template like following.

RazorView

That’s it now we are done with all the coding and It’s now time to run the project and result is as accepted as following.

Browser

That’s it. Isn’t that cool? Hope you liked this. Stay tuned for more.. Happy programming

Shout it

kick it on DotNetKicks.com
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews