Wednesday, November 25, 2015

ASP.NET MVC Do's and Dont's/Best practices

Introduction

ASP.NET MVC (Model-View-Controller architectural pattern) is getting popular day by day, due to Separation of code, extensive templates, data-binding, test-driven development (TDD), Scaffolding and no view state like features, it has REST and SEO support nature. it is really an plugged and extensible framework. We get complete control over HTML with MVC support.  But before going to code on ASP.NET MVC we should take care of some Do's and Dont's or best practices. Here i am explaining some Do's and Don'ts of ASP.NET MVC code
         Many developers/organizations thinking of migrating their exiting application to ASP.NET MVC, This article will help them to understand code facts

Do's and Dont's/Best Practices




1. Business logic should be the part of Model only
Before start code on MVC we should make understand that Business logic should be reside in Model only, it will add your security and code duplication can be avoided. The view load faster as there is no business present in view.

2.  Use only specific view engine
View engines are used to create HTML markup from your view, it is the combination of HTML and programming code, ASP.NET has its own asp.net engine where as ASP.NET MVC has its razor engine. You should only use your specified view engine, it will increase application performance, see below snippet
protected void Application_Start()
{
    ViewEngines.Engines.Clear(); //clear all engines
    ViewEngines.Engines.Add(new RazorViewEngine());
}
3. Create separate assembly for Model
if the application is large and complex then make separate assembly for Model to avoid An unfortunate mishap.  Basically Model should contain business logic, Validation part, session maintenance and data logic part.

4. HTML and data access part should be done from VIEW only
As we know VIEW is the presenter part and it should be very flexible. VIEW should not contains any business logic and session maintenance, use ViewData to access data in View.

5.  Business logic and data access should not exist in ControllerViewData
Controller should be only responsible for calling model, Prepare view, return view, redirect to action etc

6. Delete Demo code from application when you create it
Delete AccountController and all other auto created code from application it will slow down the performance

7. Disable request validation
Request validation validate the request submitted to server and avoid the potential dangerous characters, but it will also block the contents to post HTML markup tags to the server, so disable it, with the help of ValidateInput we can do it, see below snippet
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Name")]TestEmployee clsEmp)
{
//code goes here
}
8. Master view model may be use for Uniformness
In ASP.NET master pages are used to maintain uniformness in look and feel, same way in ASP.NET MVC we use master view for it.

9.  Data Annotations can be used for server side validation
Use System.ComponentModel.DataAnnotations namespace for server side validation, just use it in model with attribute, see snippet
Public class GetAddress
{
    [Required(ErrorMessage="Address is mandatory")]
    public string Address { get; set; }
}
10. Use extension methods
Extension method help us to simplify LINQ queries and improve application performance, these methods are the static methods and access with this keyword.

11. Remove un-necessary folders and references
When you start creating new ASP.NET MVC application, visual studio does create lot of un-necessary folders and references that are not useful, we can remove them to avoid additional overhead on application

12. Do Bundling and Minifying CSS Files
Bundling and Minifying is the process of minimizing the size of referenced file like .JS, .JSON, .CSS we can reduce the size of such files which will ultimately boost the application performance, in Bundling we merge all CSS in one file and same done for .JS and .JSON file in Minification we remove extra spaces and enters from file and reduce file size

13. For each view there should be a view model
Do you have view ? if yes then create ViewModel. it should used only for data binding and may not contain any presenter code. ViewModel is essential when we want to show some data in different format, in such case view only responsible for present and ViewModel does the job of data transformation

14. Design Routing properly not URL re-writing
URL routing is very much different than URL re-writing, may developers consider them as unique thing. URL routing does not create new URL for old URL but it maps resources with route

15.  Use ViewData and ViewBag for large data storage
If you want to work with lage data, spread sheets, dashboards or volume data sources then ViewData is good option, both views and controllers can easily access ViewData and ViewBag

16. For current and the subsequent requests use TempData
TempData is very short-lived instance, it should use only For current and the subsequent requests.

17. Use Glimpse, fidder, F-12 like package to monitor and improve performance of ASP.NET MVC
Glimpse NuGet package provide detail diagnostic information of ASP.NET apps, where as fidder, F-12 shows you client side activities, more information can be found on Here

18.  Deploy code in Release mode
Code with Release is more compressed than debug mode as it does not conain .pdb file so less memory is utilized by it

