Sunday, February 10, 2013

How To Improve the Performance of MVC Web Application ASP.NET

Introduction

In this article, I will examine how you can improve the performance of an ASP.NET MVC application by taking advantage of the following components:
  1. Implementing Caching
  2. Implementing HTTP Compression
  3. Implementing JQuery UI library with Google Hosted Ajax Libraries
  4. By combining scripts and other resources
  5. Deploying production code in release mode
  6. Removing default HTTP modules in ASP.NET
  7. Optimizing URL generation

Implementing Caching

The easiest way to implement cache on MVC view is to add an [OutputCache] attribute to either an individual controller action or an entire controller class. Here is a controller action GetWeather() that will be cached for 15 seconds.
 
[OutputCache(Duration = 15, VaryByParam = "None")]
public ActionResult GetWeather(string Id)
{
}
 
To cache your entire controller, you will implement [OutputCache] attribute on an entire controller class as shown below:
 
[OutputCache(Duration = 15, VaryByParam = "None")]
public class WeatherController : Controller
    {
        //         // GET: /Weather/         public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetWeather(string Id)
        {
        }
   }
 
For more details, please read this.
You can also control the cache programmatically by implementing Cache API. The System.Web.Caching.Cache class works like a dictionary. You can add key and item pairs to the Cache class. When you add an item to the Cache class, the item is cached on the server. The following code example adds an item to the cache with a sliding expiration time of 10 minutes:
 
Cache.Insert("Key", "Value",
    null, System.Web.Caching.Cache.NoAbsoluteExpiration,
    new TimeSpan(0, 10, 0));
 
For more details, please read this.
The one limitation of the ASP.NET Cache object is that it runs in the same process as your web application. It is not a distributed cache. If you want to share the same ASP.NET Cache among multiple machines, you must duplicate the cache for each machine. In this situation, you need to use a distributed cache. To implement distributed cache, you can use the Microsoft distributed cache (code-named Velocity) with an ASP.NET MVC application. Here is a great article by Stephen Walther where he explains in detail.
You can also cache any HTTP get request in the user browser for a predefined time, if the user requests the same URL in that predefined time the response will be loaded from the browser cache instead of the server. Here is another great article about ASP.NET MVC Action Filter - Caching and Compression by Kazi Manzur where he explains in detail.

Implementing HTTP Compression

You can apply the action filter to compress your response in your ASP.NET MVC application. A great article that explains this in detail is ASP.NET MVC Action Filter - Caching and Compression.
There are several problems with ASP.NET MVC application when deployed on IIS 6.0.
 
There's also a port of the YUICompress for .NET on CodePlex that compresses any Javascript and Cascading Style Sheets to an efficient level.

Implementing JQuery UI library with Google Hosted Ajax Libraries

You can Build Rich client site User Interfaces with jQuery. There is a great article by Dino Esposito on Building Rich User interfaces. You should also consider usingGoogle hosted AJAX libraries API as it will improve the site performance. Please see Test Drive of the Google Hosted Ajax Libraries.

By Combining Scripts and Other Resources

