Wednesday, December 19, 2012

Best Practices for Asp.net MVC

Bookmark of few good asp.net mvc best practices links for my future reference:


Note: I will be updating with my list added on top of this later

I have arrange them in order in which i enjoyed reading/viewing :)

Securing Asp.net Application

Incase if you haven't viewed this video which is talking on basic and very important aspect of securing your asp.net application, then I will strongly recommend everyone to view this video.

Tuesday, December 11, 2012

AllowHtml Attribute to allow html for your asp.net mvc application

Whenever you are trying to take html input from your asp.net mvc application without using AllowHtml attribute to model field then you will run into following error.

Server Error in '/' Application.

A potentially dangerous Request.Form value was detected from the client (StepValue="...Enumerable intSequence = ...").

Description: ASP.NET has detected data in the request that is potentially dangerous because it might include HTML markup or script. The data might represent an attempt to compromise the security of your application, such as a cross-site scripting attack. If this type of input is appropriate in your application, you can include code in a web page to explicitly allow it. For more information, see http://go.microsoft.com/fwlink/?LinkID=212874.

Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (StepValue="...Enumerable intSequence = ...").

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (StepValue="...Enumerable intSequence = ...").]
   System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection) +9665149
   System.Web.<>c__DisplayClass5.b__3(String key, String value) +18
   System.Web.HttpValueCollection.EnsureKeyValidated(String key) +9664565



Following are two most popular ways to allow html input in asp.net mvc

  • Make use of [AllowHtml] attribute on model field you want to allow html input. (Recommended way)
  • Make use of [ValidateInput(false)] on controller method - non recommended way because it will not validate any input field.


Example

Creating BlogPost wherein we want to allow blog content to take html

Model class 
public class BlogPost {
    public string Title { get; set; }
    public DateTime PostedOn { get; set; }
    public string Tags { get; set; }
    public string Content { get; set; }
}

Controller class
public class BlogPostController : Controller {
        public ActionResult Create() { 
            return View();
        }
        [HttpPost]
        public ActionResult Create(BlogPost model) {
            ViewBag.HtmlContent = model.Content; 
            return View(model);
        }
    }

View Page

@using (Html.BeginForm()) {
   
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>BlogPost</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PostedOn)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PostedOn)
            @Html.ValidationMessageFor(model => model.PostedOn)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Tags)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Tags)
            @Html.ValidationMessageFor(model => model.Tags)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Content)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Content)
            @Html.ValidationMessageFor(model => model.Content)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>

        <p>
            Posted Content : @ViewBag.HtmlContent
        </p>

    </fieldset>
}



Method 1: Example with [AllowHtml] Attribute (Recommended)
By allowing html using AllowHtml Attribute we are limiting Html input for particular fields.  In our example we are allowing html to only BlogPost - Content field.

Change your BlogPost Model and add [AllowHtml] attribute as follow:
using System.Web.Mvc;

public class BlogPost {
    public string Title { get; set; }
    public DateTime PostedOn { get; set; }
    public string Tags { get; set; }
  
    [AllowHtml]
    public string Content { get; set; }
}


Method 2: Example with [ValidateInput(false)] (Non-Recommended)
You can also allow html by simply turning off validation on controller method as shown in following example:


public class BlogPostController : Controller {
        public ActionResult Create() { 
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(BlogPost model) {
            ViewBag.HtmlContent = model.Content; 
            return View(model);
        }
    }

Problem with using [ValidateInput(false)] is it will turn off validation on whole controller's action method which is very dangerous.

Monday, December 10, 2012

Weird errors in asp.net mvc and its solution

If you are experiencing weird errors in asp.net mvc.

Situation 1
You have added namespace in Web.config file still your View Page is not reflecting any change or still control is error-ed out, then close the view and reopen it.  Yes VS.Net requires closing and opening of view page in order to reflect changes.


Situation 2
You have made major change in Entity Framework (Code First) Entity class and even though making sure that all changes are properly applied if you receive any runtime error saying "Invalid column name" or may be something as shown below:  Then simply close your asp.net mvc project (VS.Net Solution) and open it again. (Yes i found this weird because it requires me to close my vs.net solution and reopen it again to reflect all changes, even though i tried clean solution and rebuild solution before running project)


 at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
   at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
   at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
   at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MyBlog.Controllers.StepbystepController.Index() in d:\Websites\Source\MyBlog\MyBlog\Controllers\StepbystepController.cs:line 27
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.b__41()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.b__7(IAsyncResult _)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.b__33()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49()





Situation 3
You have change model in view then to apply changes you need to close view and reopen it again.


Now below situation are something becoz of our mistake but we don't generally noticed.  Mostly this errors result in 404 - Error Page.

If you are getting 404 Error in asp.net mvc then make sure
1) Check action name and then check view name.
Example: You have created "ContactMessage" action method in Home controller and you have created "Contact" view page, this mismatch will result in 404 error.  I know you new this but you don't realize this when 404 occurs.