19. Remove unnessary HTTP headers
Remove X-AspNetMvc version from global.asax.cs as it will not provide no direct benifit and un-necessarily use small amount of bandwidth, see below snippet
MvcHandler.DisableMvcResponseHeader = true;
20. Use CDN (Content Delivery Networks)
CDN is helping you to download your supportive things (like required .JS, .CSS, .JSON files) from nearest location/server, so travelling time of resources from one location to another will save significantly.

21. Use validationSummary to show all validations in one snap
see below method to use to show all validation in one snap
<%= Html.ValidationSummary() %>
22. Razor is recommended
We know ASP.NET MVC support multiple engines but Razor is recommended by Microsoft as it is light weight and it has very simple syntax

23. Do you want some repetitive UI to be display on each page ? use Partial view
Partial view is like a user control in classic ASP.NET, you can use them if you want to show piece of UI on each page

24. If you are not using bundles and WebAPI then simple remove their associated files
Go to App_start directory and remove BundleConfig file, now go to Application_Start method, in Global.asax.cs and remove the line BundleConfig.RegisterBundles, same thing you can do for WebApiConfig

This is not a detail level document, this document at least need a basic knowledge of ASP.NET MVC, i will cover more detail documentation in next version of this document till then enjoy this stuff

Suggestion and Queries are always welcome

Thanks
koolprasad2003
Read More » Rate this posting:
{[['']]}

Monday, October 26, 2015

A potentially dangerous Request.Form value was detected from the client occurred in ASP.NET 4.0



Error


Problem :
         If you are using ASP.NET 4.0 and  you tried to enter some non-encoded HTML content/text like "( )&< > " in Textbox then browser throws "A potentially dangerous Request.Form value was detected from the client" exception

Cause :
        ASP.Net By default validates all input controls for potentially unsafe contents and you entered text is non-encoded HTML content which is like mark-up text, Thus it disallows such content by throwing the above Exception. By default it is recommended to allow this check to happen on each postback

Resolution :
        There are following resolution for this error
1. In many cases if you want to all such mark-up text to any particular page then you can take use of page directive and make 'ValidateRequest '  to false in page directive
see below snippet
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false" %>

2. If you want to disable this check throughout your Web Application you’ll need to set it false in your web.config section, see below snippet
 <system.web>
      <pages validateRequest="false" />
 </system.web>

3. You can allow mark-up as input for specific pages instead of the whole site by putting it all in a <location> element. This will make sure all your other pages are safe, see below web.config file
<location path="Code/.aspx">
    <system.web>
      <pages validateRequest="false" />
    </system.web>
  </location>
Above snippet will take care of your all .aspx pages inside Code folder

4. If you are using ASP.NET 4.0 then above all solutions will not help you alone, you need to take help of more settings, you need to keep your requestValidationMode to 2.0, see below web.config snippet
  <location path="Code/.aspx">
    <system.web>
      <pages validateRequest="false" />
      <httpRuntime requestValidationMode="2.0" />
    </system.web>
  </location>

Just re-start your IIS and your problem is resolved !!!
Read More » Rate this posting:
{[['']]}

Wednesday, March 4, 2015

HTTP Error 404.17 : The requested content appears to be script and will not be served by the static file handler

You may got error while browsing your ASP.NET website, which reads  "HTTP Error 404.17 : The requested content appears to be script and will not be served by the static file handler "

Please see below error snap



Probable causes:

 There are many causes behind this problem
1.  HTTP Handler configured to handle the request has certain preconditions set, but its Application pool does not meet some or all of these preconditions, in simple words Application pool's .NET framework is not set properly to the application in which it is compiled (If my application developed in 4.5 and I am attaching application pool with framework 2.0)

2. If my application is migrated from IIS 6 then My Application pool should running in Classic Mode, with enable 32 bit mode options

3. Required .NET framework has restriction in 'ISAPI and CGI restrictions' in IIS

Solutions :

Problem can be resolved by following steps
1. Open IIS manager (Go to start - Run - type 'INETMGR')
2. Select the Server Name (System Name)
3. Select ISAPI and CGI restrictions in right side pane
4. Allow the Not Allowed restrictions for required framework
5. If your required framework will not exist in ISAPI and CGI restrictions  then you need to re-registered framework with following command
see below snippet, to know how to allow ISAPI and CGI restrictions 


6. Go to Start - Run put following command in Run window

C:\Windows\Microsoft.NET\Framework\v4.0.30319 \aspnet_regiis -I

see below snippet


