Tuesday, 18 October 2011

Data first approach in MVC3


Data first approach in MVC3
Project First Appearence - Database DB First Approach ASP.NET 4 MVC3
BlogContent DataTable Data
Taxonomy Data
ContentType Table Data
Existing Database table relationships schema Database DB First approach



Creating ADO.NET ENTITY Data Model From a Existing Database Database First Approch


Generate Entity Data Model From Existing Database DB Database DB First approach 

Creating ConnectionString from Exiting Database - Database First approach


Entity Data Model Edmx file view


 right click on the white surface in the entity data model of Blog Database.

DBContext Generate From Entity Data Model

Creating Repository Model and Database Table Class from the Entity Data Model, Click on 'ok' twice

After Creating RepositoryModel and DBContext from Wizard


Controller Wizard to Create V-View, C- Controller
V-View and C- Controller has been created with Read,WriteDeleteDetails View ability

Created a Link for the Blog Content Controller

Preview of the Project

Can't find ADO.NetDbContext Generatior

        I was tried my first exercise in MVC 3 to connect with database using entity framework by following the video in the url http://msdn.microsoft.com/en-us/data/gg702905.
   
        But I cant find the  ADO.Net DbContext Generator in the add new window.  I was find out the solution to add the http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=18504 to the visual studio now it is working fine...

        Happy Coding....

Wednesday, 5 October 2011

Template function and Template class in C++

        Template function is a generic type function which is supported to all data types.  It is used to avoid the repetition.

For Example:
         We want to write function to find the maximum number from given two numbers.  The given number may be integer,long or any type.  By using the classic method we must write separate function for integer and long.

int findMax(int a,int b)
{
   int result=(a>b)?a:b;
   return(result);
}

log findMax(long a,long b)
{
   long result=(a>b)}a:b;
   return result;
  }

int main()
{
    int a=10,b=20;
    long x=8.7,y=9.08;
    cout<<findMax(a,b);
    cout<<findMax(x,y);
    return 1;
 }

      We have two functions in the above code both are same except the data type to avoid this repetition we will using the Template function.

template <class myType>
myTytpe findMax(myType a,myType b)
{
   myType result=(a>b)?a:b;
   return result;
}

int main()
{
    int a=10,b=20;
    long x=8.7,y=9.08;
    cout<<findMax(a,b);
    cout<<findMax(x,y);
    return 1;
 }

Template Class 
       Template class is an generalized class. Which is the extension of the template function we can use the generic data type in the whole class i.e more than one function and declare the properties with the template data type.

Example


      I want to create a stack for the integer and string in the classic approach a separate class for integer and separate class for string.  Except the data type remaining all are same.

Like following program


       class IntegerStack 
       {
        public:
         IntegerStack() { top = -1; }
        void push(int i)
          { stack[++top] = i; }
        int pop()
          { return stack[top--]; }
        private:
          int top;
          int stack[100];
       };

       class StringStack {
public:
StringStack() { top = -1; }
void push(string i)
           { stack[++top] = i; }
          string pop()
          { return stack[top--]; }
       private:
          int top;
          string stack[100];
       };

     we will template class instead of this classic approach

template <class T>
class Stack {
     public:
       Stack();
       void push(T i);
       T pop();
     private:
      int top;
      T st[100];
     };

    template <class T>
     Stack<T>::Stack()
     {
      top = -1;
     }

   template <class T>
   void Stack<T>::push(T i)
    {
     st[++top] = i;
    }

   template <class T>
   T Stack<T>::pop()
    {
     return st[top--];
    }

   int main()
{
  Stack<int> integer;
  Stack<string> string;
  integer.push(10);
  string.push("sugunthan");
}




Tuesday, 4 October 2011

Extension Method in C#

Extension method is an very useful method to the developer.  It will extend the methods of an existing class.  That is we are regularly using the string methods like
 1.ToLower
 2.Toupper

   string s="sugunthan";
   string upper=s.ToUpper();

Like this way I want to reverse my string by using an method

Using older method


class Program
    {
        static void Main(string[] args)
        {


            string s = "sugunthan";

            stringmethod sm = new stringmethod();

            string reverse = sm.Reverse(s);
            Console.WriteLine(reverse);

        }
    }

    class stringmethod
    {
        public string Reverse(string source)
        {
            string n = string.Empty;
            int size = source.Length;
            size = size - 1;
            for (int i = size; i >= 0; i--)
                n = n + source[i];
            return n;

        }
    }



     In this classic approach we must create an object for the class and call the function by using that class.
Instead this old way we will using the extension method
The advantages are
          1.  Use as like other build in string methods i.e with intelligence
          2.  Able use with the constant like "sugunthan".Reverse();
          3.  Dont bother about the parameter type.