2) Check whether you have created view page under correct directory name.  I will not go deep into Asp.net MVC Hierarchy structure but as you know that proper naming convention needs to follow, so by mistake if you have created view under wrong directory that will also results in 404 error page.

3) Check whether controls on your view is not error-ed out. (They are getting proper values assigned from model).

4) You can always turn CustomErrors mode="RemoteOnly" to simply attack problem at first.




There are few other situations but i can't able to recall them all, but you get the gist of my post.


Moral of story:  All errors mentioned here are either becoz of our mistake or vs.net, but we don't generally noticed, so if you run into similar situation then answer is relax and try to make sure that things are not becoz of your mistake before jumping into find solution.

Sunday, December 02, 2012

How to store millions of Images in best possible way in Asp.net

I have requirement in which i want to create a architecture to store millions of images in best possible way.

Requirement 1:
Each Image have its Unique name and Path by generating MD5 Hash code for Image.  By generating MD5 Hash code duplicating of Image can be avoided.
Example: If 100 user upload the exact same image, you will only keep one copy of that image on your filesystem instead of 100 copies.
Example of MD5 Hashcode from Image: 8b68925628110278bf194cbe5e071654


Requirement 2:
Making image storing pattern such that to keep directory sizes manageable.
Example of directory structure form from Image Hash Code.
/userimages/orig/8/b6/892/8b68925628110278bf194cbe5e071654.jpg
/userimages/orig/5/28/533/528533467df9388eb63c99e78f4e9499.jpg
/userimages/orig/d/34/ca1/d34ca13a7295ccc8461281e3e7567b9f.jpg
            
/userimages/medium/8/b6/892/8b68925628110278bf194cbe5e071654.jpg
/userimages/medium/5/28/533/528533467df9388eb63c99e78f4e9499.jpg
/userimages/medium/d/34/ca1/d34ca13a7295ccc8461281e3e7567b9f.jpg
                      
/userimages/small/8/b6/892/8b68925628110278bf194cbe5e071654.jpg
/userimages/small/5/28/533/528533467df9388eb63c99e78f4e9499.jpg
/userimages/small/d/34/ca1/d34ca13a7295ccc8461281e3e7567b9f.jpg

Please note: This article only discuss core concept about how to generate hash code for image and how to store image by creating proper directory structure while storing on file system.  You can add lot on top of this but this will be a good starting point.



protected void btnUploadImage_Click(object sender, EventArgs e)
{
            UploadImage();
}

private void UploadImage()
{
            if (!(FileUpload1.HasFile))
            {
                //Image Is Invalid
                //Reason: Either of following
                //1) Non-supported Image File Format
                //2) No Image File Found
                //3) Invalid image (Eg: Text file is renamed to .jpg Image)
                //Display appropriate message to user               
                //Please note I have NOT added code for how to validate image
                //In order to keep article focus on core concept
                return;
            }
            else
            {
                //Valid Image
                string ImgHashCode = Image2Md5Hash();
                lblImageHashCode.Text = ImgHashCode;

                //Todo: Write Code to Save HashCode.filetype in database

                //Save File on FileSystem
                SaveImageonFileSystem(ImgHashCode);
            }
}


Answer for Requirement 1:
//Image to MD5 Hash Code - Generating Hash Code for Image
private string Image2Md5Hash()
{           
            const int BUFFER_SIZE = 255;
            Byte[] Buffer = new Byte[BUFFER_SIZE];

            Stream theStream = FileUpload1.PostedFile.InputStream;
            int nBytesRead = theStream.Read(Buffer, 0, BUFFER_SIZE);
                        return CalculateMD5(theStream);
}

private static byte[] _emptyBuffer = new byte[0];

public static string CalculateMD5(Stream stream)
{
            return CalculateMD5(stream, 64 * 1024);
}

public static string CalculateMD5(Stream stream, int bufferSize)
{
            MD5 md5Hasher = MD5.Create();

            byte[] buffer = new byte[bufferSize];
            int readBytes;

            while ((readBytes = stream.Read(buffer, 0, bufferSize)) > 0)
            {
                md5Hasher.TransformBlock(buffer, 0, readBytes, buffer, 0);
            }

            md5Hasher.TransformFinalBlock(_emptyBuffer, 0, 0);

            var sb = new StringBuilder();
            foreach (byte b in md5Hasher.Hash)
                sb.Append(b.ToString("x2").ToLower());
            return sb.ToString();           
}