Here I have given example for .NET Framework 4.0 you can use same command for any .NET framework.

7. Set required .NET version in application pool
8. Enable '32-Bit Applications' in application pool
9. Restart IIS

That all, Now try to browse the same website, we have resolved the bug. 
Read More » Rate this posting:
{[['']]}

Monday, August 11, 2014

Protect word file using C# : Word automation step by step

Security:
     Security is the Most heard and most important 'keyword' in IT industry, Everyone want their documents play a secure travel, should not attack by spam or any intruder. Really, security is the main concern in now world, we can make word file secure by using password protection.
word security


What is our aim:
       protect word file using C# word automation

What we need:
      C#, Interop libraries

What are the different security can be assigned to word file:
         There are multiple types security we can assign to word file
1. Read-only protection
2. Comment only protection
3. Track revision protection



Read Only protection:
It Allow read-only access to the document.

Comment only protection:
It allows Allow only comments to be added to the document.

Track revision protection:
It Allow only revisions to be made to existing content.

Lets code it, (Protect word file):
To protect word file programmatically we need to add reference of interop assemblies in our code, I have explained it in my previous article you can check here
checkout below code snippet to protect file as 'ReadOnly'
 
         object objMiss = System.Reflection.Missing.Value;  
         object fileToOpen = Application.StartupPath + "\\test.doc";  
         object szPassword = "Pass";  
         object bFalse = false;  
         object bTrue = true;  
         //Start Word and create a new document.  
         objApp = new Word.Application();  
         objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,  
                         ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,  
                         ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);  
         if (objDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)  
         {  
           objDoc.Protect(Word.WdProtectionType.wdAllowOnlyReading, ref bFalse, ref szPassword, ref bFalse, ref bTrue);  
           objDoc.Save();  
           MessageBox.Show("Word document Protected successfully (for Read only)!", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);  
         }  
         else  
         {  
           MessageBox.Show("Word document is already protected !", "Word Protect", MessageBoxButtons.OK, MessageBoxIcon.Information);  
         }  

In above code snippet we have used method  Protect of document class and pass 'wdAllowOnlyReading' enumeration and just save document with password. it is enough to accomplish the task. so simple.
like wise we can protect document with  'Comment ' and 'TrackRevision' protection

Unprotect word file:
Now after protection we can unprotect word file using Unprotect method of document class
see below snippet
 
         object objMiss = System.Reflection.Missing.Value;  
         object fileToOpen = Application.StartupPath + "\\test.doc";  
         object szPassword = "Pass";  
         object bFalse = false;  
         object bTrue = true;  
         //Start Word and create a new document.  
         objApp = new Word.Application();  
         objDoc = objApp.Documents.Open(ref fileToOpen, ref objMiss, ref objMiss, ref objMiss, ref objMiss,  
                         ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss,  
                         ref objMiss, ref objMiss, ref objMiss, ref objMiss, ref objMiss);  
         if (objDoc.ProtectionType != Word.WdProtectionType.wdNoProtection)  
         {  
           objDoc.Unprotect(ref szPassword);  
           objDoc.Save();  
         }  

So, with the above example we can say it is easy to protect and unprotect document programmatically.
You can get full source code here

Note:
    As we know word is heavy object so do not forget to close and dispose it, I have explained it in my previous blog

Summary:
Someone said, there is always scope for improvement. so I think its a on going think for programming too. Finally we have ready with our code, it is very simple to protect a file with customized password, still many things to discover with word and C#, we can them one by one in near future till then enjoy this stuff and be happy with C# and Word

Suggestions and comments/doubts are always welcome

Happy Programming
- Prasad
Read More » Rate this posting:
{[['']]}

Wednesday, July 23, 2014

Create a word table using C# : Word Automation step by step

Our Aim: Create a word file programmatically and create a table in it


Things we need : C#, Word interop object


Word Automation


Getting started

Many times in real world scenario, we need to create our reports in word file, Means we need to export 'things' to word file. In such cases we need to create and write word file programmatically and to accomplish the task .NET will help you, COM winword interop library will play a role for you.

