MVC Dropdown List using Enumerator(enum)

In this post I will explain how to create a drop down list with Enumerator using MVC Rozar view. Many ways we have to do that but I will explain one of the easiest ways. If you follow this way we easily set select index of dropdown in Edit page also.
The view is
@{
var EnumInterval = from EnumDropDown().Interval n in Enum.GetValues(typeof(EnumDropDown.Interval))
select new SelectListItem
{
Value = n.ToString(),
Text = EnumDropDown.GetEnumDescription(n),
};
}
The Helper class is look like below

using System.Reflection;
using System.ComponentModel;
namespace EnumHtmlHelper.Helper
{
public static class EnumDropDown
{
public static string GetEnumDescription(TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.
GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Description;
else
return value.ToString();
}
public enum Interval
{
[Description("Daily")]
D = 1,
[Description("Quick")]
Q = 2,
[Description("Weekly")]
W = 3
}
}
}
The View source look like bellow

Method Overriding in C#.NET


        Creating a method in derived class with same signature as a method in base class is called as method overriding.
        Same signature means methods must have same name, same number of arguments and same type of arguments.
        Method overriding is possible only in derived classes, but not within the same class.
 
When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.
         To allow the derived class to override a method of the base class, C# provides two options,
virtual methods and abstract methods.

Page.PreviousPage Property(How to get value of previous page control value

            
            When you use the Server.Transfer method or use cross-page posting to transfer processing from one ASP.NET page to another Page, the originating page contains request information that might be required for the destination page. You can use the Previous Page property to access that information.


The following example is in two parts. The first is an ASP.NET page that uses the Transfer method, exposed in the page model as Server.Transfer("path"). The second part is the target page, which uses the PreviousPage property to get the title of the first page.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        // If second is an even number, the server is available
        // Replace this line with a valid check for the server.
        bool IsServerAvailable = (DateTime.Now.Second % 2 == 0);

        if (!IsServerAvailable)
            Server.Transfer("Notify.aspx", true);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Switch Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>Database Server is Available</h2>

    <p>This page appears if the database server
        is available.</p>

    <p>Enter a pretend Server Name:
        <asp:TextBox ID="serverNameText"
        runat="server">MyDatabaseServer</asp:TextBox>
    </p>

    <p><asp:Button ID="SubmitButton" runat="server"
        Text="Is server available?" /></p>
    </div>
    </form>
</body>
</html>


Notify.aspx page 

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        // Find the server name on the previous page
        TextBox txt =
                (TextBox)Page.PreviousPage.FindControl("serverNameText");
        if (txt != null)
            prevServerName.Text = Server.HtmlEncode(txt.Text);
        else
            prevServerName.Text = "[Name Not available]";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Page A</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>Database Server is Not Available</h2>

    <p>This page appears if the named database server is not
    available, but the URL displays as the main target page.</p>

    <p>Server Name (From Page.PreviousPage):
        <asp:Label ID="prevServerName" runat="server" /></p>

    <p>Refresh the page to see if the server is now available.</p>
    </div>
    </form>
</body>
</html>


A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies

In this post I will explain Circular Reference Serialization Error in MVC Entity frame work. In my latest project I need to get data from database for purpose of Autocomplete.So I need data as JSON format.
          When I request the “http://localhost:xxxx/Student/GetStudentJson”
Circular reference

How to get MVC Razor view Controls ID from Java script

In this post I will explain How to get MVC Razor view controller id from JavaScript .In real time some time we need to assign  value to controller or we need to read (get) value from controller.

Example The view have Following Controller
@model MvcApplication1.Models.User
@{
    ViewBag.Title = "create";
}
<h2>
    create</h2>
@using (Html.BeginForm())
{

    @Html.ValidationSummary(true)
    <fieldset>
        <legend>User</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>

MVC Action Names & NonAction method


            In MVC URLs not being case sensitive. So that for example if you have the request “Home/About” this goes to HomeController and About action, as well as hOmE/AbOUT is going to the same controller and same action method. 
            SUPPOSE  if we have 2 about action methods in the same controller with different cases such as:


public class HomeController:Controller{
    public ViewResult About()    {
        return View();
   }
    public ViewResult aBOut()
    {
        return View();
    }
}
when Icall action method About using following url http://your applicationname/Index/ABOUT I got following server page error

The framework can’t determine which ‘about’ function to call, and throws the exception telling that the call is ambiguous. Of course one way to fix this problem is to change the action name. If for some reason you don’t want to change the action name, and one of these function is not an action, then you can decorate this non action method with NonAction attribute. Example:

[NonAction]
public ActionResult aBOut()
{
   return View();
}


JSON serialization error [maxJsonLength property.]

In my previous project I need to retrieve ticket  from Web service.When I request the web service it return a ticket as JSON format.Some time I need to retrieve more than 10 lacks ticket per requet.In that time I got the following error

Exception information:
Exception type: InvalidOperationException
Exception message: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Solution is 
            We need to set Maximum allowed length of json response in Web.config file 
The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k).

HOW TO CHECK YOUR LAST SQL DATABASE BACKUP TIME


      It is good to check when was your last backup happened, I have wrote small query which it pull the information from msdb backupset table, it lists all the database names with last backup date and time.
It is very easy to track when was your last backup was happened. You can use the following query
.

Create a Foreign Key relationship using Code First Entity Framework In asp.net MVC4

In this post I will explain How to create Foreign Key relationship in  Entity Framework(EF).

When you create a model of relation database some time we got following error
Unable to retrieve association information for association 'Models.Product_Parent'. Only models that include foreign key information are supported. See Entity Framework documentation for details on creating models that include foreign key information.

         I will explain how to create Model class for following  relation data base

Login failed for user "sa" error 18456


In SQL Server's most common issue in securities is login failed for user, Error 18456.
To resolve 18456 error, you have to change the Server Authentication mode "SQL Server and Windows Authentication mode".
In order to resolve the above issue through selecting "SQL Server and Windows Authentication mode", please refer to the following steps:
Here is the error #18456 getting while connecting to the server through "SA" login and password.

MVC Action link with Html text

In this post I will explain how to write MVC Action link with Html text.

MVC Razor View

<a href='@Url.Action("MyAction", "MyController")'>
     <span>My Asp.Net</span>
</a>


MVC Html View


<a href='<%: Url.Action("MyAction", "MyController") %>'>
     <span>My Asp.Net</span>
</a>



String Format for DateTime [C#]

This example shows how to format Date Time using String.Format method. All formatting can be done also using DateTime.ToString method.
Custom Date Time Formatting
There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed),t (P.M or A.M) and z (time zone).
Following examples demonstrate how the format specifiers are rewritten to the output.
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

         

Reverse of a string without using the Reverse function in C# and VB

This is a simple code snippet for reversing a string without using the Reverse function. For example, we have a string "He is playing in a ground." without using a function, we can reverse it using the code snippet below. Code is given in both C# and VBalso. This will be helpful to beginners. If you have any queries, please feel free to ask me.
example

Tamil keyboard

The Html code is


<div dir="ltr" style="text-align: left;" trbidi="on">
<center>

<input id="Phrase" size="80" style="font-size: 16;" type="text" value="" />

<script language="JavaScript" type="text/javascript">

 function AppendCharacter(ChrToAppend)
 {
   document.getElementById("Phrase").value += ChrToAppend;
 }



 </script>

<table><tbody>
<tr>             <td>
<input name="02947" onclick="AppendCharacter('ஃ');" style="font-size: 18;" type="button" value=" ஃ " />
</td>             <td>
<input name="02949" onclick="AppendCharacter('அ');" style="font-size: 18;" type="button" value=" அ " />
</td>             <td>
<input name="02950" onclick="AppendCharacter('ஆ');" style="font-size: 18;" type="button" value=" ஆ " />
</td>             <td>
<input name="02951" onclick="AppendCharacter('இ');" style="font-size: 18;" type="button" value=" இ " />
</td>             <td>
<input name="02952" onclick="AppendCharacter('ஈ');" style="font-size: 18;" type="button" value=" ஈ " />
</td>             <td>
<input name="02953" onclick="AppendCharacter('உ');" style="font-size: 18;" type="button" value=" உ " />
</td>             <td>
<input name="02954" onclick="AppendCharacter('ஊ');" style="font-size: 18;" type="button" value=" ஊ " />
</td>             <td>
<input name="02958" onclick="AppendCharacter('எ');" style="font-size: 18;" type="button" value=" எ " />
</td>             <td>
<input name="02959" onclick="AppendCharacter('ஏ');" style="font-size: 18;" type="button" value=" ஏ " />
</td>             <td>
<input name="02960" onclick="AppendCharacter('ஐ');" style="font-size: 18;" type="button" value=" ஐ " />
</td>             <td>
<input name="02962" onclick="AppendCharacter('ஒ');" style="font-size: 18;" type="button" value=" ஒ " />
</td>         </tr>
</tbody></table>
<table><tbody>
<tr>             <td>
<input name="02963" onclick="AppendCharacter('ஓ');" style="font-size: 18;" type="button" value=" ஓ " />
</td>             <td>
<input name="02964" onclick="AppendCharacter('ஔ');" style="font-size: 18;" type="button" value=" ஔ " />
</td>             <td>
<input name="02965" onclick="AppendCharacter('க');" style="font-size: 18;" type="button" value=" க " />
</td>             <td>
<input name="02969" onclick="AppendCharacter('ங');" style="font-size: 18;" type="button" value=" ங " />
</td>             <td>
<input name="02970" onclick="AppendCharacter('ச');" style="font-size: 18;" type="button" value=" ச " />
</td>             <td>
<input name="02972" onclick="AppendCharacter('ஜ');" style="font-size: 18;" type="button" value=" ஜ " />
</td>             <td>
<input name="02974" onclick="AppendCharacter('ஞ');" style="font-size: 18;" type="button" value=" ஞ " />
</td>             <td>
<input name="02975" onclick="AppendCharacter('ட');" style="font-size: 18;" type="button" value=" ட " />
</td>             <td>
<input name="02979" onclick="AppendCharacter('ண');" style="font-size: 18;" type="button" value=" ண " />
</td>             <td>
<input name="02980" onclick="AppendCharacter('த');" style="font-size: 18;" type="button" value=" த " />
</td>             <td>
<input name="02984" onclick="AppendCharacter('ந');" style="font-size: 18;" type="button" value=" ந " />
</td>             <td>
<input name="02985" onclick="AppendCharacter('ன');" style="font-size: 18;" type="button" value=" ன " />
</td>         </tr>
</tbody></table>
<table><tbody>
<tr>             <td>
<input name="02986" onclick="AppendCharacter('ப');" style="font-size: 18;" type="button" value=" ப " />
</td>             <td>
<input name="02990" onclick="AppendCharacter('ம');" style="font-size: 18;" type="button" value=" ம " />
</td>             <td>
<input name="02991" onclick="AppendCharacter('ய');" style="font-size: 18;" type="button" value=" ய " />
</td>             <td>
<input name="02992" onclick="AppendCharacter('ர');" style="font-size: 18;" type="button" value=" ர " />
</td>             <td>
<input name="02993" onclick="AppendCharacter('ற');" style="font-size: 18;" type="button" value=" ற " />
</td>             <td>
<input name="02994" onclick="AppendCharacter('ல');" style="font-size: 18;" type="button" value=" ல " />
</td>             <td>
<input name="02995" onclick="AppendCharacter('ள');" style="font-size: 18;" type="button" value=" ள " />
</td>             <td>
<input name="02996" onclick="AppendCharacter('ழ');" style="font-size: 18;" type="button" value=" ழ " />
</td>             <td>
<input name="02997" onclick="AppendCharacter('வ');" style="font-size: 18;" type="button" value=" வ " />
</td>             <td>
<input name="02999" onclick="AppendCharacter('ஷ');" style="font-size: 18;" type="button" value=" ஷ " />
</td>             <td>
<input name="03000" onclick="AppendCharacter('ஸ');" style="font-size: 18;" type="button" value=" ஸ " />
</td>             <td>
<input name="03001" onclick="AppendCharacter('ஹ');" style="font-size: 18;" type="button" value=" ஹ " />
</td>         </tr>
</tbody></table>
<table><tbody>
<tr>             <td>
<input name="03006" onclick="AppendCharacter('ா');" style="font-size: 18;" type="button" value=" ா " />
</td>             <td>
<input name="03007" onclick="AppendCharacter('ி');" style="font-size: 18;" type="button" value=" ி " />
</td>             <td>
<input name="03008" onclick="AppendCharacter('ீ');" style="font-size: 18;" type="button" value=" ீ " />
</td>             <td>
<input name="03009" onclick="AppendCharacter('ு');" style="font-size: 18;" type="button" value=" ு " />
</td>             <td>
<input name="03010" onclick="AppendCharacter('ூ');" style="font-size: 18;" type="button" value=" ூ " />
</td>             <td>
<input name="03014" onclick="AppendCharacter('ெ');" style="font-size: 18;" type="button" value=" ெ " />
</td>             <td>
<input name="03015" onclick="AppendCharacter('ே');" style="font-size: 18;" type="button" value=" ே " />
</td>             <td>
<input name="03016" onclick="AppendCharacter('ை');" style="font-size: 18;" type="button" value=" ை " />
</td>             <td>
<input name="03018" onclick="AppendCharacter('ொ');" style="font-size: 18;" type="button" value=" ொ " />
</td>             <td>
<input name="03019" onclick="AppendCharacter('ோ');" style="font-size: 18;" type="button" value=" ோ " />
</td>             <td>
<input name="03020" onclick="AppendCharacter('ௌ');" style="font-size: 18;" type="button" value=" ௌ " />
</td>             <td>
<input name="03021" onclick="AppendCharacter('்');" style="font-size: 18;" type="button" value=" ் " />
</td>         </tr>
</tbody></table>
<table><tbody>
<tr>             <td>
<input name="space" onclick="AppendCharacter(' ');" type="button" value="                     " />
</td>         </tr>
</tbody></table>
</center>

<hr />
</div>

The Out put is

The Html code is

The Out put is

Arrays resized dynamically



In C#, arrays cannot be resized dynamically. One approach is to use System.Collections.ArrayList instead of a native array. Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array. The generic function resizeArray (below) can be used to do that.
Example is bellow

Localization In InfoPath


Introduction to Localizing InfoPath Form Templates

    In common design practice is to embed text directly in the form.However, when you need localized forms, a different approach is required. The typical design pattern for localization is to move all strings into locale-specific resource files and load the appropriate strings at run time

Designing Your Form
 The following step will explain step by step creating simple Infopath ffrom
  1. Go to start -> All Program ->Microsoft Office ->Microsoft Info Path Designer
  2. File -> New -> Crate New Blank Form.
  3. Desigin a form like this

 

Figure 1

Localizing the Form

       After your form template works as you expect, you can start to implement localization for your form. This consists of five main stages
  1. Creating an .resx resource file that contains the display strings for the language of your locale, and then creating additional .resx resource files for each locale your form supports.
  2. Adding the .resx resource files to the form template as resources, and then defining a secondary data source to enable code and formulas in InfoPath to access the data contained in the resource files.
  3. Adding code to detect or specify the current locale, and then load the appropriate localization resource file.
  4. Converting controls on the form template and adding code or formulas to read display strings from the XML resource files you created.
  5. Deploying and testing the localized form template.

Creating the Localization Resource Files for the Form

        After your form template operates as expected, you need to create the localization resource files that contain the display strings for your form, and then define a secondary data connection that will be used to access the data in the files.

Creating a Default Localization Resource File

  1. Go to Project Explorer and right click and select Add New item

  2. Select Resource file under Template
  3. Rename "Resource1.resx" to "en-US."
  4. modifying the like this and save                                  Figure2
  5. Repeating step 2 to 4 and save the file like sp_Sp,resx                            Figure 3

Adding the Localization Resource Files to Infopath and Defining Their Data Connection

After you complete all localization resource files, you need to add them to the form template as resource files.
To add the localization resource files to the form template.
  1. Open the form template in design mode.
  2. Click On Data then following the Image bellow
    Figure4
  3. Click add button and select "en-US..resx" where you save 
  4. Similarly you need to add "sp_Sp,resx"                                                    click ok                                                               Figure 5

Adding a Secondary Data Source to the Form

This design pattern uses a data connection defined as a secondary data source to connect to the localization resource files and read data from the files.
To add a secondary data source to retrieve data from localization resource files
  1. On the Tools menu, click Data Connections, and then click Add.
  2. Click Create a new connection to, click Receive data, and then click Next.
  3. Click XML document, and then click Next.
  4. Click Resource Files, select your default localization resource file, click OK, and then click Next.
  5. Name the data connection Resources, ensure that the Automatically retrieve data when form is opened check box is selected, and then click Finish, as shown in Figure 6.
Figure 6. Adding a secondary data source

Adding a secondary data source