Answer for Requirement 2:
private void SaveImageonFileSystem(string ImgHashCode)
{
 /*
/userimages/orig/8/b6/892/8b68925628110278bf194cbe5e071654.jpg
/userimages/orig/5/28/533/528533467df9388eb63c99e78f4e9499.jpg
/userimages/orig/d/34/ca1/d34ca13a7295ccc8461281e3e7567b9f.jpg            
*/

            if(!string.IsNullOrEmpty(ImgHashCode))
            {
                string RootDirPath = "userimages";
                string ImageSize = "orig";
                string FirstFolder = ImgHashCode.Substring(0,1);
                string SecondFolder = ImgHashCode.Substring(1,2);
                string ThirdFolder = ImgHashCode.Substring(3, 3);

                string DirectoryName = Server.MapPath("~")
                                        + RootDirPath + "\\"
                                        + ImageSize + "\\"
                                        + FirstFolder + "\\"
                                        + SecondFolder + "\\"
                                        + ThirdFolder + "\\";

                if (!Directory.Exists(DirectoryName))
                {
                    Directory.CreateDirectory(DirectoryName);
                }

                FileUpload1.SaveAs(DirectoryName + ImgHashCode + Path.GetExtension(FileUpload1.FileName));
            }
}


Related Post
How to identify whether uploaded image is valid or not
How to remove image from cache

Saturday, September 29, 2012

Asp.net Security - Validating Uploaded Image File Format

I found two really good links talking about how to upload image file and validate file format in more secure way rather than just checking file extension.



You should also check image file content before you try checking for header of image file.

I found both the articles have missed this code.  Here is that missing code for validating file extension.

private Boolean CheckFileType()
        {
            string[] acceptedTypes = new string[]
            {
                "image/bmp",
                "image/jpeg",                
                "image/gif",
                "image/png"
            };

            if (!acceptedTypes.Contains(fuPhoto1.PostedFile.ContentType))
            {
                return false;
            }
            else
            {
                return true;
            }
        }


Note: This article is basically bookmark for my future reference.

Friday, September 28, 2012

All About ASP.NET Website Performance Improvement

In this article i will be explaining some of quick, easy and must use Asp.net Website Performance Improvement tips.

Asp.net Performance Improvement checklist is divided into 4 broad categories

  1. Identifying which part of asp.net web application requires optimization.
  2. Optimizing Asp.net web project to improve website performance
  3. Tips for writing code in order to enhance performance.
  4. Database Optimization to improve performance (I will be explaining for SQL Server but same tips will also apply to MySQL, Oracle or any other DB by changing syntactical meaning respectively.)
I will be discussing each of asp.net performance improvement categories in detail.

Identifying which part of asp.net web application requires optimization.

It is very important to identify which part of your application requires more attention in order to improve website performance.  

1 Using VS.Net 2010 Profiler
2 Tracing asp.net web application
3 Extension (Firefox Firebug, YSlow, Google Chrome Speed Tracer, IE9 Developer Tools)
4 Monitoring tools like fiddler will also be helpful.


Optimizing Asp.net web project to improve website performance.

In order to improve asp.net web page performance most important thing we should consider is
  • Reduce asp.net page size - By reducing page size page it will get download quickly and thus load quickly on user's browser.  It will also reduce bandwidth consumption of your website.  
  • Reduce number of HTTP request -  It is very important to reduce number of HTTP requests on your server, it will help in reducing the server load and allowing more visitors to access your website.
  • Avoid round trip to server.

In order to reduce asp.net page size.

1) Avoid viewstate - viewstate is used to persist data of web page on page postback.  This increase page size.  I always prefer to turn off viewstate at page level and only turn on viewstate to specific control whose data i need to persist over page postback.  

You can do so by <%@ Page  EnableViewState="false" %>

Situation in which you must avoid viewstate.
  • Only page which take user input or control whose values you want to persist on page postback will require viewstate.  Example: If user press submit button and if there are error on page we should persist user input, so in that case we should make EnableViewState="true" for those control or may be at page level.
  • Display pages or asp.net page which will not require page postback.  Example: Page on which you are displaying customers information in datagrid, doesn't require viewstate so in this situation you can turn of viewstate.
2) Use div instead of table. - Make use of div and css to replace table.  Combination of div and css is much more faster than table.

3) Avoid big name for asp.net server control and CSS class tag - Do not give big name for ID field of asp.net server control,  specially to ContentPlaceHolder  asp.net server control in master page.  ContentPlaceHolder ID name is appended to each and every asp.net server control inside child page, so if you choose a big name for your asp.net server control it will increase html file size.

Similarly if you choose a big name for CSS class tag, it will have long name on every instance you make use of that class tag and in return it increase html size.

For this reason, I prefer to choose very short name for any controls or css tag definition.
Example: <asp:ContentPlaceHolder ID="CC" runat="server">

4) Remove unnecessary white space (Compress generated HTML Size)
  • Remove white spaces between tags and lines of html render by asp.net page.  In order to remove white space dynamically on all page, you should put "render" method inside master page class file.
  • Remove unused tags from CSS file and also remove unused script from Javascript file.
  • Remove white spaces from CSS file while deploying to production server.  Remember, Comments and whitespace inside your CSS and Javascript file are not needed for execution; Removing them will speed up css rendering time and script execution times.  You can add this step to your deployment checklist. You can take advantage of online compress css tool and online javascript compress tool.

5) Make use of JQuery instead of Ajax Control toolkit.  
I have observed that JQuery can do the task with less code and light weight, while Ajax control toolkit is bulkier and increase page size.  Find more on JQuery vs Ajax control toolkit.