Example

using MyExtensionMethods;


namespace extension_methods
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "sugunthan";
            string reverse = s.Reverse();
            Console.WriteLine(reverse);
            Console.WriteLine("extension method".Reverse());
        }
    }
}



namespace MyExtensionMethods
{
    public static class MyExtension
    {
        public static string Reverse(this string source)
        {
            string n=string.Empty;
            int size = source.Length;
            size = size - 1;
            for (int i = size; i >= 0; i--)
                n = n + source[i];
            return n;

        }
    }
}




Monday, 3 October 2011

ienumerable in c#

           We all are very familiar with foreach method is c# that returns a result per iteration.  Ienumeration is used to create user defined function which is used with foreach loop.

Example:
          I want to get the numbers between 2 values using a function get_numbers(int min,int max).

                  foreach(int n in get_nubers(10,30))
                 {
                    Console.WriteLine(n);
                  }

                   IEnumerable<int> get_numbers(int min, int max)
                  {
                     for (; min <= max; min++)
                     {
                        yield return min;
                      }
                   }

         In the above example we have a new keyword yield  it is a special type of return because the foreach method calls the function at each iteration i.e

          n <--- get_numbers(10,30)  then the control passed to the method and get the number 10  then returned to the called function.  Again the function called for the next iteration.

         Simply set a break point in the foreach statement and check the flow.

         

                   

       

Wednesday, 28 September 2011

Difference between string and String

Answer simply nothing.....   String=System.String  dot net provide another name string for the convenience of the programmers who are basically from c and c++.   short= System.Int16 , int=System.Int32.

Diffference between ViewBag and ViewData in MVC

                 I am proud to write the first article in MVC.   I am brand new to MVC at this date.  I saw the ways to convey the message between the control to the view,  the easiest ways are viewbag and viewdata both are nearly do the same in the difference way.
ex:
    public ActionResult Index()
        {
              ViewBag.Greeting="Hello World";
              ViewData["Greeting"]="Hello World";
          }

in the view

<body>
  <h1><%=ViewBag.Greeting%></h1>
   <h2.<%=ViewData["Greeting"]%></h1>
</body>

1.  The simple difference is we use a string in the ViewData for indexing purpose that is called magic string but in the ViewBag method view simply use the property similar to the class.

2.  For the both cases the intelligence is not provided.  So there may be chances to make a manual mistake to indicating the variables.
            * If you made mistake in the ViewData  ex ViewData["Greting"] instead of Greeting at the time the error is ignored and HTML is executed without any error.
             * But it is strictly notified in the ViewBag method.

3. In the ViewBag the data conversion is handled by itself no need to convert the data from object to the data type. But it must be defined in the ViewData.
              ex:
                  public ActionResult Index()
             {
                    List<string> namelist = new List<string>{"sugunthan","shamnugam","sundaram"};
                    ViewBag.list = namelist;
                    ViewData["list"] = namelist;
                    return View();
              }

In the View
               <ul>
                 <%foreach (var name in (List<int>) ViewData["list"]){ %>
                   <li><%=name %></li>
                   <%} %>
                   </ul>
                   <ul>
                   <%foreach (var name in ViewBag.list)
                    { %>
                    <li> <%=name %></li>
                    <% }%>
                   </ul>

If you made any mistake in the data conversion it make an error in the runtime.






Saturday, 17 September 2011

Cookies

     Cookies are created when a user's browser loads a particular website. The website sends information to the browser which then creates a text file. Every time the user goes back to the same website, the browser retrieves and sends this file to the website's server. Computer Cookies are created not just by the website the user is browsing but also by other websites that run ads, widgets, or other elements on the page being loaded. These cookies regulate how the ads appear or how the widgets and other elements function on the page.

Session Cookies:

     
Webpages have no memories. A user going from page to page will be treated by the website as a completely new visitor. Session cookies enable the website you are visiting to keep track of your movement from page to page so you don't get asked for the same information you've already given to the site. Cookies allow you to proceed through many pages of a site quickly and easily without having to authenticate or reprocess each new area you visit.
Session cookies allow users to be recognized within a website so any page changes or item or data selection you do is remembered from page to page. The most common example of this functionality is the shopping cart feature of any e-commerce site. When you visit one page of a catalog and select some items, the session cookie remembers your selection so your shopping cart will have the items you selected when you are ready to check out. Without session cookies, if you click CHECKOUT, the new page does not recognize your past activities on prior pages and your shopping cart will always be empty.



Tuesday, 13 September 2011

Trim Functions in JavaScript

Three type of trims are available
1. Trim (Left and Right)
2. Right Trim
3. Left Trim