follow the steps below to know how to do it
1. Create a simple windows/web/wpf application (You may take console application or class library too, here I have used windows application in C# with Visual studio 2010)
2. Now just right click on solution explorer, click on Add reference and select COM tab
3. Select Word com library (If you have word 2007 installed you will see 12.0 object library, if you have word 2010 installed you will see 14.0 object library and for word 2013 you will see 16.0 object library)
see below snap

4. Add reference, Now in reference folder of solution explorer you will see 'Microsoft.Office.Interop.word' library added.
5. Now we are ready to code, first we need to create a new word document using C#
6. Import word namespace and create word object
see below snap
 
   Word._Application objApp;  
   Word._Document objDoc;  
   objApp = new Word.Application();  
   objApp.Visible = true;  
   objDoc = objApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);  

With the help of above code we can able to create a new word file. (Note: Do not ever create new object of word document.) .Visible property will open a new word file.
7. Now to add a new table in word document, we need to define bookmark first (which is the range of word document from which we need to start writing the things)
see below snap to define default bookmark of word document

 object objMiss = System.Reflection.Missing.Value;  
 object objEndOfDocFlag = "\\endofdoc"; /* \endofdoc is a predefined bookmark */  

8. Yes, we have successfully defined 'end of doc' flag, now we can first add some caption to table with the help of Paragraph object (Paragraph object is a object which used to write some text in word document)
see below snap

 Word.Paragraph objPara1; //define paragraph object  
 object oRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; //go to end of the page  
 objPara1 = objDoc.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document  
 objPara1.Range.Text = "Test Table Caption"; //add some text in paragraph  
 objPara1.Format.SpaceAfter = 10; //defind some style  
 objPara1.Range.InsertParagraphAfter(); //insert paragraph  

Here we have define a paragraph and insert that paragraph to end of the document.
9. Now we need to define a rows and columns for table that we need to draw. Here I have draw a table with 2 rows and 2 columns
In code, Simply go to the end of the document and create 2X2 table, see below snippet

  Word.Table objTab1;  
       Word.Range objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;  
       objTab1 = objDoc.Tables.Add(objWordRng, 2, 2, ref objMiss, ref objMiss);  
       objTab1.Range.ParagraphFormat.SpaceAfter = 6;  
       int iRow, iCols;  
       string strText;  
       for (iRow = 1; iRow <= 2; iRow++)  
         for (iCols = 1; iCols <= 2; iCols++)  
         {  
           strText = "r" + iRow + "c" + iCols;  
           objTab1.Cell(iRow, iCols).Range.Text = strText;  
         }  
       objTab1.Rows[1].Range.Font.Bold = 1;  
       objTab1.Rows[1].Range.Font.Italic = 1;  

 Here we have create a 'word.table' object and add some text with the help of Range object
 
  //Add text after the chart.  
       objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;  
       objWordRng.InsertParagraphAfter();  
       objWordRng.InsertAfter("THE END.");  

We have done with the task. lets checkout the final code as Whole
C#

checkout here,
       object objMiss = System.Reflection.Missing.Value;  
       object objEndOfDocFlag = "\\endofdoc"; /* \endofdoc is a predefined bookmark */  
       //Start Word and create a new document.  
       Word._Application objApp;  
       Word._Document objDoc;  
       objApp = new Word.Application();  
       objApp.Visible = true;  
       objDoc = objApp.Documents.Add(ref objMiss, ref objMiss,  
         ref objMiss, ref objMiss);  
       //Insert a paragraph at the end of the document.  
       Word.Paragraph objPara2; //define paragraph object  
       object oRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; //go to end of the page  
       objPara2 = objDoc.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document  
       objPara2.Range.Text = "Test Table Caption"; //add some text in paragraph  
       objPara2.Format.SpaceAfter = 10; //defind some style  
       objPara2.Range.InsertParagraphAfter(); //insert paragraph  
       //Insert a 2 x 2 table, (table with 2 row and 2 column)  
       Word.Table objTab1; //create table object  
       Word.Range objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; //go to end of document  
       objTab1 = objDoc.Tables.Add(objWordRng, 2, 2, ref objMiss, ref objMiss); //add table object in word document  
       objTab1.Range.ParagraphFormat.SpaceAfter = 6;  
       int iRow, iCols;  
       string strText;  
       for (iRow = 1; iRow <= 2; iRow++)  
         for (iCols = 1; iCols <= 2; iCols++)  
         {  
           strText = "row:" + iRow + "col:" + iCols;  
           objTab1.Cell(iRow, iCols).Range.Text = strText; //add some text to cell  
         }  
       objTab1.Rows[1].Range.Font.Bold = 1; //make first row of table BOLD  
       objTab1.Columns[1].Width = objApp.InchesToPoints(3); //increase first column width  
       //Add some text after table  
       objWordRng = objDoc.Bookmarks.get_Item(ref objEndOfDocFlag).Range;  
       objWordRng.InsertParagraphAfter(); //put enter in document  
       objWordRng.InsertAfter("THIS IS THE SIMPLE WORD DEMO : THANKS YOU.");  
       object szPath = "test.docx";  
       objDoc.SaveAs(ref szPath);  