Reduce number of HTTP request
With help of Firebug, Firefox extension, you can find out how many resource request was made by your asp.net web page.  It is very important to reduce number of HTTP requests on your server, it will help in reducing the server load and allowing more visitors to access your website.

1) Make minimum use of Images.  Images are good for UI but can increase size of web page and also results in too many http request.

2) Combine multiple db request into single db request.  Find more details on How to avoid multiple database request to improve performance

3) Combine 2 or more css file into 1 file, since most of modern browser do cache css file, it will only take little more time for 1st request, all sub subsequent request will be super fast.  Combining multiple css file into 1 will reduce number of http request.

4) Combine 2 or more javascript file into 1 file, since most of modern browser do cache javascript file, it will only take little more time for 1st request, all sub subsequent request will be super fast.  Combining multiple javascript file into 1 will reduce number of http request.

5) Special tips if your web application is using JQuery
    • Try to use Jquery from CDN (Content distribution network) link for google CDN http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
    • While adding JQuery try using min version (Example: jquery-1.6.2.min.js), which is less file size, since space and line break are removed from that.  This will help in faster loading of file and also improves performance of web application.
    • Avoid too many third party jquery controls rather make use of JQuery UI, which supports too many control within one js file.


Avoid round trip to server
In order to give user a lightning fast effect, it is important that you avoid round trip to server.  You can use:
  • Caching
  • JQuery Ajax

Tips for writing code in order to enhance performance.

1 VS.Net 2010 Code Analysis


Database Optimizing tips to improve website performance.
1. Thumb rule decrease as many joins as possible.  It will be very helpful in improving search query performance.
2. In order to avoid too many joins, make optimal use of "xml datatype".  That will help you to reduce needs of number of tables for small data structure, also be helpful in storing complex data-type.  (In summary, I am in love of xml datatype, If you know correct way to use that, you can optimize performance.)
3 Check out DB Optimization tricks
4 Use PL\SQL Programming instead of making too many DB Request.
One of the most resource efficient and performance improvement technique is to make use of PL\SQL Programming inside stored procedure to avoid round trip.  But be careful with this technique if you don't know how to use it efficiently, it may adversely affect performance.
Example: To Improve Performance through


Finally i want to say it is also important to check your asp.net web application architecture.  Try to identify what all bad architectural design was taken in past and how to rectify those in order to improve performance of your web application.  Its very important to design architecture of web application nicely.  I understand that it is not always possible to design things right at first point, but it is continuous improvement process, you should always keep on identifying things and correct it asap.  Hope my checklist had helped you too.

Please note: I have been writing this article since long and I am still in process of improving this article on regular basis.  Please share your suggestions and comments here so that it will help everybody to improve their website performance.  At present most of performance improvement topics here are purely related to asp.net web forms, but i will be going to make a list of asp.net mvc specific performance improvement checklist in my future article.  Thank you. :)

Sunday, September 23, 2012

Internet works for some sites and doesn't work for some sites

I know this is a Off topic for this blog, but it might help or remind you when you run into similar problem.

I was stuck with weird problem, Internet was working for some sites and was not working for some sites, I thought may be it could be internet problem, but it was NOT, my internet was working good.  Since i have habit of running my PC day and night i though PC might need some rest so restart my PC but things were not change even after restart.

Cause of Problem
The point i want to make here is my PC got infected with Virus.  Anytime you stuck in similar situation where your PC is behaving weird or start doing something unusual you should do a virus scan, since it could be virus which has made changes to registry and that is causing all sorts of problem in my case.

Solution
Best solution i personally believe when you feel that your PC is infected with virus is "Restore your system" to last good state, I do believe that antivirus are good and do good job, but i personally don't trust them 100%.

On my Win 7 PC, I did

  • Start > All Programs > Accessories > System Tools > "System Restore"
"System Restore" is a utility provided by Microsoft OS which saves a restore point automatically at regular interval of time. (Mostly when you install any programs.)  I know lots of people know about this option but when you are stuck in problem you try to find solution, but in this case i believe solution might not fix the things 100% and it is better to restore your system to last known good state.

System Restore program will allow you an option to select different date of restore point it has made and will restore your PC to that point
  • Good thing about System Restore is, it will not delete any of file created by you during this time period, but it will uninstall any of programs installed between that time frame.
  • After system restore, I have found everything on my PC is normal.


Other Solutions
  • Trust your antivirus, do scan your system and remove virus identified by your antivirus.
  • Open MSConfig tool (Run menu > MSConfig) and try to check "Startup" and "Service" tab to see is there any bad program getting started when you start your PC.
  • If you consider yourself as registry expert, then you can try to identify what changes are recently made to registry and validate those changes.
  • Use third party tools like CCleaner,... to check whether they can help you?

I personally like to restore my system back to good known state, that is the best solution whenever you run into problem.

Sunday, September 16, 2012

Error: Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF

I run into situation where i have to insert explicit value for identity column and run into following error, which is expected. Incase you run into similar situation here is the solution to insert value into Identity column in SQL Server.

Error: Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.

Cause of error: Trying to insert record including ID field where ID field is IDENTITY Column.

Solution: 
1) Make sure that you are in situation where you really want to insert ID, If that is not the requirement than simply remove ID field from your insert statement and try to execute the insert statement again.

2) Since i was sure that i want to insert ID in Identity column, here is solution...

SET IDENTITY_INSERT YourTableName ON

INSERT INTO YourTableName
(IDENTITY Column, Column1...ColumnN)
VALUES
(IDENTITY Value, Value1, ...., ValueN)

SET IDENTITY_INSERT YourTableName OFF

Note:
Make sure that your insert statement does include all column name list, otherwise you will run into this error.

Error: 
Msg 8101, Level 16, State 1, Line 1
An explicit value for the identity column in table 'Users' can only be specified when a column list is used and IDENTITY_INSERT is ON.


Wrong Insert Statement
INSERT INTO YourTableName
VALUES
(IDENTITY Value, Value1, ...., ValueN)

Correct Insert Statement
INSERT INTO YourTableName
(IDENTITY Column, Column1...ColumnN)
VALUES
(IDENTITY Value, Value1, ...., ValueN)

Saturday, July 21, 2012

Error: Database could not be exclusively locked to perform the operation

You might receive "Database could not be exclusively locked to perform the operation" or many error like such when you are trying to perform operation on database which is already been used by process or some other users.

In order to obtain "Exclusive lock" to perform some critical database operation when someone is already using database you can perform following steps as described below to solve your problem.

Earlier I have blogged in context of restore error, but it is not limited to only restore and since this is very common error you get stuck when you are trying to do some critical database operation i have decided to explain step by step so that it can help me and many others like me who are in same situation. :)


Solution to obtain exclusive locked to perform database operations.


Step 1: Disconnect Connection.
To do so:   File > Disconnect Object Explorer

Step 2: Connect Connection
To do so:  File > Connect Object Explorer

Step 3: Open "New Query" window and run following command
use master
Note: Above command will make your current database to master which is important before we run following sequence of command.

Step 4: Copy and paste following sequence of command in Query window.  Replace the word "MyDatabaseName" with Database name you are trying to get exclusive access.

ALTER DATABASE MyDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

ALTER DATABASE MyDatabaseName SET SINGLE_USER WITH ROLLBACK AFTER 30 

ALTER DATABASE MyDatabaseName SET SINGLE_USER WITH NO_WAIT

ALTER DATABASE MyDatabaseName SET MULTI_USER WITH ROLLBACK IMMEDIATE; 


You are now done and you can now try the command or operation you were trying to perform earlier which was giving you "Database could not be exclusively locked to perform the operation" error. 

Sunday, May 20, 2012

Whats new in Asp.net MVC 4

Looks like asp.net MVC 4 is coming up with lots of new developer friendly features.  Check out this video.

I feels that following features will make developers life lot more easier.

  • Combining multiple CSS and JS file request into 1 request with eliminating white space.
  • Url Resolution Enhancement
  • Entity Framework 4.3 Release
Check out all the features of Asp.net MVC 4

Monday, April 16, 2012

How to avoid multiple database request to improve performance

It is not good to execute multiple db request for loading single page.  Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database.

In order to improve performance you should execute single stored proc and bring multiple resultset in to single db request.  In this article i will explain you how to avoid multiple database request and how to bring multiple resultset into single db request.

Consider a scenario of loading a Product Page, which displays

  • Product Information and
  • Product Review Information

In order to bring 2 database request in single db request, your sql server stored proc should be declared as below.

SQL Server Stored Proc

CREATE PROCEDURE GetProductDetails
@ProductId bigint,
AS
SET NOCOUNT ON

--Product Information
Select ProductId,
ProductName,
ProductImage,
Description,
Price
From Product
Where ProductId = @ProductId


--Product Review Information
Select ReviewerName,
ReviewDesc,
ReviewDate
From ProductReview
Where ProductId = @ProductId




Asp.net, C# Code to bring multiple db request into single db request

Code Inside Data Access Class Library (DAL)

public DataSet GetProductDetails()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "GetProductDetails";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataSet dsResultSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);