ASP.NET MVC Client-side Resource Combine is another great library which is available at CodePlex. This library requires you to organize client-side resources into separate sets, each with different configuration settings (although there's nothing stopping you from having a 1-file resource set). The resources in each set are to be minified, combined, compressed, and cached together and therefore can be requested in 1 single HTTP request. Refer to the project CodePlex page for detailed usage and binary/code download. The library uses the great YUI Compressor library for the minification part.

Deploying Production Code in Release Mode

When we develop ASP.NET applications using Visual Studio, the default value for debug attribute is true. These settings will give a poor performance in production if released in the default debug mode. So, never release your website or application with debug mode set to true. It should be set to false inweb.config when moving to production.
 
 <compilation debug="false" />
 
Removing Default HTTP Modules in ASP.NET
The following default httpModules element is configured in the root Web.config file in the .NET Framework version 2.0.
 
<httpModules>
     <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />
     <add name="Session" type="System.Web.SessionState.SessionStateModule" />
     <add name="WindowsAuthentication"
type="System.Web.Security.WindowsAuthenticationModule" />
     <add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule" />
     <add name="PassportAuthentication"
type="System.Web.Security.PassportAuthenticationModule" />
     <add name="RoleManager" type="System.Web.Security.RoleManagerModule" />
     <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
     <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" />
     <add name="AnonymousIdentification"
type="System.Web.Security.AnonymousIdentificationModule" />
     <add name="Profile" type="System.Web.Profile.ProfileModule" />
</httpModules>  
 
You can remove the modules you don't need in the web.config like so:
 
 <httpModules>
  <remove name="PassportAuthentication" />
  <remove name="Profile" />
  <remove name="AnonymousIdentification" />
</httpModules>
 
Optimizing URL Generation
ASP.NET MVC framework offers the following methods to generate URL:
  1. Html.ActionLink()
  2. Html.RouteLink()
  3. Url.Action()
  4. Url.RouteUrl()
Html.RouteLink() is equivalent to Html.ActionLink():
 
<%= Html.RouteLink("Click here", new {controller= "Weather", action= "GetWeather"}) %>
       //will render the following <a href="/Weather/GetWeather">Click here</a>
 
Similarly, Url.RouteUrl() is equivalent to Url.Action():
 
<%= Url.RouteUrl(new {controller= "Weather", action= "GetWeather"}) %>
will render the following /Weather/GetWeather
 
However, these methods can have a performance impact on your application.

Summary

In this article, we examined how to improve the performance of an ASP.NET MVC application by taking advantage of the caching and HTTP compression that are available in .NET Framework. We also examined other open source libraries such as JQuery and combining scripts and other resources to improve the MVCapplication performance.

Sunday, February 3, 2013

Whats App in Your PC


Step 1


Android application

First you have to download an android programm on your personal computer.

This has to be done before you download the Whatsapp application.

We need this programm to make use of Whatsapp, because this programm acts like it is your mobile phone.

The programm is an android emulator.

Nowadays I use a free application called Bluestacks. You can download This application  here:

http://bluestacks.com/
http://allmyapps.com/apps/whatsapp/download



It is very userfriendly and it is also available for MAC users. Also can you synchronize this program

with your android apps on your phone when you like that!!

here is an instruction for that:

http://www.youtube.com/watch?v=ffFxnnGqFLk  SaveFrom.net

We did recommend “Youwave” in the past. Although it works fine it is limited by a 7 day trial period.

When you dont mind paying after several days or you just want to check the trial out.

Youwave is downloadable here:  http://youwave.com/download.html


Step 2


Whatsapp on your android application

When we have installed one of the android applications, we need to get Whatsapp installed in this application.

I will explain how to this for both applications from step 1.

For Bluestacks users. After you start Bluestacks and it is loaded , simply go to the search line and type in Whatsapp and download it.

It will appear among the other apps which are preinstalled.

For Youwave users. The easiest way to do this is to use the  Youwave application itself for it.

So we open and start Youwave. Click on view on top and click on online content.

We can see the Whatsapp icon beneath the online apps (click and run ). Click on it and run it.

This will download Whatsapp and place it in your Youwave. After it is done you can see the icon on the home page of Youwave.

You  also can download and install Whatsapp with the browser of Youwave going to this site:

whatsapp.com/android




Step 3
How to setup Whatsapp on your pc

After the Whatsapp application is installed and you run it, it will  asks for your personal details.

You have to fill it in and keep your phone in the near area. The number you fill in has to be correct.

You even can use your home phone instead of a mobile phone.

First you will get a text message from Whatsapp with a 3 digit number.

The install screen of Whatsapp will ask you to click on “call me”.

When u click on “call me”, an automatic call is made to your phone number.

A voice will tell you the same 3 digit number as the number they send you by text message. Fill in this number.

Last step is to fill in your name or nickname. Verification is complete and you are ready to use Whatsapp.

In step 4 we will learn you to add contacts and to useWhatsapp.


Step 4


Add contacts and whatsapp in use

To use whatsapp go back to your home screen of youwave or bluestack.

For Bluestack users

Just open your whatsapp application and click on the black menu button on the bottom left.
When you click on it you see contacts in the list. Click on it and add contacts.
After adding contacts, you can just click on your contacts to chat with them via whatsapp.

Here is a very usefull video, which shows all steps.

For Youwave users

Keep in mind this application is a replacement for a mobile phone. This way the contacts have to be added in the android application and not in whatsapp, like other messengers request.
Youwave is the main programm and whatsapp is an add.

On the home page of youwave we click on the green phone icon. We get a sort of call screen. Here we type in the number of a contact, who uses whatsapp. Next we click at the bottom on menu and click on add to contacts, next we click on create a contact and fill in the name details. This way we can add many contacts.
When you are in the contact list just click a contact and when he or she has whatsapp you can click on Whatsapp icon and chat with this contact.

You also can click on the whatsapp icon on the home page of youwave and click on the pencil for all contacts that use whatsapp.

Enjoy your whatsapp on your computer!

Here is a very usefull video, which shows all steps. Thanks to youtube user xNAILEDxITx for making this video.

Wednesday, August 31, 2011

Insert Update Delete Using Stored Procedure

SqlConnection CN = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
ddlBindlist();
ViewState["sortOrder"] = "";
bindGridView("", "");
}
}

