Wednesday, November 28, 2012

How to implement data annotation in MVC Razor?


Validation  :

Validation is most important process for any of the application. This process prevents wrong input to the application. For generating the meaningful output it is must that input should be meaningful because based on input only application generates output.

Like other application we can also implement validation process for our MVC application also, in this article, I am explaining – How to implement validation using data annotation in MVC application.

To implement validation I have used Data annotation, for this first we need to use “System.ComponentModel.DataAnnotations” namespace in our application. Here I am giving step by step implementation.

Step1:

Create one simple MVC Application, for this open Visual Studio and select “New Project” option then select “Asp.Net MVC Application Template”.

After creating new application you will find default MVC folder structure.

Step2:

Now right click on “Models” folder and add one Class, I have added by named- “EmployeeModels.cs”.

Here I have declared some properties like this-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;  

namespace DataAnnotationArticle.Models
{
    public class EmployeeModels
    {
        public int ID { get; set; }
        

       //Validation for empty input
        [Required(ErrorMessage ="First Name can't be empty.")]
        public string FisrtName { get; set; }



       //Validation for length of string
        [StringLength(10, ErrorMessage = "Last Name length can't be greater than 10.")]
        public string LastName{ get; set; }
       
    }
}
 

As you can see that I have added reference of  “System.ComponentModel.DataAnnotations” Namespace which will help us to implement validation over data using data annotation.

For this I have set some validation over properties like this-

        [Required(ErrorMessage ="First Name can't be empty.")]
        public string FisrtName { get; set; }

        [StringLength(10, ErrorMessage = "Last Name length can't be greater than 10.")]
        public string LastName{ get; set; }


We have other properties also based on our need we can implement other validation.

Step3:

Now add one controller, for this right click on “Controller” folder and click on “Add Controller” option, I have added by named- “EmployeeController.cs”. I have written controller code like this-

public ActionResult EmployeeView()
        {
            return View();
        }


Now we have to bind this ActionResult with one View.

Step4

To bind this ActionResult with View, Just right click on “EmployeeView()“ and you will get menu list here click on “Add View …” option after that you will get one dialog, like this-


View


Fill the details here like I have given Now Finally say “OK”, then View will be created automatically with following lines of code-

@model DataAnnotationArticle.Models.EmployeeModels

@{
    ViewBag.Title = "EmployeeView";
}

<h2>EmployeeView</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>EmployeeModels</legend>

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

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

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

<div>
    @Html.ActionLink("Back to List", "Index")
</div>


Here we can see that, one user input form is generated with validation. This is because of “Create” option which we have set at the time of view creation.   For validating user input code is already written, this code will perform user validation based on this JavaScript files-

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>


Finally our solution explorer structure will be like this-



MVC


Now you are done, to test the application just run your application and give some invalid input to the control like I have given , Here we can see the output-




MVCDataAnnotation



Here we can see that the validation which we have given in EmployeeModels.CS that is taking place for wrong input. Like this we can validation other controls also.




Thanks


Tuesday, November 27, 2012

How to add ToolTip for DropDownList Items?

  
ToolTip-

ToolTip is a small piece of information, which is used to show some idea or information about control and control's functionality.  This is most important when we are using icons for performing the operations. In every application it plays very important role either for web applications or windows applications.

Generally it is invisible but when we put mouse over any control then related ToolTip automatically gets visible.

In this article, I am explaining - How to add ToolTip for DropDownList Items?

Generally DropDownList doesn't have any direct property or method to set ToopTip for DropDowbList items; here I am giving simple code to add ToopTip for DropDownList items.

Write this code in Page_Load() event-

 protected void Page_Load(object sender, EventArgs e)
    {
        foreach (ListItem  item in DropDownList1.Items)
        {
            //Adding ToolTip for each item of DropDownList
              item.Attributes.Add("title", "item - "+ item.Text );
        }
    }


In above code, I have used foreach loop to iterate each item of DropDownList. Here insidse loop, I am using Attributes.Add() method to add title (ToopTip) to each item.
    
    //Adding ToolTip for each item of DropDownList
   item.Attributes.Add("title", "item - "+ item.Text );


 Here "title" is client side property of controls, using this property ToolTip can be added for any controls.  Using Attributes.Add() method we can also add any other client side method to any control.
 
The output of this code will be this this-


ToolTip

Thanks


How to disable back button of browser?


This is common requirement for all the web application to disable back button of browser after log-out. But there is no direct method or property to disable back button of browser. This only depends on browser cache or history, if browser contains any history or cache then back button will be active after log-out also.