try
{
    var conString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"];
    string strConnString = conString.ConnectionString;
    SqlConnection conn = new SqlConnection(strConnString);

    cmdToExecute.Connection = conn;

    cmdToExecute.Parameters.Add(new SqlParameter("@ ProductId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _productId));

    //Open Connection
    conn.Open();

    // Assign proper name to multiple table
    adapter.TableMappings.Add("Table", "ProductInfo");
    adapter.TableMappings.Add("Table1", "ProductReviewInfo");
    adapter.Fill(dsResultSet);

    return dsResultSet;              
}
catch (Exception ex)
{
    // some error occured. 
    throw new Exception("DB Request error.", ex);
}
finally
{
    conn.Close();
    cmdToExecute.Dispose();
    adapter.Dispose();
}
}



Code Inside Asp.net .aspx.cs page

protected void Page_Load(object sender, EventArgs e)
{
   if (Request.QueryString[ProductId] != null)
   {
      long ProductId = Convert.ToInt64(Request.QueryString[ProductId].ToString());  
   
      DataSet dsData = new DataSet();

      //Assuming you have Product class in DAL
      ProductInfo objProduct = new ProductInfo();
      objProduct.ProductId = ProductId;
      dsData = objProduct.GetProductDetails();

      DataTable dtProductInfo = dsData.Tables["ProductInfo"];
      DataTable dtProductReviews = dsData.Tables["ProductReviewInfo"];

      //Now you have data table containing information
      //Make necessary assignment to controls
      .....
      .....
      .....
      .....
      .....  

    }
}


Hope above code gave you basic idea of why it is important to avoid multiple db request and how to bring multiple recordset with single db request.

Saturday, April 07, 2012

Asp.net Security Considerations

If you are web developer or architect, I would recommend reading this ebook.  It explains how to make your asp.net website secured.   I believe not most of users need to consider "ALL" those points, but you should perform some of important points to secure your asp.net website.

I was planning to make a list of important considerations from this book, but since this book is very well written i personally like most of points i have read so far.

And finally if you have developed asp.net website which is accessible through internet, than check whether your website do pass against security scan.

Asp.net website security analyser 

Hope this book help you too :)

Sunday, March 11, 2012

How to be ProActive rather than ReActive in Software World

Many times people have habit of speaking be Proactive rather than Reactive and blah... blah...

I found a very good video giving an example on this, In a true sense.  This is what i say "Customer Care".

What i can say guy's be patient and listen to his keynotes till end.  This guy is true genius and thinking out of box.  I really enjoyed every bit of it.






Thursday, February 02, 2012

How to open and auto close JQuery UI Dialog box on click of Hyperlink or Anchor Tag

In this article i will be explaining, How to open and auto close and change content of JQuery UI Dialog box on click of Hyperlink or Anchor Tag.

I have assumed that you have already created VS.Net Web Project and add JQuery UI reference into your web project.  If you need help in adding JQuery UI into asp.net website, then please read my post on how to add JQuery UI into asp.net website

Create a asp.net content page and add following code
<a id="hlOpenMe" runat="server" href="#">Click Me to Open and auto close Dialog Box</a>
<br />
<b>Please wait for 5 Seconds and JQuery UI Dialog box will auto close.</b>
<br /><br />
<div id="dialog" title="My Dialog Title">
    <p>This is My Dialog box Description/Content</p>    
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


<script type="text/javascript">
    $(document).ready(function () {
        $("#dialog").dialog({ autoOpen: false });


        $("#<%=hlOpenMe.ClientID%>").click(
            function () {
                $("#dialog").dialog('open');


                //Change content on the fly
                ChangeMessage("Welcome to JQueryUI Dialog Box Example");


                //Auto Close JQueryUI Dialog Box
                AutoCloseDialogBox(5000);
                return false;
            }
        );


        function ChangeMessage(Message) {            
            $("#dialog").html(Message);
        }


        function AutoCloseDialogBox(WaitSeconds) {
            //Auto Close Dialog Box after few seconds
            setTimeout(
                function () {
                    $("#dialog").dialog("close");
                }, WaitSeconds);
        }
    });
</script>


Understanding above code
1) I have declared a simple asp.net hyperlink control (Since it has runat="server" it is asp.net control)
2) setTimeOut javascript function will cause dealy, this helps us to close JQuery UI dialog box after few seconds.
Syntax: setTimeout("javascript function declaration",milliseconds);
Example:
   setTimeout(
                function () {
                    $("#dialog").dialog("close");
                }, 5000);

Above line will cause a delay 5 seconds and then auto close dialog box.

Watch out Live Demo

For More on JQuery Tutorials

How to open and close JQuery UI Dialog box on click of Hyperlink or Anchor Tag

In this article i will be explaining, How to open and close JQuery UI Dialog box on click of Hyperlink or Anchor Tag

I have assumed that you have already created VS.Net Web Project and add JQuery UI reference into your web project.  If you need help in adding JQuery UI into asp.net website, then please read my post on how to add JQuery UI into asp.net website

Create a asp.net content page and add following code


<a id="hlOpenMe" runat="server" href="#">Click Me to Open Dialog Box</a>


<div id="dialog" title="My Dialog Title">
    <p>This is My Dialog box Description/Content</p>    
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


<script type="text/javascript">
    $(document).ready(function () {
        $("#dialog").dialog({ autoOpen: false });


        $("#<%=hlOpenMe.ClientID%>").click(
            function () {
                $("#dialog").dialog('open');
                return false;
            }
        );
    });
</script>