The function for these trims are
Trim
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,"");
}
Left Trim
String.prototype.ltrim = function()
 {
return this.replace(/^\s+/,"");
}

Right Trim
String.prototype.rtrim = function()
 {
return this.replace(/\s+$/,"");
}


Simply places these function into your page or external javascript file but it must be availble where you will use these functions.

We see how to use these functions

var sampleString="  this is my blog   ";
alert("$"+sampleString.trim()+"$");
alert("$"+sampleString.ltrim()+"$");
alert("$"+sampleString.rtrim()+"$");

                                             

Friday, 2 September 2011

Concrete class and Abstract class

Concrete class is nothing but normal class, we can use as a base class or may not.Not compulsory, it can't contain abstract methods.we can create object and work with this class.

class Sample
{
public void MyMethod()
{..............}
}


Abstract class:- Abstract class is class which declared with a keyword Abstract,
Must be used as a base class.
Only intension to declare a abstract class is to use as a base class,that is we can't create object of this class like concrete class.
It can contain abstract methods as well as concrete(normal) methods.

public abstract class MyClass
{
public void MyMethod()
{..............}

public abstract TestMethod()
{
.........
}
}

Tuesday, 30 August 2011

2 Types of Primary Key Creation

1.CREATE TABLE one(sno int,name varchar(40) CONSTRAINT s1 PRIMARY KEY(sno))

2. CREATE TABLE two(sno int PRIMARY KEY,name varchar(40))

Both gives the same result.......  Then what is the difference....

Expand the Object Explorer and Reach the key folder of the Table
For NO 1 the primary key with the name s1 but NO 2 have a key with default name
It did the same thing when you will check with sp_help <table name>

So if you use 2 type it is some what informative  to you.

It also very useful when you will try to alter the primary key or constraints
like
ALTER TABLE dbo.one DROP CONSTRAINT s1

You will get confusion when you failed to give the name to the constraints like PRIMARY KEY or FOREIGN KEY.......



Wednesday, 27 July 2011

Condition to checking the time range

         Actually half a day I am seeking a right solution to check the time range for the hall management project.  For example the hall is booked for a meeting from 9.00 am to 11.00 am on a particular day.  If any other user try to book the hall at a time which include this time range.
        
         Here these timing are possible to crash  1. exact 9am to 11am
                                                                          2. 8.30am to 9.30 am
                                                                          3. 9.30 am to 10 am
                                                                          4. 8am to 12 pm

         We must check all of these conditions before book the hall 

         Here the solved condition in as C# program  consider extStart as existing start time extEnd as existing End time (i.e) the previous entries


sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace conditioncheck
{
    class Program
    {
        static void Main(string[] args)
        {

            float extStart = 9, extEnd = 11;
            Console.WriteLine("The existing strat time is {0} \n End time is {1} \n", extStart, extEnd);
            Console.WriteLine("Enter the start time and end time ");
            float givenStart = float.Parse(Console.ReadLine());
            float givenEnd = float.Parse(Console.ReadLine());

            Console.WriteLine("The given strat time is {0} \n End time is {1} ", givenStart, givenEnd);
           

            if (((givenStart>=extStart)&&(givenStart<extEnd))||((givenStart<=extStart)&&(givenEnd>extStart)))
                {
                Console.WriteLine("Meeting Crashes ");
                }
                else
                {
                    Console.WriteLine("Meeting not crashes ");
                }
            Console.Read();


        }
    }
    }

Tuesday, 26 July 2011

Get Element By Id in Sharepoint

I’ve just found out that using JavaScript’s getElementById() function doesn’t quite work as expected when dealing with controls on SharePoint pages. This is because SharePoint uses its own identifiers, so TextBox1 becomes something like ctl00$ctl00$g_3f6d90e4_335b_467c_a53f_6ae00bca6b63$ctl00$TextBox1.
Fortunately there’s a simple solution – instead of the following (which will cause an “Object required” JavaScript error):
document.getElementById("TextBox1");
you need to use this, which will insert the correct full ID for the element and thus work correctly:
document.getElementById("< %=TextBox1.ClientID%>");
It gets a bit more complicated when using nested controls, which is explained in this

Tuesday, 19 July 2011

How to prevent a user to close the browser window using JavaScript

           You had seen in many sites if you are going to close the page one warning windows is displayed and ask "This page is asking you to confirm that you want to leave - data you have entered may not be saved." Leave Page or Stay.......... 

           If you need a alert like this it is very very simple by using the following code
<html>
<head>
<title> sample page</title>
<script type="text/javascript">
window.onbeforeunload=checkIt;
function checkIt()
{
 return false;
}
</script>
</head>
<body>
</body>
</html>