private void BindData()
{
try
{
SqlDataAdapter da = new SqlDataAdapter("SelectEmployeeAll", CN);
da.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
//GridView1.Columns[2].Visible = false;
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}

protected void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text == "Add")
{
try
{
//string str = "InsertEmployee";
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand("InsertEmployee", CN);
da.InsertCommand.CommandType = CommandType.StoredProcedure;
da.InsertCommand.Parameters.AddWithValue("@Name", txtEmpName.Text);
da.InsertCommand.Parameters.AddWithValue("@Address", txtAddress.Text);
da.InsertCommand.Parameters.AddWithValue("@DateOfBirth", txtDoB.Text);
da.InsertCommand.Parameters.AddWithValue("@JoingDate", txtJoingDate.Text);
da.InsertCommand.Parameters.AddWithValue("@CompanyId", ddlCompanyid.SelectedValue);
CN.Open();
da.InsertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
lblMessage.Text= "Inserted Successfully";
}
}
else if (btnAdd.Text == "Update")
{
try
{
int id = Convert.ToInt32(GridView1.SelectedRow.Cells[2].Text);
//string strUpdate = "UpdateEmployee";
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand("UpdateEmployee", CN);
da.UpdateCommand.CommandType = CommandType.StoredProcedure;
da.UpdateCommand.Parameters.AddWithValue("@Name", txtEmpName.Text);
da.UpdateCommand.Parameters.AddWithValue("@Address", txtAddress.Text);
da.UpdateCommand.Parameters.AddWithValue("@DateOfBirth", txtDoB.Text);
da.UpdateCommand.Parameters.AddWithValue("@JoingDate", txtJoingDate.Text);
da.UpdateCommand.Parameters.AddWithValue("@CompanyId", ddlCompanyid.SelectedValue);
da.UpdateCommand.Parameters.AddWithValue("@Id", id.ToString());
CN.Open();
da.UpdateCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
lblMessage.Text = "Updated Successfully";
}

}

clear();
btnAdd.Text = "Add";
BindData();
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
txtEmpName.Text = GridView1.SelectedRow.Cells[3].Text;
txtAddress.Text = GridView1.SelectedRow.Cells[4].Text;
txtDoB.Text = GridView1.SelectedRow.Cells[5].Text;
txtJoingDate.Text = GridView1.SelectedRow.Cells[6].Text;
ddlCompanyid.SelectedItem.Text = GridView1.SelectedRow.Cells[7].Text;
btnAdd.Text = "Update";
}

private void clear()
{
txtEmpName.Text = "";
txtAddress.Text = "";
txtDoB.Text = "";
txtJoingDate.Text = "";
}

protected void btnCancle_Click1(object sender, EventArgs e)
{
clear();
}

public void ddlBindlist()
{
try
{
string str = "SelectCompanyInfoAll";
SqlDataAdapter da = new SqlDataAdapter(str, CN);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
ddlCompanyid.DataSource = ds;
ddlCompanyid.DataTextField = "CompanyName";
ddlCompanyid.DataValueField = "Id";
ddlCompanyid.DataBind();
}
catch (Exception ex)
{
throw ex;
lblMessage.Text = ex.Message;
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int Id = Convert.ToInt32(GridView1.SelectedRow.Cells[2].Text);
int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
DeleteRecordByID(Id);
}

protected void DeleteRecordByID(long Id)
{
SqlDataAdapter da = new SqlDataAdapter();
da.DeleteCommand = new SqlCommand("DeleteEmployee", CN);
da.DeleteCommand.CommandType = CommandType.StoredProcedure;
da.DeleteCommand.Parameters.AddWithValue("@Id",Id);
CN.Open();
da.DeleteCommand.ExecuteNonQuery();
//DataSet ds = new DataSet();
//da.Fill(ds);
BindData();
}
protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
if (e.Exception == null)
{
lblMessage.Text = "Record deleted";
}

else
{
lblMessage.Text = e.Exception.Message;
e.ExceptionHandled = true;
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
public void bindGridView(string sortExp, string sortDir)
{
if (CN.State == ConnectionState.Closed)
{
CN.Open();
}

SqlCommand mySqlCommand = new SqlCommand("SelectEmployeeAll", CN);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);

DataView myDataView = new DataView();
myDataView = myDataSet.Tables[0].DefaultView;

if (sortExp != string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}

GridView1.DataSource = myDataView;
GridView1.DataBind();

if (CN.State == ConnectionState.Open)
{
CN.Close();
}
}

public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}

return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
bindGridView(e.SortExpression, sortOrder);
}

Insert Update Delete Linq



























Employee Name:



Address:



Date of Birth:





(eg. MM/dd/yyyy)

Joing Date:





(eg. MM/dd/yyyy)

CompanyName:























//-----Code

SqlConnection CN = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConnectionString"].ConnectionString);
DataClassesDataContext db = new DataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
ddlBindlist();
ViewState["sortOrder"] = "";
bindGridView("", "");
}
}

private void BindData()
{
try
{
GridView1.DataSource = from emp in db.Employees
join cinfo in db.CompanyInformations on emp.CompanyId equals cinfo.Id
orderby emp.Id
select new { emp.Id, emp.Name, emp.Address, emp.DateOfBirth, emp.JoingDate, cinfo.CompanyName };
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}

protected void btnAdd_Click(object sender, EventArgs e)
{
if (btnAdd.Text == "Add")
{
Employees emp = new Employees();
emp.Name = txtEmpName.Text;
emp.Address = txtAddress.Text;
emp.DateOfBirth = txtDoB.Text;
emp.JoingDate = txtJoingDate.Text;
emp.CompanyId = Convert.ToInt32(ddlCompanyid.SelectedValue);

db.Employees.InsertOnSubmit(emp);
try
{
db.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
finally
{
lblMessage.Text = "Inserted Successfully";
}
}
else if (btnAdd.Text == "Update")
{
Employees emp = db.Employees.Single(ep => ep.Id == Convert.ToInt32(GridView1.SelectedRow.Cells[2].Text));
emp.Name = txtEmpName.Text;
emp.Address = txtAddress.Text;
emp.DateOfBirth = txtDoB.Text;
emp.JoingDate = txtJoingDate.Text;
emp.CompanyId = Convert.ToInt32(ddlCompanyid.SelectedValue);

try
{
db.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
finally
{
lblMessage.Text = "Updated Successfully";
}
}

clear();
btnAdd.Text = "Add";
BindData();
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
txtEmpName.Text = GridView1.SelectedRow.Cells[3].Text;
txtAddress.Text = GridView1.SelectedRow.Cells[4].Text;
txtDoB.Text = GridView1.SelectedRow.Cells[5].Text;
txtJoingDate.Text = GridView1.SelectedRow.Cells[6].Text;
ddlCompanyid.SelectedItem.Text = GridView1.SelectedRow.Cells[7].Text;
btnAdd.Text = "Update";
}

private void clear()
{
txtEmpName.Text = "";
txtAddress.Text = "";
txtDoB.Text = "";
txtJoingDate.Text = "";
}

protected void btnCancle_Click1(object sender, EventArgs e)
{
clear();
}

public void ddlBindlist()
{
try
{
//DataClassesDataContext db = new DataClassesDataContext();
ddlCompanyid.DataSource = from cinfo in db.CompanyInformations
select cinfo;
ddlCompanyid.DataTextField = "CompanyName";
ddlCompanyid.DataValueField = "Id";
ddlCompanyid.DataBind();
}
catch (Exception ex)
{
throw ex;
lblMessage.Text = ex.Message;
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//int Id = Convert.ToInt32(GridView1.SelectedRow.Cells[2].Text);
int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
DeleteRecordByID(Id);
lblMessage.Text = "Record deleted";
}

protected void DeleteRecordByID(long Id)
{
//DataClassesDataContext db = new DataClassesDataContext();
Employees toDelete = db.Employees.Single(p => p.Id == Id);
db.Employees.DeleteOnSubmit(toDelete);
db.SubmitChanges();
BindData();
lblMessage.Text = "Record deleted";
}
protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
if (e.Exception == null)
{
lblMessage.Text = "Record deleted";
}

else
{
lblMessage.Text = e.Exception.Message;
e.ExceptionHandled = true;
}
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}

public void bindGridView(string sortExp, string sortDir)
{
if (CN.State == ConnectionState.Closed)
{
CN.Open();
}

var company = db.SpCompanyInformation();
//SqlCommand mySqlCommand = new SqlCommand("select Employee.Id, Employee.Name, Employee.Address, Employee.DateOfBirth, Employee.JoingDate, CompanyInformation.CompanyName from Employee left join CompanyInformation on Employee.CompanyId = CompanyInformation.Id", CN);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
DataSet myDataSet = company;
mySqlAdapter.Fill(myDataSet);

DataView myDataView = new DataView();
myDataView = myDataSet.Tables[0].DefaultView;

if (sortExp != string.Empty)
{
myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
}

GridView1.DataSource = myDataView;
GridView1.DataBind();

if (CN.State == ConnectionState.Open)
{
CN.Close();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
bindGridView(e.SortExpression, sortOrder);
}
public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}

return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}