Understanding above code
1) I have declared a simple asp.net hyperlink control (Since it has runat="server" it is asp.net control)
2) $("#dialog").dialog({ autoOpen: false });  - By default dialog box will open on page load, this line will explicitly disallow dialog box to open on page load.
3) Inside hyperlink click event, I have wrote code to open JQuery UI dialog box.
        $("#<%=hlOpenMe.ClientID%>").click(
            function () {
                $("#dialog").dialog('open');
                return false;
            }
        );

Similarly if you want to close JQuery UI dialog box  change below line with "close" rather than "open"
                $("#dialog").dialog('close');

Watch out Live Demo


For More on JQuery Tutorials

How to open and close JQuery UI Dialog box on Button Click

In this article i will be explaining, How to open and close JQuery UI Dialog box on Button Click.

I have assumed that you have already created VS.Net Web Project and add JQuery UI reference into your web project.  If you need help in adding JQuery UI into asp.net website, then please read my post on how to add JQuery UI into asp.net website

Create a asp.net content page and add following code

<asp:Button ID="btnOpenMe" runat="server" Text="Click Me to open Dialog box" />


<div id="dialog" title="My Dialog Title">
    <p>This is My Dialog box Description/Content</p>    
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


<script type="text/javascript">
    $(document).ready(function () {
        $("#dialog").dialog({ autoOpen: false });


        $("#<%=btnOpenMe.ClientID%>").click(
            function () {
                $("#dialog").dialog('open');
                return false;
            }
        );
    });
</script>

Understanding above code
1) I have declared a simple asp.net button control
2) $("#dialog").dialog({ autoOpen: false });  - By default dialog box will open on page load, this line will explicitly disallow dialog box to open on page load.
3) Inside button click event, I have wrote code to open JQuery UI dialog box.

        $("#<%=btnOpenMe.ClientID%>").click(
            function () {
                $("#dialog").dialog('open');
                return false;
            }
        );

Similarly if you want to close JQuery UI dialog box  change below line with "close" rather than "open"
                $("#dialog").dialog('close');


Watch out Live Demo


For More on JQuery Tutorials

How to open JQuery UI Dialog box on Page Load - AutoOpen

In this article i will be explaining, How to open JQuery UI Dialog box on Page Load - AutoOpen.

I have assumed that you have already created VS.Net Web Project and add JQuery UI reference into your web project.  If you need help in adding JQuery UI into asp.net website, then please read my post on how to add JQuery UI into asp.net website

Create a asp.net content page and add following code
<div id="dialog" title="My Dialog Title">
    <p>This is My Dialog box Description/Content</p>
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


<script type="text/javascript">
    $(function () {
        $("#dialog").dialog();
    });
</script>

Understanding above code.
<div id="dialog" title="My Dialog Title"> - You can be able to change dialog title by editing title.

    <p>This is My Dialog box Description/Content</p> You can be able to change dialog description/message by editing paragraph tag.  You can write anything which is valid html inside div tag.


    $(function () {
        $("#dialog").dialog(); - Please note in above example, JQuery UI dialog box has ID as "dialog", so we have $("#dialog") and call dialog method to show dialog box.

By default JQuery UI dialog box opens on page load, show we haven't done anything specific to open it on page load.


Preview of code.


You can also show image or any valid html inside JQuery UI dialog box.  Here is the example.

Watch out Live Demo

For More on JQuery Tutorials

Wednesday, February 01, 2012

JQueryUI Demo and Tutorial for Asp.net Developers

This article contains all links for JQuery UI Demo and Tutorials for Asp.net Developers.

**Please note: I am in middle of making JQuery Tutorial, so this page will be updating frequently until this tutorial is complete, their is lot to come yet.  I will be using this post as a placeholder to track my progress and making tutorial

How to add JQuery UI to Asp.net Website

JQuery UI contains sets of controls and themes which you can simply add and start using it, just the way you can use any other third party jquery control.  Incase if you have used Asp.net Ajax Control toolkit in past, then Jquery UI controls are very similar to that.  Let me cut this discussion here and directly show how you can start using JQuery UI in asp.net website, later you can decide how helpful this is for your asp.net projects.

Step 1: Download JQuery UI
Click this link to Download JQuery UI


On Themes Page, click on Gallery tab and select the theme best suitable for your project, you can even customize its color and setting by clicking on edit button, ones you are done, click on download button.

On Download Page, on very right side you will find "Download" button. Its little confusing if you are visiting this page for first time.  Atleast i found it confusing, because i don't read all details :)   

Extract the .zip file, it comes up with 3 folders and 1 index.html file
  1. css folder
  2. development-bundle folder and
  3. js folder
The only folder we are interested in is css folder.  Copy "css" folder and put in your VS.Net Solution directory.  (Incase you haven't created a VS.Net Web Project Please create it now)

Ones you have copied "css" folder inside VS.Net solution directory, click on "Show All Files" from solution explorer.

This make "css" directory to appeared in VS.Net Solution, now right click "css" directory and select "Include in Project" option.

You are done adding necessary files to start "JQueryUI".

Step 2: Open Master Page of your project and add following lines just before </Head>
<%--For JQuery--%>
<script type="text/javascript" language="Javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<%--For JQuery UI--%>
<script type="text/javascript" language="javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>

Step 3: Add CSS File reference in your project.  You can do so by simply drag and drop .css file from css folder.
<link href="Styles/css/blitzer/jquery-ui-1.8.17.custom.css" rel="stylesheet" type="text/css" />

That's it you are ready to use JQueryUI.

Incase you want to test whether JQueryUI is working or not simply create one asp.net page and add following lines of code in your content page.
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


<script>
    $(function () {
        $("#dialog").dialog();
    });
</script>

And this will display JQueryUI dialog box on page load.
We will learn how this code works and more in my next coming blog post

Monday, January 23, 2012

How do I remove my personal details from Google search?

If you want to remove your personal details/data from google search results try use some of these tools:
1. Wizard Removing Content From Google
2. Keeping personal information out of Google.
3. User Webmaster Tools for remove data:

If you don’t already have one, then
1) Create a Google account (I am sure you might have one, if not create a gmail account)
2) Go to this URL: https://www.google.com/webmasters/tools/removals



3) Click on "Create a new removal request" button
4) Type in URL you would like to remove.
That's it you are done.