Here I am explaining - How to disable back button of browser?

This can be possible using only after clearing history or cache of browser.
or
Don't allow browser to keep history or cache.

For this we can add this code for all the pages to which we don't want to allow cache.

Here is code-

  protected void Page_Load(object sender, EventArgs e)
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
            Response.Expires = -1000;
            Response.CacheControl = "no-cache";
        }



 In this code, I am written code to disallowing browser to cache the page. So that even after browsing the page browser will not keep page as cache or history.

This code should be included for all the pages.


Thanks

Friday, November 2, 2012

How to change NewDataSet xml root name while creating xml using WriteXml() method of Dataset?


This is default behavior of WriteXml() method when we create xml then it adds  <NewDataSet> node as root xml node and <Table> as child node. In this article, I am explaining- How to change <NewDataSet> xml root name while creating xml using WriteXml() method of Dataset?

Let first see the default case-

Suppose you we have one DataSet object ds and we are filling it will data source, like this-

Dataset ds= new DataSet();
ds= datasource;


After that we are using WriteXml() method to create XML, like this-

ds.WriteXml("FileName");

Then in this case output will be like this-

<NewDataSet>
  <Table>
    <Emp_ID>717</Emp_ID>
    <Emp_Name>Jitendra Faye</Emp_Name>
    <Salary>35000</Salary>
  </Table>
----------
----------
----------
</NewDataSet>


Here we can see that <NewDataSet> and   <Table> is default tag here.

Now to change these default tag follow this code, Here I am changing <NewDataSet> tag as <EmployeeRecords> tag and <Table> tag as <Employee> tag.

Here is code-

Dataset ds= new DataSet();
ds= datasource;


//Giving Name to DataSet, which will be displayed as root tag

ds.DataSetName="EmployeeRecords";

//Giving Name to DataTable, which will be displayed as child tag

ds.Tables[0].TableName = "Employee";

//Creating XML file
ds.WriteXml("FilePath");


Now after executing this above code generated XML file will be like this-

<EmployeeRecords>
  <Employee>
    <Emp_ID>717</Emp_ID>
    <Emp_Name>Jitendra Faye</Emp_Name>
    <Salary>35000</Salary>
  </Employee>
----------
----------
----------
</EmployeeRecords>



Here we can see that DataSet name is coming as root tag and DataTable name is coming as child tag.

Note-

Before giving name to DataTable (ds.Tables[0].TableName) first check that it should not be null otherwise it will cause an error.



Thanks


Thursday, November 1, 2012

How to edit word document using Asp.Net?


Problem -
 

Editing word document is not an easy task in ASP.Net, because we don't have any direct option to open server copy of word document. When we open any word document from server machine then first that document is downloaded to client machine's temp folder and then it is displayed. So if we will make any changes to that opened document then that changes will be saved in only client machine not in server machine.
 

Means the changes will not be reflected directly to server copy of word document.   
 

I have done some RND in this problem and came with one workaround. Hope this solution will help you.


Workaround-

There are some steps for this workaround.

Step 1: Store your document in any server folder.

Step 2: Read that document from server and convert to HTML Document.

Step 3: Now load converted HTML document to any HTML editor, for this you can use any free editor, there are lot of free editors are available in the market you can use anyone.

See this link for free HTML editors -

http://www.techsupportalert.com/best-free-html-editor.htm
Step4: Start editing document which is displayed in HTML editor using HTML editor ToolBox.

Step 5: After editing document get updated data from HTML editor and load to MemoryStream object.

Step 6: Finally again convert that MemoryStream object data to word file.

By following these steps you can edit word document online for this there is no need to use any paid third party controls.

Code Implementation-

For this implementation, I am using following tools-

1. Aspose DLL –   For converting Word document to HTML document and vice versa.
(I am using evaluation copy)

2. nicEditor HTML Editor - for showing and editing converted HTML document.
(It is free)

Now I have designed .aspx page like this-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EditDocument.aspx.cs" Inherits="OnlineEdit.EditDocument"
    ValidateRequest="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="NicScript/nicEdit.js" type="text/javascript"></script>
    <script type="text/javascript">
        bkLib.onDomLoaded(function () {
            new nicEditor({ fullPanel: true, iconsPath: 'NicScript/nicEditorIcons.gif' }).panelInstance('docArea');
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table border="1">
            <tr>
                 <td>
                     <textarea cols="100" rows="20" id="docArea" runat="server"></textarea>
               </td>
            </tr>
            <tr>
                 <td align="center">
                   <asp:Button ID="btnLoad" runat="server" Text="Load Doc" Width="70px" OnClick="btnLoad_Click" />
                        
                   <asp:Button ID="btnSave" runat="server" Text="Save" Width="70px" OnClick="btnSave_Click" />
                 </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>



Note-   Set ValidateRequest="false"


Here I have taken one TextArea control by named – docArea. This will be used for showing and editing Word document. For this I have bounded nicEditor editor with TextArea. Using these lines of code-

    <script type="text/javascript">
        bkLib.onDomLoaded(function () {
            new nicEditor({ fullPanel: true, iconsPath: 'NicScript/nicEditorIcons.gif' }).panelInstance('docArea');
        });
    </script>


Pictorial representation will be like this-

Edit word document using ASP.Net


Now write following code in code behind-

protected void btnLoad_Click(object sender, EventArgs e)
        {
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            
             //Loading word document to HTML editor
            LoadDoc(strFileName);
        }

Here, I am reading Word document from docs directory (which is present in my solution structure) and passing to LoadDoc () function.

//Function to convert word document to HTML document after that loading into HTML editor
        private void LoadDoc(string strFileName)
        {
            //Loading  doc file using Document class of Aspose DLL
            Document doc = new Document(strFileName);

             //SaveOptions for image which is present in Word document
            HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
            string strImagePath = Server.MapPath("docs\\");

             //Location to save images which is included in word document
            options.ImagesFolder = strImagePath;
            options.ImagesFolderAlias = "docs\\";

           //Setting SaveFormat to save as HTML document
            options.SaveFormat = SaveFormat.Html;

           //Saving  file as HTML document
            doc.Save(strFileName + ".html", options);

             //Reading converted HTML file in Editor
            StreamReader sr = new StreamReader(strFileName + ".html");
            string strValue = sr.ReadToEnd();
            docArea.Value = strValue;
             sr.Close();
            sr.Dispose();
        }



In above function I have used Document class of Aspose dll to load Word document.
            Document doc = new Document(strFileName);

After loading document, we need to set the path for saving images which is included in Word document, for this I have used HtmlSaveOptions class.
       
            HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
            string strImagePath = Server.MapPath("docs\\");

//Location to save images which is included in word document
            options.ImagesFolder = strImagePath;
            options.ImagesFolderAlias = "docs\\";


Finally to save Word document as HTML document we need to set SaveFormat

            options.SaveFormat = SaveFormat.Html;
            doc.Save(strFileName + ".html", options);


Once these lines of code will be executed Word document will be converted to HTML document. Now we can load this HTML document to HTML editor.

             //Reading converted HTML file in Editor
            StreamReader sr = new StreamReader(strFileName + ".html");
            string strValue = sr.ReadToEnd();
            docArea.Value = strValue;
             sr.Close();
            sr.Dispose();


Output will be like this, when we will click on Load() button-

Edit word document using ASP.Net


Now to save edited document use the following code-

    protected void btnSave_Click(object sender, EventArgs e)
         {
             //Getting Text of HTML editor and writing into memorystream class object
            MemoryStream storeStream = new MemoryStream();
            StreamWriter sw = new StreamWriter(storeStream);
             sw.Write(docArea.Value);
             sw.Flush();

             //Again saving edited document with same name
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            Document doc = new Document(storeStream);
             doc.Save(strFileName, SaveFormat.Doc);
            storeStream.Close();
            storeStream.Dispose();
            sw.Close();
            sw.Dispose();
        }



In above code, first I am getting all the text of TextArea and writing to MemoryStream class object.

//Getting Text of HTML editor and writing into memorystream class object    
           MemoryStream storeStream = new MemoryStream();
            StreamWriter sw = new StreamWriter(storeStream);
            sw.Write(docArea.Value);
            sw.Flush();


After storing data into MemoryStream class object, I am using Document class of Aspose dll to write that data into same word file.

             //Again saving edited document with same name
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            Document doc = new Document(storeStream);
             doc.Save(strFileName, SaveFormat.Doc);
            storeStream.Close();
            storeStream.Dispose();
            sw.Close();
            sw.Dispose();


Now you are done.  We can test edited word document by going to same location where we have stored Word document.

Limitations-

1. One Extra HTML document will be created

2. You need to explicitly delete that HTML document after editing.

3. Time taking process because first you need to convert word doc to HTML doc and after editing again you have to create word doc.

4. Formatting can be lost, it depends on HTML editor.


Thanks