Summing Up
So, we have seen with the help of bit code, we can develop a nice word table application.
If you want to download source code then you may follow the link
Click here to download Source Code

Finally
COM interop is not a single cup of tea, There are thousands of things needs to discuss, we can cover them one by one in later article
Suggestions and Doubts are welcome.

Thanking You
-Prasad
 
Read More » Rate this posting:
{[['']]}

Tuesday, June 17, 2014

Simple encryption in .NET using XOR technique

Passwords are essential thing in virtual world, it is the thing which keeps you safe, If someone else gains access to your account, they may cause you a great deal of trouble - perhaps deleting your files,  hack other systems or may stolen crucial data from your system.
so while development a big/small and web/windows application you need to keep password for your account. A password with a plain text is always a danger since it can be easily Move stealthily by someone so, we need to make our plain text password to some tricky thing and thus here we need some type of 'ENCRYPTION'.
         
Encryption

Many times we need to encrypt the string in our application, it may be used for login password, transaction password, secret key etc.
In this post, I will explain how to encrypt a string using C# with XOR encryption technique
.NET provide inbuilt encryption technique using 'System.Cryptography' namespace and various in-built encryption algorithms like,
1.AES
2.Blowfish
3.DES
4.Triple DES
5.Serpent
6.Twofish
7.Camellia
8.CAST-128
9.IDEA,RC2,RC5,SEED,Skipjack,TEA,XTEA etc

Here we go for some different technique apart from above algorithms

XOR encryption (exclusive disjunction (XOR) operation):
The XOR operator is extremely common and execute with the help of binary operations.
One of the cool things about XOR encryption is that when you apply it twice, you get back the original string
In this encryption we convert our Plain text and key to 8-bit ASCII format and then apply X-OR operation on them and same thing is done for decryption.

Let's Cook:
Things we need : C# windows/web application
Write a function in C# which accept a plain text and a key to encrypt the text
see below snippet
 
     public string EncryptDecrypt(string szPlainText, int szEncryptionKey)  
     {  
       StringBuilder szInputStringBuild = new StringBuilder(szPlainText);  
       StringBuilder szOutStringBuild = new StringBuilder(szPlainText.Length);  
       char Textch;  
       for (int iCount = 0; iCount < szPlainText.Length; iCount++)  
       {  
         Textch = szInputStringBuild[iCount];  
         Textch = (char)(Textch ^ szEncryptionKey);  
         szOutStringBuild.Append(Textch);  
       }  
       return szOutStringBuild.ToString();  
     }  

Now we have ready with the code in which we have accept the plain text and key to encrypt the text. Finally we have apply XOR operation on plain text
Above function will give you Encrypted string and Same function with same key will return your Decrypted string
I have call above function and pass plain text and a key to it.

 txtEncryptedText.Text = EncryptDecrypt(txtPlainText.Text, 200);  

I got following result, see below snaps

Excryption

Now to Decrypt the encrypted string just call same function and pass the encrypted string to it (Do not change encryption key)
Now this simple encryption is ready to use anywhere you want.
 
4107687
Read More » Rate this posting:
{[['']]}

Monday, June 2, 2014

How to resolved error 'Make sure AjaxControlToolkit. Properties. Resources. NET4.resources was correctly embedded'

Do you want to use AJAXControltoolkit 4 ? Are you stuck with following error occurred when you run your code

Error Message:
Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "AjaxControlToolkit.Properties.Resources.NET4.resources" was correctly embedded or linked into assembly "AjaxControlToolkit" at compile time, or that all the satellite assemblies required are loadable and fully signed.

Cause:
This error occurred when An unhandled exception was generated during the execution of the current web request, basically when you use any AJAX control but does not refer a ajax library in your page then Ajaxcontoltoolkit unable to load reference of that control from System.Qeb.UI.Contol namespace and hence it produce such error

Resolutions

Add "Script Manager" in ASPX page as below

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </cc1:ToolkitScriptManager>

OR

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


Hope it Helps to resolve the issue
Read More » Rate this posting:
{[['']]}