Saturday, January 21, 2012

JQuery Ajax DB Call to Retrieve data based on user Criteria

In this article, i will be retrieving data from database with asp.net web service using jQuery Ajax.

If you are new to jQuery and don't know anything about it, I will recommend you to first read following articles before reading any further.


In this article we will take input country name and display region information. Check out Live Demo

Step 1: Create Asp.net Web Application


Step 2: Open Site.Master and include jQuery Reference by adding below line just before </head> tag.
<!--Include JQuery File-->
<script type="text/javascript" language="Javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>




Step 3: Open "Default.aspx" and add following code
I have added here h2 title tag, asp.net button, textbox and label.  Please note, that i have declared ShowRegionInfo function, I will be calling javascript this function, which will internally make jQuery Ajax call to asp.net web service.



<h2>Example 4: JQuery DB Call to Retrieve data based on user Criteria </h2>
<br />
<b>Retrieve region based on country name</b><br /><br />
Enter Country Name: <asp:TextBox ID="txtCountryName" runat="server" Text=""></asp:TextBox><br />
<asp:Button ID="btnGetMsg" runat="server" Text="Click Me" OnClientClick="ShowRegionsInfo();return false;" /><br />
<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>


Step 4: Add new folder to solution named "WebService"


Step 5: Right click on "WebService" folder and click add new item, to add new web service.


Step 6: Add code to make database call to retrieve region data using jQuery Ajax.  Please add following code inside "wsJQueryDBCall.asmx.cs" file
Add following namespaces

using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Text;


Add following code



[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class wsJQueryDBCall : System.Web.Services.WebService
{


    [WebMethod]
    public string ReadRegion(string CountryName)
    {
        String strConnString = ConfigurationManager.AppSettings["connStr"].ToString();


        String strQuery = "Select Region " +
                            "from Regions " +
                            "Inner Join CountriesNew on CountriesNew.CountryId = Regions.CountryId " +
                            "where UPPER(CountriesNew.Country) = @CountryName";


        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@CountryName", CountryName.ToUpper());
                cmd.CommandText = strQuery;
                cmd.Connection = con;
                con.Open();
                SqlDataReader sdr = cmd.ExecuteReader();
                StringBuilder sb = new StringBuilder();


                if (sdr.HasRows)
                {
                    sb.Append("" + CountryName + " has following regions:
");



                    while (sdr.Read())
                    {
                        sb.Append(sdr["Region"].ToString() + "
");

                    }
                }
                else
                {
                    sb.Append("No Records found");
                }


                con.Close();


                return sb.ToString();
            }
        }
    }
}

As you have noticed ReadRegion Method is regular method which takes input country name and makes database call to retrieve region data from sql server database and return result as appended string of region.


Important Note:  Please UnComment line
[System.Web.Script.Services.ScriptService]
In order to allow this Web Service to be called from script, using ASP.NET AJAX



Step 7:  Open "Default.aspx" and Write jQuery function to make webservice call to retrieve data from database.



<script type = "text/javascript">
    function ShowRegionsInfo() {


        var pageUrl = '<%=ResolveUrl("~/WebService/wsJQueryDBCall.asmx")%>'
            
        $.ajax({
            type: "POST",
            url: pageUrl + "/ReadRegion",
            data: "{'CountryName':'" + $('#<%=txtCountryName.ClientID%>').val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccessCall,
            error: OnErrorCall
        });


    }


    function OnSuccessCall(response) {
        $('#<%=lblOutput.ClientID%>').html(response.d);
    }


    function OnErrorCall(response) {
        alert(response.status + " " + response.statusText);
    }
</script>


Understanding jQuery Ajax call parameter

Now, run the web application and input your country name and hit button to see region which is retrieved from sql server database.


Check out Live Demo of Calling Webservice using JQuery Ajax Example

More JQuery Tutorials

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape