Skip to main content

Posts

Showing posts from March, 2014

How to Implement Server Side Validation in Asp.Net MVC

Server side validation can be performed by submitting the model and then check the values in related action of the controller. Asp.Net MVC framework populates a ModelState object with any validation failure and passes that object to controller. If any error found just add the error in the state of model by using ModelState object of type ModelStateDictionary.

According to our previous article about client side validation, programmer have to change some minor changes in the view as well as controller’s action. Just write the following code in our GetValues view:

@using (Html.BeginForm())
{
    <div>
        <div>Name: </div>
        <div>
            @Html.TextBox("username")
            @Html.ValidationMessage("nameError")
        </div>
        <input type="submit" value="Send" />
    </div>
}

Here I have added a validation message having the key "nameError" to show the validation message for username. …

Save Password using Encoding, decoding and Hashing Techniques in ASP.NET

Introduction Plain text change in unreadable format known as encoding. And reverse of it known as decoding. Change a plain text into cipher text using any key known as hashing. There are lots of techniques available in hashing.
Here we take a simple example of among. First we start from Encoding.


How to change plain text into cipher text (Unreadable format) first of all, take a string variable, after that take a byte array, which size is equal to string Length. Look like

String str = "Hello World";
Byte [] encode = new Byte[str.Length];

Get Bytes of string value using getBytes( ) method of UTF8 encoding. Now, your code look like

encode = Encoding.UTF8.GetBytes(str);
Now, change encoded byte array into Base64String.

encodepwd = Convert.ToBase64String(encode); // here encodepwd is the string variable.
Store encoded password is stored in encodepwd variable.

How to Change cipher Text into Plain Text First of all, encoded string convert into specified string format, which is equivale…

Difference between LINQ to XML and DOM Method

XML Document Object Model (DOM) is the current predominant XML programming API. In XML DOM, you build an XML tree in the bottom up direction. The typical way to create an XML tree using DOM is to use Xml Document. LINQ to XML also supports the Xml Document approach for constructing an XML tree, but also supports an alternative approach, called the functional construction. The functional construction uses the XElement and XAttribute constructors to build an XML tree.

In LINQ to XML, you can directly work with XML elements and attributes. You can create XML elements without using a document object. It also loads the T: System.Xml .Linq.XElement object directly from an XML file. It also serializes the T: System". Xml. Linq. XElement object to a file or a stream. When you compare this with XML DOM, the XML document is used as a logical container for the XML tree. In XML DOM, the nodes, which also include the elements and attributes, are created in the context of an XML document. The…

Remove first element from array , Example of List and Resize method

Introduction If you want to remove first element from an array. First of all, fill array with some values.Create a list collection and fill it with array list. Remove first element using RemoveAt(0) method , here 0 is the first index of array. After remove, must resize array using Resize( )  method. Again pass resized list into array.

Source Code<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Animal" Width="100px"
        onclick="Button1_Click" ForeColor="Red" />
    <div>

        <asp:Label ID="Label1" runat="server" Text="Label" BackColor="Yellow"
            BorderStyle="Solid" Font-Underline="True" ForeColor="Blue"></asp:Label>

    </div>
    </form>
CodeBehind Code#region remove_first_index
    protected void Button1_Click(object sender, EventArgs e)
    {
        st…

How to Implement Client-Side Validation in ASP.NET MVC

Implementing Client-Side Validation in an Asp.Net MVC application requires some app settings in the web.config file that must be true. These settings are used to enable two jquery i.e. jquery.validate.min.js and jquery.validate.unobtrusive.min.js in our project.

<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

These setting are by default enabled in an MVC project so programmer just remember to check these lines if validation are not working at all. In Visual studio there is an in-built validation attribute mostly used in all the required fields.

[Required]
(Field to be required…..)

This attribute is defined in System.ComponentModel.DataAnnotations namespace and it is used to not complete the page submission if user don’t enter any value in the respective field. The error message shown is the standard message ("Required") by defaul…

Example of array in c# , print array element at specified position

Introduction It is a simple example of array in c#, You can print element of array using for loop. Also print array element at specific position or index number. Simple, lower bound initialized from some value, where you want to print array element. Let's take an simple example
Source code    <form id="form1" runat="server">
    <div>

        <asp:Button ID="Button1" runat="server" Text="Button" Width="81px"
            onclick="Button1_Click" />

    </div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
Business Logic Codeprotected void Button1_Click(object sender, EventArgs e)
    {
        string[] fruits = new string[]
        {
            "papaya",
            "Apple",
            "Banana",
            "Grapes",
            "Orange",
            "Pine-apple&quo…

Append, modify or Edit string in ASP.NET C#

Introduction "A group of characters known as string", Like "Hello World!". If you want to change in it, use StringBuilder class, which is a mutable string class. Mutable means, if you want create an object with some character value, also want to change in it further , that is possible with same object. So here we take StringBuilder class for appending string.

<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button"
        Width="68px" BackColor="#FFFF66" />
    <div style="width: 88px">

        <asp:Label ID="Label1" runat="server" Text="Label" BackColor="#FFCC66"
            BorderColor="#CC0000"></asp:Label> 
    </div>
    </form>
Business Logic Codeprotected void Button1_Click(object sender, EventArgs e)

        {
            StringBu…

Remove last element of array in C#

Using the Resize method you can decrement size of an array. Resize method creates a new array with new specified size Also copy old array items into newly created. Let's take an simple example to remove last element. Take less than one size of original array size. Newly created array skip last element of original array size.

<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" Height="37px" onclick="Button1_Click"
        Text="Vegetable" Width="100px" />
    <div>

        <asp:Label ID="Label1" runat="server" Text="Label" Width="100px" ForeColor="Black" BackColor="Yellow"></asp:Label>

    </div>
    </form>
Business Logic codeprotected void Button1_Click(object sender, EventArgs e)
    {
        string[] Vegtables = new string[]
        {
            "1.Tomato",
            …

Print element of array at specific position in c#, LINQ subset array

Using the LINQ subset array you can print element of array at specific position through Skip( ) method. If you want to print array element at position number 3 then you should skip three starting index of array. Like
ArrayName .Skip(3).Take(2).ToArray( ) .
Source<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1" runat="server" Height="33px" onclick="Button1_Click"
            Text="Button" Width="96px" />  
    </div>
    <p style="width: 118px">
        <asp:Label ID="Label1" runat="server" Height="40px" Text="Label" Width="100px"></asp:Label>
    </p>
    </form>
Business Logic Code protected void Button1_Click(object sender, EventArgs e)
    {
        string[] Vegetables = new string[]
        {
            "Tomato",
            "Potato",
            "…

Insertion sort and let us consider an array of size 10 for Data Structure in 'C'

Insertion sort:                   In this technique of sorting, the fact of inserting the pivotal element  at its proper position from n (size of the array) number of elements is used. The pivotal element to be inserted is picked from the array itself. The selected pivotal element is inserted at the position from the left part of the array that is treated as sorted.                    Initially the first element of the array is treated as left part of the array and being one element that is treated as sorted part of the array. The first pivotal element that is selected for insertion is the second element of the array. the pivotal element is compared with the first element and if the first element is greater than the pivotal element, then it is moved to the second position. Now we remain with no elements compared to be compared in the left part, the position where the pivotal element is found as the first position. The pivotal element is inserted at the first position to over the pass.…

Change Header border style as dotted of Gridview in ASP.NET

Make border dotted of GridView header row using BorderStyle property using property window. This style enumeration is applies on compile time. First bind Gridview with SqlDataSource control , after that make some changes in style properties. This example cover dotted border style. Some steps are:

Step-1 : Open Visual Studio IDE
Step-2 : Add New Webform into your project
Step-3 : Add Gridview control on design window.
Step-4 : Bind Gridview with SqlDataSource control, make changes in border style



<!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> </head> <body>     <form id="form1" runat="server">     <asp:GridView ID="GridView1" runat="server" AllowPaging="True"          AutoGenerateColumns="False&q…

How to use LINQ to SQL in ASP.NET

INTRODUCTION LINQ to SQL is a component of .NET Framework, and is specifically designed for working with SQL server database. It provides a run-time infrastructure for managing relational data as objects. It allows you to write queries to retrieve and manipulate data from the SQL server. LINQ to SQL supports all the key functions that you would expect while developing SQL applications. You can retrieve the data from the database, insert, update, and also delete the information from the table. Your query expression is translated into parameterized SQL code, parameters are created, and the query is executed on the server. LINQ to SQL also supports transactions, views, and stored procedures. It also provides an easy way to integrate data validation and business logic rules into your data model.
LINQ to SQL is an object-relational mapping (ORM) framework that allows the direct 1-1 mapping of a Microsoft SQL Server database to .NET classes, and query of the resulting objects using LINQ. Wi…

C program to sort 10 elements of an array and a list of 11 names in ascending order using selection sort technique

C program to sort 10 elements of an array in ascending order using selection sort technique. #include<stdio.h>
#include<conio.h>
void se1_sort_ao(int arr[],int n)
{
  int i, j, min, mops;
  for(i=0;i<n-1;i++)
   {
    min = arr[i]; mpos = 1;
    for(j=i+1; j<n; j++)
    if(arr[j] < min)
      {
      min = arr[j]; mops = j;

      }
    arr[mpos] = arr[i];   arr[i] = min;
   }
}
main()
{
    int a[10], i;
    printf("Enter 10 element of the array:\n \n");
    for(i=0;i<10;i++)
      scanf("%d",&a[i]);
    printf("The array before sorting:\n \n");
    for(i=0;i<10;i++)
      printf("%d",a[i]);
    sel_sort_ao(a,10);
    printf("\n \n The array after sorting:\n \n");
    for(i=0;i<10;i++)
      printf("%d",a[i]);
}

C program to sort a list of 11 names in ascending order using selection sort technique.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void se1sortstrao(char …

'C' Function to implement 'selection sort' in ascending and descending order

‘C’ function to implement ‘selection sort’ in ascending order.
void se1_sort_ao(int arr[],int n)
{
    int i, j, min, mpos;
    for(i=0;i<n-1;i++)
    {
    min = arr[i];    mpos = i;
    for(j=i+1;j<n;j++)    /*selection of min element */
     if(arr[j] < min)
     {
      min = arr[j]; mpos =j;
     }
    arr[mpos] = arr[i];         /*replacing min element */
    arr[i] = min;
    }    
}

‘C’ function to implement ‘selection sort’ in descending order. void se1_sort_ao(int arr[],int n)
{
    int i, j, max, mpos;
    for(i=0;i<n-1;i++)
    {
    max = arr[i];    mpos = i;
    for(j=i+1;j<n;j++)    /*selection of max element */
     if(arr[j] > max)
     {
      max = arr[j]; mpos =j;
     }
    arr[mpos] = arr[i];         /*replacing max element */
    arr[i] = max;
    }    
}

Algorithm to implement selection sort ascending and descending order

Algorithm to implement selection sort (ascending order):
SELECTIONSORTAO(arr,n)
Repeat For I =1 to n-1                [n-1 passes]
MIN <-- arr[I]
POS <-- I
Repeat for J=I+1 to n  [to select minimum element]
  If arr[J]< MIN Then:
     MIN <-- arr[J]
     POS <-- J
  [ End of if ]
 [ End of for J ]
 arr[pos] <-- arr[I]
 arr[I] <-- MIN
[End of For I ]
Exit.  
Algorithm to implement selection sort (descending order):  SELECTIONSORTDO(arr,n)
[‘arr’ is an array of n elements]
Repeat For I =1 to n-1            
  MAX <-- arr[I]; POS <-- I
 Repeat for J=I+1 to n
   If arr[J]>MAX Then:
       MAX <-- arr[J];  POS <-- J
    [ End of if ]
   [ End of for J ]
   arr[pos] <-- arr[I];  arr[I] <-- MAX
[End of For I ]
Exit.  


How to use LINQ projection Operators in ASP.NET

Introduction Projection operators are used to transform an object into a new object of a different type. By using the Projection operators, you can construct a new object of a different type that is built from each object. The Select and SelectMany clauses are the Projection operators used in LINQ. The Select operator performs a projection over a sequence and projects the value that is based on a transform function. The Select operator in LINQ performs function just as the Select statement in SQL. The Select operator specifies which elements are to be retrieved. For example, you can use the Select clause to project the first letter from each string in a list of strings. The syntax of using the Select clause is:
C# public static lEnumerable<S> Select<T, S>( this IEnumerable<T> source, Function<T, S> selector);
The second type of Projection operator used in LINQ is the SelectMany operator. The SelectMany operator projects a sequence of values that are based on a tr…

How to make custom password change control in asp.net

Introduction This control is designed for authenticated user, he/she can change own profile password. Basically, it have three fields, such as old password field, New password field, and retype password field. Looking like

If your old password doesn't match with stored data then new password will not update. Id password match with stored data then your new password will be updated.
Algorithm behind the programStep-1 : First of all match your old password with table data using user_id, which is unique. For that, we will create a SELECT query.
Step-2 : Result of Select Query match with Text Box, which is defined for old password.
Step-3 : If Your inputted password is matched with fetched data, which is fetched from select query.
Step-4 : Design update query and will change your old password with new one.
Programming codeStep-1 : Create connection from SqlEngine using SqlConnection class, which is inside in System. Data. SqlClient namespace.

SqlConnection con;
 con = new SqlConnection();
   …