Monday, December 22, 2008

MicroSoft in OpenSource : PHP

As the technologies grow, Microsoft is also lightning it.
Open-source initiatives at Microsoft are important to the open-source community because they give developers greater exposure for their products through access to a broadly adopted platform….The (open-source development and interoperability) initiatives are important because they break down barriers between proprietary and open-source developers allowing them to benefit from each other’s work.

Take a round to an interview with the PHP Classes blog.

Microsoft engineers and contractors have made contributions to the PHP run-time engine and to PHP application projects. And communication between Microsoft; commercial open-source-based companies including Zend, OmniTI, and iBuildings; and open-source developers has broadened significantly.

In other words, both the PHP community and Microsoft benefit from this interoperability development.
For more info: http://news.cnet.com/8301-13505_3-10126079-16.html

Open-Source Blog : Launched by MicroSoft

MicroSoft launched an Open-Source blogging platform
However, the software maker was quick to underline that the product is aimed at developers and not intended to directly compete with popular blogging software such as WordPress or Movable Type.
The same has been available at : oxite
One need MicroSoft Public licence from Open-Source License.
Read about first public release at : http://www.codeplex.com/oxite/Release/ProjectReleases.aspx?ReleaseId=20210
Oxite is a standards-compliant, extensible content-management system designed to support either blogs or larger Web sites, Microsoft said. The platform includes support for features such as pingbacks, trackbacks, anonymous or authenticated commenting, gravatars (globally recognized avatars), and RSS feeds at any page level, the company said.
For more details: http://news.cnet.com/8301-1001_3-10119017-92.html?subj=news&tag=2547-1_3-0-20&part=sphere

Sunday, December 14, 2008

Redirect to Error Page Using JavaScript

My readers enquired that how to rehuffle the yellow page on web.
The Yellow page appears when Web-Site got any runtime error.

I always suggested to supercede the Yellow-Page. Try the following code :


namespace AStepAhead.redirectErrorPage
{
public class redirectErrorPage
{
public redirectErrorPage()
{
String strDomainName = “MsDotnetHeaven.com”;
try
{
//Write you coding here
}
catch (Exception ex)
{
SystemFramework.ApplicationLog.WriteError(”Error : ” + ex.ToString());
//Redircet you main page to error page
Response.Write(”\n”);
Response.End();
}
}
}

}


Now, in error page, read ErrorString and show to the users.

Step(s): Followings are the steps to perform above:

1. Create an Error Page and named it as errorpage.aspx.
2. Read Error string at Page_load
3. Write above code in your Web Page.

After above, whenever any runtime exception occured, your user will see a maintained / designed error page.

Sunday, November 30, 2008

Writting a CLR Stored Proc

With the launch of SqlServer2005, we got the ability to write CLR from any .Net language.

Overview:


The following code-snippet tells how to write a simple CLR Stored Proc with the use

of C#.

Step:

1. Start Visual Studio2005 or higher
2. Add new file from File -> New -> File
3. Select Class with C#
4. Mark the name as AStepAheadProc.cs
5. Write the following lines:


/* This Example is a part of different
* examples shown in Book:
* C#2008 Beginners: A Step Ahead
* Written by: Gaurav Arora
* Reach at : Gaurav Arora */

using System.Data.SqlServer;
using System.Data.SqlTypes;

public class AStepAheadProc
{
public static void FirstProcProc()
{
//Client output buffer

SqlPipe sqlPipe = SqlContext.GetPipe();

//send the output

sqlPipe.Send("This is demo Store Proc Assembly");

}
}


Explanation :

The sqlContext provides The GetPipe() method returns a SqlPipe that we can use
to send results back to the client.

Steps of Use/Working

1. Compile the above code into assembly


csc /target:library c:\AStepAheadProc.cs /r:"D:\Program Files\Microsoft SQL Server\
MSSQL.1\MSSQL\Binn\sqlaccess.dll"


2. Load the created assembly in SQL with the use of CREATE PROCEDURE


create procedure AStepAheadProc
as external name AStepAheadProc.AStepAheadProc.FirstProcProc


3. Execute the Created stored procedure in Query Analyzer


exec AStepAheadProc


Note:

The above code-snippet is just describe how to create a CLT Stored Proc.

Thursday, November 27, 2008

Get Client System's Drive List : JavaScript

The following code tells how to get client systems Drive List.


<HTML>

<HEAD>



<SCRIPT language=JavaScript>



//Following function returns the drive list from client system

function getClientDrives() {

var objfs, s, n, e, x;

objfs = new ActiveXObject("Scripting.FileSystemObject");

e = new Enumerator(objfs.Drives);

s = "";

do {

x = e.item();

s = s + x.DriveLetter;

s += ": ";

if (x.DriveType == 3) n = x.ShareName;

else if (x.IsReady) n = x.VolumeName;

else n = "<font color=red>[Other Drive-not intialized]</font>";

s += n + "<br>";

e.moveNext();

} while (!e.atEnd());



return (s);

}



</SCRIPT>

</HEAD>



<BODY>

<P>

<h1>The following is the list of available drives on Client system:</h1>

<SCRIPT language=JavaScript> document.write(getClientDrives());</SCRIPT>

</P>

</BODY>

</HTML>

Sunday, November 23, 2008

ref - out : at a glance

The ref


The ref keyword causes argument passed by reference. The effect is that any chnages is made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.

An argument passed to to a ref parameter must first be initialized. his differs it from out whose argument need not be explicitly initialize before being passed.

Both ref and out are treated differently at runtime, but treated the same at compilation. Therefore, methods can't be overloaded if one method takes a ref keyword and the other takes an out argument.

Exaple:

class refpara
{
static void refMath(ref String STR)
{
STR = "Hi!";
}
static void Main()
{
String str = "Hello!";
refMath(ref str);
}
}


The out



The out keyword also causes argument to be passed by reference. There no need to initialize the out variable as it requires in case of ref variable.

Exaple:

class refpara
{
static void refMath(out String STR)
{
STR = "Hi!";
}
static void Main()
{
String str = "Hello!";
refMath(out str);
}
}

Sunday, November 16, 2008

ASP.NET MVC – A Step Ahead Series: Part-II

ASP.NET MVC – A Step Ahead Series: Part-II


This article is only for learning purpose and to enhance the ASP.Net MVC skills. The A Step Ahead Series containing few chapters to describe the same.

History


In Part-I we have learnt few basics of the ASP.Net MVC, including features and containing the creation of a sample application. In this entire tutorial we will continue the same application with other concepts.

Introduction


This part of tutorial expands the previously created project. Let’s remind the last tutorial in following steps:

  1. The MVC pattern separates the components of an MVC web application, which allows the more controls of the individual parts of that application.

  2. MVC pattern separates objects into Model, View and Controllers

  3. The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.

  4. Steps to create an ASP.Net MVC application :

    • Start your Visual Studio2008 : Start ->Programs -> Visual Studio2008

    • On the File menu, click New Project.

    • In the upper-right corner, make sure that .NET Framework 3.5 is selected.

    • Under Project types, expand either Visual Basic or Visual C#, and then click Web [I have opted C#]

    • Under Visual Studio installed templates, select ASP.NET MVC Web Application.

    • In the Name box, enter MVCApplicationStepAhead.

    • In the Location box, enter a name for the project folder.

    • If you want the name of the solution to differ from the project name, enter a name for the solution in the Solution Name box.

    • Select Create directory for solution and click OK



MVCApplicationStepAhead – At a glance


The folder structure of an MVC project differs from that of an ASP.NET Web site project. The MVC project contains the following folders:

  • Content Folder : This folder contains the style sheets. Basically this folder having responsible files for page layout, design etc.

  • Controller Folder : As ot pronounced from name this folder contains the controller files like AccountController.cs and HomeController.cs.

  • Models Folder : Contains Data Model files.

  • Script Folder : Contains Script files.

  • View Folder : For view page files. This folder contains three subfolders: Account, Home, and Shared. The Account folder contains views that are used as UI for logging in and changing passwords. The Home folder contains an Index view (the default starting page for the application) and an About page view. The Shared folder contains the master page view for the application.



Creating the Routes


One of the powerful new features that ASP.NET MVC brings to the table is the ability to customize the URLs that access your application. The URL routing feature explicitly breaks the connection between physical files on disk and the URL that is used to access a given bit of functionality. This is important for Search Engine Optimization as well as general usability of the website.
This is done by creating a route table in the global.asax file in the MVC Application. Luckily for us, the defaults included in the template work perfectly this application.

Finally, we are ready to start creating application:

Scope :


Scope of our Test application is

  • Creation of an Interface for employees to:

  • Defining their roles

  • Getting Roles

  • Checking the availability of an Employee [whether retiree or not]


Requirement :


We need for above

  • A Storage where we put records – The Model

  • An Interface where user can interact – The Viewer

  • A media through which all activities could be inspected – The Controller


Selecting Application :


We have assigned tasks for .Net and we need MVC, so, the best selection of language is ASP.NET MVC.
Now, let’s start creating above one-by-one [I assume that there is no predefined file exists]:

Creation of Model


First o f all as have discussed we want a Container where we store our data. Here What I mean of Container , ofcourse, a Database.
Here are three options for you to choose container of this application:

  1. Go with the existing database file EmployeeDB.mdf under App_data folder of application.

  2. Use the available script EmployeeDB.sql available under App_data folder of application to create above database

  3. Finally, follow bellow mentioned steps to create a new database from / within the environment :

  4. Select App_data folder Choose New From File -> New -> File option , or

  5. Right Click the App_data to add new database file.

  6. Create a Database with name EmployeeDB

  7. Create a Table ERoles following is the query for this :



/*******************************************
*This script creates
****** database EmployeeDB
****** Table Roles
********************************************/

IF EXISTS (SELECT name FROM sys.databases WHERE name = N'EmployeeDB')
DROP DATABASE [EmployeeDB]
Go
CREATE DATABASE [EmployeeDB]
GO

USE [EmployeeDB]
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Roles]') AND type in (N'U'))
DROP TABLE [dbo].[Roles]
GO

/********************************************************************
******This script is a part of ASP.NET MVC-A Step Ahead Series
****** Written by : Gaurav Arora
****** Reach author at : webmaster@msdotnetheaven.com
****** Anyone can use this for educational purposes.
**********************************************************************/

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Roles](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Role] [nvarchar](300) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[IsRetiree] [bit] NOT NULL,
[HireDate] [datetime] NOT NULL,
CONSTRAINT [PK_Roles] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


  • Fill some initial values into new created table either from Environment or Query analyzer :


  • USE [EmployeeDB]
    GO

    INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])
    VALUES('Manager - Resource',0,'01/01/2005')
    GO
    INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])
    VALUES('Manager - Technical',0,'01/11/1999')
    GO
    INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])
    VALUES('Member - Technical Staff',0,'01/11/2007')
    GO
    INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])
    VALUES('Sr. Member - Technical Staff',0,'11/11/2007')
    GO
    INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])
    VALUES('Lead Member - Technical Staff',1,'11/11/1986')
    GO

    Alternatively, you can also used available stored procedures. I am not discussing about Stored Procedure here.
    Finally, you have a database with table.
    Note: You can change the name of above objects as per your feasibility.
    With the invention of LINQ, its very easy to solve the smut problems in applications. Here to defining a Model.
    There are many tools to generate this task like :

    1. LINQ To SQL

    2. nHibernet

    3. Entity Framework



    I prefer to use LINQ to SQL, although above three are likely to be same but I always use LINQ to SQL.

    To do the same :

    Right click on Models folder and select Add New Item -> LINQ To SQL -> EmpRole.dbml

    Now, just pick and drop your object of Container i.e. ERoles table on Method Pane.
    Alternatively, you can create a new class from tool box by defining all the elements.
    Finally, click on ‘Save’ when done.

    Many author says that the next step should be adding the logics but my opinion is you should have at-least one interface to interact user then may go for logics.

    So, lets start to create a UI:

    Creation of Views


    Right Click on Home folder under Views folder to add new Views.
    Select Add -> View Create.aspx, Home.aspx these are the two views we need here.

    Now Double click on Index.aspx and put following lines there:

    First include namespace:


    <%@ Import Namespace="MVCApplicationStepAhead.Models" %>


    Now, rewrite the above with following code:


    <!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 id="Head1" runat="server">
    <title>Employee Roles</title>
    </head>
    <body>
    <div>
    <h1>
    Employee Roles</h1>
    <ul>
    <%foreach (RoleE roleE in (IEnumerable)ViewData.Model)
    {%>
    <li>
    <%if (roleE.IsRetiree)
    { %>
    <font color="red">
    <%= roleE.HireDate.ToShortDateString() %>
    --
    <%= roleE.Role1%>
    </font>
    <%}
    else
    { %>
    <a href="/Home/Complete/<%=roleE.Id.ToString() %>" >Change Role as Retiree</a>
    <%= roleE.HireDate.ToShortDateString() %>
    --
    <%= roleE.Role1 %>
    <% } %>
    </li>
    <% } %>
    </ul>
    <br /><br />
    <a href="/Home/Create">Add New Task</a>
    </div>
    </body>
    </html>


    The above piece of code – just defining the activities of getting Available roles of Employee, adding new roles with Employee, changing Employee current roles.
    In Create.aspx page we pull some new roles, use following code:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Create.aspx.cs" Inherits="MVCApplicationStepAhead.Views.Home.Create" %>

    <!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>
    <div>
    <h1>
    Add New Role</h1>
    <form method="post" action="/Home/CreateNew">
    <label for="role">
    Role: </label>
    <input type="text" name="role" />
    <br />
    <input type="submit" value="Add Task" />
    </form>
    </div>
    </body>
    </html>



    As you can check here we are using postmethod.
    Do not confuse with both above two pages, very soon you will get all the answers of your queries:

    Creation of Controllers:


    Click on Controllers folder and add new MVC controller, named as HomeController.cs

    Put the following lines there:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    using MVCApplicationStepAhead.Models;

    namespace MVCApplicationStepAhead.Controllers
    {
    public class HomeController : Controller
    {
    private EmpRoleDataContext dbEmpRole = new EmpRoleDataContext();

    //Display a list of Roles
    public ActionResult Index()
    {
    var roles = from r in dbEmpRole.RoleEs orderby r.HireDate descending select r;

    //return View();
    return View(roles.ToList());
    }

    //New Role form
    public ActionResult Create()
    {
    return View();
    }

    //Adding new Roles

    public ActionResult CreateNew(string roleDescription)
    {
    //New role to database
    RoleE newRole = new RoleE();
    newRole.Role1 = roleDescription;
    newRole.IsRetiree = false;
    newRole.HireDate=DateTime.Now;

    dbEmpRole.RoleEs.InsertOnSubmit(newRole);

    return RedirectToAction("Index");
    }

    //Mark that Role has been Completed
    public ActionResult Complete(int Id)
    {
    //database tasks here
    var roles = from r in dbEmpRole.RoleEs where r.Id == Id select r;

    foreach (RoleE match in roles)
    match.IsRetiree = true;

    dbEmpRole.SubmitChanges();

    return RedirectToAction("Index");
    }

    }
    }

    Finally, we reach to conclusion:
    Now you can build application or run application:
    Start the above application by pressing F5
    Add some new roles, change roles to retiree etc.
    Conclusion

    The ASP.NET MVC provides us a huge availability to represent our application in of MVC manner:
    The folder structure of an MVC project differs from that of an ASP.NET Web site project. The MVC project contains the following folders:

    • Content Folder : This folder contains the style sheets. Basically this folder having responsible files for page layout, design etc.

    • Controller Folder : As ot pronounced from name this folder contains the controller files like AccountController.cs and HomeController.cs.

    • Models Folder : Contains Data Model files.

    • Script Folder : Contains Script files.

    • View Folder : For view page files. This folder contains three subfolders: Account, Home, and Shared. The Account folder contains views that are used as UI for logging in and changing passwords. The Home folder contains an Index view (the default starting page for the application) and an About page view. The Shared folder contains the master page view for the application.


    This all above for Tutorial Part – II.
    We will include some advance topics in our next tutorials.

    Code Dom: A Step Ahead Series

    Code Dom: A Step Ahead Series

    Introduction:


    This is a continuation to my earlier post C#-The Language : A Step Ahead Series-Part-II
    The following code snippet showed the power of CODE DOM:

    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : msdotnetheaven*/

    // File name : CodeDomExpl.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.CodeDom;
    using System.CodeDom.Compiler;
    using Microsoft.CSharp;
    using System.IO;

    namespace CSharp.AStepAhead.CodeDomExpl
    {
    public class CodeDomExpl
    {
    public static void Main()
    {
    Console.Clear();
    Console.Write("This will create a simple Console aplication\n");
    Console.Write("\n Enter Namespace: ");
    string nmSpace = Console.ReadLine();

    Console.Write("\n Enter Class file name: ");
    string fName = Console.ReadLine();

    Console.Write("\n Enter Output file name: ");
    string oFname = Console.ReadLine();

    Console.Write("\n Enter Your message: ");
    string msg = Console.ReadLine();

    if (nmSpace.Length == 0)
    nmSpace = "CSharp.AStepAhead.CodeDomExpl";
    if (fName.Length==0)
    fName = "CodeDomExpl.cs";
    if (oFname.Length==0)
    oFname ="CodeDomExpl.exe";
    if (msg.Length==0)
    msg = "Hello! I am created using CodeDom i.e. Code Document Object Model.";



    //Validate enteries
    nmSpace = CodeDomExpl.chkValid(nmSpace,0);
    fName = CodeDomExpl.chkValid(fName,1);
    oFname = CodeDomExpl.chkValid(oFname,2);
    msg = CodeDomExpl.chkValid(msg,3);

    //create an instance of the class
    GenerateConsoleApp oC = new GenerateConsoleApp(nmSpace,fName,oFname,msg);
    oC.CreateCode();
    Console.WriteLine("\nApplication crated :\nSource File Name :{0}\nExecutable File Name :{1}", fName, oFname);
    Console.ReadLine();
    return;
    }
    public static string chkValid(string str,int id)
    {
    string newStr=string.Empty;
    string filePath = @"F:\myWrittings\CSharpBook\Source Codes\CodeDomApplications\";
    switch (id)
    {
    case 3: //message
    {
    newStr = str;

    break;
    }
    case 2: //output file name
    {

    int i = str.IndexOf(".");

    newStr = (i > 0) ? filePath + str.Substring(0, i) + ".exe" : filePath + str + ".exe";

    break;
    }



    case 1: //class file name
    {

    int i = str.IndexOf(".");
    newStr = (i > 0) ? filePath + str.Substring(0, i) + ".cs" : filePath + str + ".cs";

    break;
    }
    case 0: //namespace
    {

    int i = str.IndexOf(".");
    newStr = "CSharp.AStepAhead.";
    newStr += (i > 0) ? str.Substring(0, i) : str;

    break;
    }
    }
    return newStr;

    }
    }

    public class GenerateConsoleApp
    {

    public string nameSpace;
    public string sourceFile;
    public string executingFile;
    public string customMessage;



    public GenerateConsoleApp()
    {
    }
    public GenerateConsoleApp(string nmSpace, string csFile,string exeFile,string msg)
    {
    nameSpace = nmSpace;
    sourceFile = csFile;
    executingFile = exeFile;
    customMessage = msg;
    }
    public void CreateCode()
    {
    CodeCompileUnit unit = GenerateCode();

    // Set up options for source code style
    CodeGeneratorOptions opts = new CodeGeneratorOptions();
    opts.BracingStyle = "C";
    opts.IndentString = "\t";


    // Create code generator and write code file
    CSharpCodeProvider cscp = new CSharpCodeProvider();

    ICodeGenerator gen = cscp.CreateGenerator();

    StreamWriter sw = new StreamWriter(sourceFile);
    gen.GenerateCodeFromCompileUnit(unit, sw, opts);
    sw.Close();

    CompilerParameters compilerParams = new CompilerParameters();
    compilerParams.GenerateExecutable = true;

    compilerParams.OutputAssembly = executingFile;

    ICodeCompiler compiler = cscp.CreateCompiler();

    compiler.CompileAssemblyFromFile(compilerParams, sourceFile);
    }


    private CodeCompileUnit GenerateCode()
    {
    CodeEntryPointMethod objMainMethod = new CodeEntryPointMethod();
    objMainMethod.Name = "Main";

    // generate this expression: Console
    CodeTypeReferenceExpression consoleType = new CodeTypeReferenceExpression();
    consoleType.Type = new CodeTypeReference(typeof(Console));

    // Set up the argument list to pass to Console.WriteLine()
    CodeExpression[] writeLineArgs = new CodeExpression[1];
    CodePrimitiveExpression arg0 = new CodePrimitiveExpression(customMessage);
    writeLineArgs[0] = arg0;

    // generate this statement: Console.WriteLine(message)
    CodeMethodReferenceExpression writeLineRef = new CodeMethodReferenceExpression(consoleType, "WriteLine");
    CodeMethodInvokeExpression writeLine = new CodeMethodInvokeExpression(writeLineRef, writeLineArgs);

    // generate this statement: Console.ReadLine()
    CodeMethodReferenceExpression readLineRef = new CodeMethodReferenceExpression(consoleType, "ReadLine");
    CodeMethodInvokeExpression readLine = new CodeMethodInvokeExpression(readLineRef);

    // Add Main() method to a class
    CodeTypeDeclaration theClass = new CodeTypeDeclaration();
    theClass.Members.Add(objMainMethod);

    string className = string.Empty;
    //retrieve actual class name
    int j = sourceFile.LastIndexOf(@"\");
    int k = sourceFile.IndexOf(".");
    className = sourceFile.Substring(j + 1, k - j - 1);


    // Add both the code of WriteLine and Readline
    objMainMethod.Statements.Add(writeLine);
    objMainMethod.Statements.Add(readLine);

    // Add namespace and add class
    CodeNamespace ns = new CodeNamespace(nameSpace);
    ns.Imports.Add(new CodeNamespaceImport("System"));
    ns.Types.Add(theClass);

    // Generate the Compile Unit
    CodeCompileUnit unit = new CodeCompileUnit();
    unit.Namespaces.Add(ns);

    return unit;
    }

    }
    }


    To represent source code, CodeDOM elements are linked to each other to form a data structure known as a CodeDOM graph, which models the structure of some source code.

    The System.CodeDom namespace defines types that can represent the logical structure of source code, independent of a specific programming language.

    Simply, it is an object model which represents actually source code. It is designed to be language independent.

    Some common uses for the CodeDOM include:



    • Templated code generation: generating code for ASP.NET, XML Web services client proxies, code wizards, designers, or other code-emitting mechanisms.

    • Dynamic compilation: supporting code compilation in single or multiple languages.

    Control State, Partial Class, Iterators, Nullable – At a glance

    Control State, Partial Class, Iterators, Nullable – At a glance

    Control State



    Control State is a new feature added in Asp.net2.0 framework. Control state is very similar to View State, where value is stored in the hidden_VIEWSTATE form field, with a little difference i.e. Control State cannot be disabled. Control state is intended to be used only for storing crucial information across postbacks.


    Partial Classes



    Partial Classes are new feature added to the .net framework 2.0. Partial classes allow dividing up a single class into multiple class file. These classes are combined into a single class later when compiling. To create a partial class there is a simple keyword partial.

    Example:

    public partial class MathClass
    {
    public int Add(int a, int b)
    {
    return a+b;
    }
    }

    public partial class MathClass
    {
    public int Substract(int a, int b)
    {
    return a-b;
    }
    }



    At compile time system gather the information of all relevant partial classes MathClass in above case, and combined all into a single class.

    Iterators


    Iterators enable us to use foreach loops on our own custom types. To achieve the same we need to have class implement the IEnumerable interface.

    Example:

    public class mylistClass
    {
    internal object[] objElements;
    internal int intcount;
    public IEnumerator GetEnumerator()
    {
    yield return “Gaurav”;
    yield return “Shuby”;
    }
    }

    //here is the use
    //put following code at anywhere as per your requirement, I used it on page_load

    Void pageload(object sender, EventArgs e)
    {
    //create an instance of class
    mylistClass custList = new mylistClass();

    foreach (String custItem in custList)
    {
    Response.Write(“Item : “ +custItem.ToString() + “<br/>”);
    }

    }



    Note:
    You need to include System.Collections namespace in above.


    Nullable



    Nullable types are instances if System.Nullable. A nullable type can represent the normal range of values of its underlying value type plus an additional null value.

    Example:


    namespace AStepAhead.Nullable
    {
    class nullableclass
    {
    static void Main(string[] args)
    {
    int? num = null;
    int? num1 = null;
    if (num.HasValue == true)
    {
    Console.WriteLine("Num : {0}", num);
    }
    else
    {
    Console.WriteLine("Num has Null value");
    }

    //int y = num.GetValueOrDefault(); //throw an exception
    int z;
    try
    {
    //y = num.Value;
    //Console.WriteLine("Y:{0}", y);
    z = num1 ?? 2;
    Console.WriteLine("Z:{0}", z);
    }
    catch(Exception ex)
    {
    Console.WriteLine(ex.Message);
    }


    Console.ReadLine();
    }
    }
    }


    Note:
    You need to include System.Collections.Generic namespace in above.

    Monday, October 13, 2008

    Silverlight2.0 : releases on Monday

    Get ready for Silverlight2.0 release on Monday

    I got the news from one of my friend and want to share the same with you. MicroSoft decided to release Silverlight2.0 on Monday.

    I have not more for its:
      1. Features
      2. Working
      3. New implementations
      4. Flexibility etc.

    Only the idea is that its a great inventions in the new era.

    For more information pelase visit : http://news.cnet.com/8301-13860_3-10063722-56.html

    Wednesday, October 8, 2008

    Visual Studio 2010 : MicroSoft Next release

    Visual Studio 2010 : MicroSoft Next release

    In the world of languages MicroSoft will introduce its new release very soon. The .net version is 4.0 for this release.
    There are lot of following lot of promises :
    1. Improved Software testing tools
    2. Database functions for application lifecycle management

    For more detail please visit : Visual Studio 2010

    Monday, October 6, 2008

    Want to Shrink Images - Now its easy by Yahoo tool

    Want to Shrink Images - its easy with Yahoo tool

    Whenever I want to put some images on my website, I stucked with the size issues of images [this is the most known issue]. I thank to entire development team of Yahoo, who have introduced a new Web based tool smush it

    To know more in detail please visit : Yahoo makes it easy!

    Some of the feature(s):

    1. It shrinks the size.

    2. It contains the visibility.

    3. It converets format too.


    and many more unbelievable features.

    Saturday, August 30, 2008

    Android apps store - by Google

    Its a new lime way of Google, on Thursday Google walks to start application store similiar to iPhone's App, this storeis for Android apps.

    Actually, I am also very much beginner to this one as anyone else.

    To more in details please visit:

    Android Developers Blog

    http://www.infoworld.com/archives/emailPrint.jsp?R=printThis&A=/article/08/08/28/Google_introduces_Android_apps_store_1.html

    Please share your update knowledge about technical news.

    Sunday, August 10, 2008

    MicroSoft's Greatest Release : SQL Server 2008

    On Wednesday MicroSoft releases SQL Server 2008 .

    This is the great invention to the older ones' like SQL Server 2000 and SQL Server 2005. But, all the work is not put ahead Microsoft on top in the Warehouse Market. There are still Oracle, IBM abd TeraData.

    For viewers and MicroSoft Well-wishers [like me...] are very much happy to read this news.

    Lets share the news and celebaret the among our world.

    For more info visit :
    http://www.informationweek.com/shared/printableArticle.jhtml?articleID=209903873

    Classes and Structures

    Lets take these in general words, these are template from which you define object to access their functionalities. The programmers of C++ and Java are well aware from these two names. Till now from above reading you new that Classes are reference type and structures are value type so they are stored on Heap and Stack respectively in memory.

    Structures
    A structure in C# is simply a composite data type [you are well aware from composite data type, refer to data types for more details], which consists number of members of other types. The structure define simply by using the struct keyword



    struct enroll
    {
    public string name, fname, mname;
    public string char sex;
    Public int age;
    public string address;
    }




    Important points towards structures

    There are some points towards structures:
    1. Structures are C# composite data types
    2. By default like classes structures are public
    3. Sealed and Abstract modifiers cant applicable on structures
    4. Structures have no inheritance features
    5. A variable of structure type contains all the data of structure
    6. Structures cant allow a destructor
    7. By default C# provides a constructor with no parameter, but explicitly you cant use and replace it.
    8. Initializations of fields are not allowed.


    Classes
    It is cleared from above study that Classes are reference type. A class is a collection of its data members. Data members are those members of class which contains the data of class like fields, constants and events etc. Class is declared simply just followed by class keyword with optional modifiers; by default C# classes are public.



    class myClass
    {
    public int xyz;
    public string name;
    public const int y=22;
    }







    In above, all members are public, when we declare members we can optionally supply modifiers, in C# all class members private by default.



    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : gaurav.aroraose@yahoo.co.in*/
    // File name : classstructue.cs
    using System;
    namespace CSharp.AStepAhead.classstructue
    {
    class enroll
    {
    string name, fname;
    int age;
    char sex;
    void getInfo()
    {
    Console.WriteLine("Enter Name: ");
    name = Console.ReadLine();
    Console.WriteLine("Enter Father Name: ");
    fname = Console.ReadLine();
    Console.WriteLine("Enter age: ");
    age = int.Parse(Console.ReadLine());
    Console.WriteLine("Enter Sex [Male -m, Female - f]: ");
    sex = char.Parse(Console.ReadLine());
    }
    void showInfo()
    {
    Console.Clear();
    Console.WriteLine("You have provided following information(s): \n");
    Console.WriteLine(" Name : {0}\n Father Name : {1}\n Age : {2}\n Sex : {3}", name, fname, age, sex);
    Console.ReadLine();
    }
    static void Main()
    {
    //Create an object of class
    enroll objEnroll = new enroll();
    objEnroll.getInfo();
    objEnroll.showInfo();
    }
    }
    }



    Moonlight : Handles Silverlight Application in Unix

    As you knew that Mono project provides the platform to run .Net application on UNIX. Now, there is a new term Silverlight in the field of .Net so, what about the UNIX fellows.
    Will they stand alone?
    No, Mono has decided to plan Moonlight which runs on Unix for Silverlight.

    To do the same:
    -One need SDK
    -Build Silverlight program

    For more detail please visit: http://www.mono-project.com/Moonlight

    Mono Project - CAS

    I have very little idea about Mono Project, it is a Software platform which helps to develop cross-platform applications. This is a great one helps us to run .net on Unix.
    It has C# Compiler http://www.mono-project.com/CSharp_Compiler, Mono Runtime http://www.mono-project.com/Mono:Runtime,
    These all are as per ECMA http://www.mono-project.com/ECMA
    In Version Mono 1.2 there is no security model like CAS – Code Access Security, but in future version Mono will be with CAS.

    For more information please visit : http://www.mono-project.com/CAS

    World’s costlier computer: Human Being

    Teacher: Tell me the name of cheapest computer in the universe
    KMG: Human Being
    There is whispering in class, teacher also shocked.
    Teacher: What are you saying? How?
    KMG: I am right mam
    There are noises in the class and teacher is in angry mood
    Teacher [strictly]: You are wrong, sit down.
    KMG: I can prove it mam
    Teacher: I said, sit down. Otherwise you will punish.
    KMG: No, mam let me prove:
    -Humans have CPU: their brain
    -Humans have vision: their eyes
    -Humans also need resources: Glucose, air, water etc.
    -Humans have voice: Can communicate in different languages
    There is silence in class, teacher asked suddenly
    Teacher: Ok, Ok but how it is cheap.
    KMG: Humans have heart: No computer has heart
    Heart pumps 24X7 and then its CPU work and functioning. It’s absolutely free.
    Neuron system developed on the basis of human CPU
    Teacher: Yes, yes
    Suddenly, another student interfere
    Pankaj: No, mam it’s not cheaper. It is costlier in compare to Computers
    It creates noise
    It creates pollution
    It cuts greenery
    It makes bombs
    It creates partitions between regions
    Today, brain is heavy on heart and nobody control it.
    Mam, Human-being knew there is no life without Greenery, Air, Sun, Water, they knew piece is the best, then why they are playing with their lives.
    Teacher: Pankaj, this is not our subject.
    KMG: No, mam, its. Sorry, mam, I was wrong Pankaj is right. Is it possible to control human-being like Operator can control computers.
    Teacher: silence
    Pankaj: Mam, we are growing we need piece, greenery and want to be cheaper computer in the world
    Teacher: Right
    KMG: If you knew it then why don’t you teach others?
    Teacher: Again silence
    Pankaj: Are they big student mam?
    Teacher: Don’t know who will teach them or how they will learn all these? But, till that day “World’s Costlier Computer is Human-Being”.

    There are lots of questions in the mind of students, which can easily be ignored. But, what about you.

    Think it again and again…..

    Tuesday, August 5, 2008

    Got Editor's Choice Award

    I am feeling great to share good news with all of you. I got the prestigious award from dotnetspider, this is a prestigious award in the life of any Technical guy. This is the golden day in my life.

    I am very much thankful to the community to choose me for such a great honor. For more info please Visit this page for the list of winners - http://www.dotnetspider.com/credits/Index.aspx.

    Monday, August 4, 2008

    A Simple VideoPlayer Custom COntrol - Uses in application

    In my previous post, I have presented a Video Player Custom control which plays all type of streaming media. Now, here I am presenting a simple way to apply the same custom control in web application.

    File Name : VideoPLayerCustomControl.aspx
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="VideoPLayerCustomControl.aspx.cs"
    Inherits="VideoPLayerCustomControl" %>

    <%@ Register TagPrefix="whPlayer" TagName= "vaPlayer" Src="~/videoPlayer.ascx" %>
    <!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>Video Player Using Custom Control</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div align="center">
    <whPlayer:vaPlayer ID="videoPlayer" autoStart="true" runat="server" />
    <br />
    <asp:ValidationSummary id="valSumm" runat="server" />
    <asp:Label ID="lblVideoName" Text="Enter Video Name" runat ="server" />
    <asp:TextBox ID="txtVideoName" runat="server" EnableViewState="true" Text="D:\Videos\AVSEQ06.DAT" />
    <asp:Button ID="btnPlayVide" runat="server" OnClick="btnPlayVide_Click" Text="Play Video" />
    <asp:RequiredFieldValidator id="rfvtxtVideoName" ControlToValidate="txtVideoName" text="*" ErrorMessage="Please eneter Video to play" runat="server" />

    </div>
    </form>
    </body>
    </html>
    File Name : VideoPLayerCustomControl.aspx.cs
    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : g_arora@hotmail.com */
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    public partial class VideoPLayerCustomControl : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if (Request.QueryString["sourceUrl"] != null)
    this.videoPlayer.sourceUrl = Convert.ToString(Request.QueryString["sourceUrl"]);

    videoPlayer.autoStart = true;
    videoPlayer.height = "300";
    videoPlayer.width = "300";
    }

    protected void btnPlayVide_Click(object sender, EventArgs e)
    {
    if(IsValid)
    Response.Redirect("videoplayercustomcontrol.aspx?sourceUrl=" + txtVideoName.Text);

    }
    }

    Steps to run the application
    1. Open VS2005
    2. Select New Web application

    3. Add new Page from existing pages and browse to attachment
    4. Run the applcation by prssing F5

    OR

    3. If not want to add new page just copy and paste the content from above, code(s)
    4. Make sure all contents would be copied and then press F5

    and then Enjoy the video...

    A VideoPlayer - Custom Control

    Some day ago, I have faced a little problem to show streaming contents on my Web-Projects, I have gone through many R & d’s and then decided to write a custom control for the same, then I have written a custom control.

    Here, the same, I want to share with you:
    File Name : videoPlayer.ascx

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="videoPlayer.ascx.cs" Inherits="videoPlayer" %>
    <asp:PlaceHolder ID="phError" runat="server" Visible="false">
    <%asp:Label ID="lblError" runat="server" ForeColor="Red" Text="Error" />
    </asp:PlaceHolder>
    <asp:Table ID="tblPlayer" runat="server" BorderWidth="1">
    <asp:TableRow>
    <asp:TableCell>
    <asp:Literal ID="ltVideo" runat="server" />
    </asp:TableCell>
    </asp:TableRow>
    </asp:Table>

    Now, lets start to write code-behind as follows:
    File Name : videoPlayer.ascx.cs

    /* This Example is a part of different
    * examples shown in Book:
    * C#2005 Beginners: A Step Ahead
    * Written by: Gaurav Arora
    * Reach at : g_arora@hotmail.com */
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    public partial class videoPlayer : System.Web.UI.UserControl
    {
    #region Properties to customize the Video/Audio Control

    ///
    /// true:FullScreen, false:CustomSize
    ///
    public Boolean isFullSize
    {
    set
    {
    ViewState["isFullSize"] = value;
    }
    get
    {
    if (ViewState["isFullSize"] != null)
    return Convert.ToBoolean(ViewState["isFullSize"]);
    else
    return true;
    }
    }
    ///
    /// Full url-path of Video/Audio
    ///
    public String sourceUrl
    {

    set
    {
    ViewState["sourceUrl"] = value;
    }
    get
    {
    if (ViewState["sourceUrl"] != null)
    return Convert.ToString(ViewState["sourceUrl"]);
    else
    return "http://www.video.com/myVideo.mpeg"; //Default video

    }

    }
    ///
    /// width of player
    ///
    public String width
    {
    set
    {
    ViewState["width"] = value;
    }
    get
    {
    if (ViewState["width"] != null)
    return Convert.ToString(ViewState["width"]);
    else
    return "640";
    }
    }
    ///
    /// Height of player
    ///
    public String height
    {
    set
    {
    ViewState["height"] = value;
    }
    get
    {
    if (ViewState["height"] != null)
    return Convert.ToString(ViewState["height"]);
    else
    return "480";
    }
    }
    ///
    /// Custom message when player initializes
    ///
    public String standByMessage
    {
    set
    {
    ViewState["standByMessage"] = value;
    }
    get
    {
    if (ViewState["standByMessage"] != null)
    return Convert.ToString(ViewState["standByMessage"]);
    else
    return "Please wait while the player inializes...";
    }
    }
    ///
    /// States whether media automatic starts or not
    ///
    public Boolean autoStart
    {
    set
    {
    ViewState["autoStart"] = value;
    }
    get
    {
    if (ViewState["autoStart"] != null)
    return Convert.ToBoolean(ViewState["autoStart"]);
    else
    return true;
    }
    }
    ///
    /// -100 is fully left, 100 is fully right.
    ///
    public String balance
    {
    set
    {
    ViewState["balance"] = value;
    }
    get
    {
    try
    {
    if (ViewState["balance"] != null)
    return Convert.ToString(ViewState["balance"]);
    else
    return "0";
    }
    catch
    {
    return "0";
    }
    }
    }
    ///
    /// Position in seconds when starting.
    ///
    public Int32 currentPosition
    {
    set
    {
    ViewState["currentPosition"] = value;
    }
    get
    {
    if (ViewState["currentPosition"] != null)
    return Convert.ToInt32(ViewState["currentPosition"]);
    else
    return 0;
    }
    }

    ///
    /// Show play/stop/pause controls
    ///
    public Boolean showcontrols
    {
    set
    {
    ViewState["showcontrols"] = value;
    }
    get
    {
    if (ViewState["showcontrols"] != null)
    return Convert.ToBoolean(ViewState["showcontrols"]);
    else
    return true;
    }
    }
    ///
    /// Allow right-click
    ///
    public Boolean contextMenu
    {
    set
    {
    ViewState["contextMenu"] = value;
    }
    get
    {
    if (ViewState["contextMenu"] != null)
    return Convert.ToBoolean(ViewState["contextMenu"]);
    else
    return false;
    }
    }
    ///
    /// Toggle sound on/off
    ///
    public Boolean mute
    {
    set
    {
    ViewState["mute"] = value;
    }
    get
    {
    if (ViewState["mute"] != null)
    return Convert.ToBoolean(ViewState["mute"]);
    else
    return false;
    }
    }
    ///
    /// Number of times the content will play
    ///
    public Int32 playCount
    {
    set
    {
    ViewState["playCount"] = value;
    }
    get
    {
    if (ViewState["playCount"] != null)
    return Convert.ToInt32(ViewState["playCount"]);
    else
    return 1;
    }

    }
    ///
    /// 0.5=Slow, 1.0=Normal, 2.0=Fast
    ///
    public Double rate
    {
    set
    {
    ViewState["rate"] = value;
    }
    get
    {
    if (ViewState["rate"] != null)
    return Convert.ToDouble(ViewState["rate"]);
    else
    return 1.0;
    }
    }
    ///
    /// full, mini, custom, none, invisible
    ///
    public String uiMode
    {
    set
    {
    ViewState["uiMode"] = value;
    }
    get
    {
    if (ViewState["uiMode"] != null)
    return Convert.ToString(ViewState["uiMode"]);
    else
    return "Full";
    }
    }
    ///
    /// Show or hide the name of the file/url
    ///
    public Boolean showDisplay
    {
    set
    {
    ViewState["showDisplay"] = value;
    }
    get
    {
    if (ViewState["showDisplay"] != null)
    return Convert.ToBoolean(ViewState["showDisplay"]);
    else
    return false;
    }
    }

    ///
    /// 0=lowest, 50= normal, 100=highest
    ///
    public Int32 volume
    {
    set
    {
    ViewState["volume"] = value;
    }
    get
    {
    if (ViewState["volume"] != null)
    return Convert.ToInt32(ViewState["volume"]);
    else
    return 50;
    }
    }

    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {

    try
    {
    ltVideo.Text = this.VideoPlayer(this.sourceUrl, this.isFullSize);
    }
    catch (Exception ex)
    {
    lblError.Text = ex.ToString();
    phError.Visible = true;
    }
    }

    #region VideoPlayer
    ///
    /// Return the whPlayer to Play Video/ Audio Content
    ///
    /// Source of content
    /// Size of Player
    ///
    private string VideoPlayer(string strsourceUrl, bool boolFullSize)
    {
    string whPlayer = "";
    strsourceUrl = strsourceUrl + "";
    strsourceUrl = strsourceUrl.Trim();

    if (strsourceUrl.Length < 0)
    {
    //play content
    }
    else
    {
    throw new System.ArgumentNullException("strsourceUrl");
    }


    if (boolFullSize)
    {
    //this.width = String.Empty;
    //this.height = String.Empty;
    this.width = "800";
    this.height = "600";
    }
    else
    {
    //continue with supplied width/height
    }

    whPlayer = whPlayer + "";

    return whPlayer;
    }
    #endregion
    }

    In Next article, I will tell you how to use the VideoPlayer Custom Control?

    Sunday, August 3, 2008

    Really Midori supersedes Windows?

    I have got news from one of my reader that in future there will be a new name Midori instead of Windows. Till today there is no official definition for Midori but Midori is a componentized and a non-windows operating system.

    So, let’s prepare for a new upcoming era. I want to share the news with all of you, just visit: Microsoft prepares for end of Windows with Midori

    Sunday, July 27, 2008

    What is DLR?

    Yes, this is a new name heard by me. I am very much beginner for DLR. I know little about DLR and the same sharing with you.

    DLR stands for Dynamic Language Runtime, it would be a layer top on the CLR.

    For more detail, must look these links:-

    http://geekswithblogs.net/ranganh/archive/2008/07/24/dlr-hosting.aspx
    http://blogs.msdn.com/seshadripv/
    http://www.codeplex.com/sdlsdk
    http://blogs.msdn.com/hugunin/archive/2007/04/30/a-dynamic-language-runtime-dlr.aspx

    How to shuffle results - SqlServer?

    This is an interesting question asked by Mr. Ram Nath Rao.
    The history is:

    Mr. Nath wants to shuffle his record(s) every time when the page refreshes, the same has been tried with the use of rand() function by him. Unfortunately, the results were not as expected.

    Now, lets elaborate some of interesting points towards this :

    When anybody use rand() function what happened [check followings)]:

    Select rand()as Random Number --creates random number

    The result may be:



    When you will repeat above statement, the new result is entirely different from the earlier one.

    Now, try another similar query:

    Select rand()as Random_Number,* from Employees

    The result may be:



    In above, result note-down first column Random_Number, this column has the similar value through-out the result.

    In another words from above, we can sum-it up that the rand() function, generates a random number which is a new every time we press or execute the query.

    Also, it doesn't change with rows when result-set retrieves more than one row(s). So, the problem of Mr. Ram Nath Rao doesn't resolve with the use of rand() function.

    I recommended newid() to retrieve the solution of Mr. Ram's problem.

    Check the following query:

    Select newid()as RowId,* from Employees

    Above generates following result(s):-



    Note-down first column of above result(s), every row has a new value.

    Now, lets try to ad-more stuff in above:

    Select newid()as RowId,* from Employees order by newid()



    Now, regenerate above result(s) one more time, you can get different resul(s). This is the solution of the problem.

    The above is a short-description how we can get random data in SqlServer2000.

    Its time to do all above at application-level, I have decided to use Vs2005:

    Step(s) to use:

    1. Start your Vs2005
    2. Create a New Website project named its as 'Shuffle Result'.
    3. Rename your default web-page to 'shuffleresults.aspx'
    4. Write the following lines



    5. Press F7 or choose code-view from Solution-Explorer
    6. Add following sort-of-code in 'shuffleresults.aspx.cs'



    7. Run the above application by pressing F5.
    8. It will generate following result(s):



    This is the normal output.

    9. Click on 'Shuffle Results' button and check the output it might be s following :



    The above is described "How one can shuffle the result-sets".

    Sunday, July 20, 2008

    How to review .net application?

    This is not the end when any application has been developed. After development there are many steps which must have to pass by an application. The same process is know as Code-Review process.

    Here are certain guidelines which are assembled by me for my work, I hope these will suits you. Your comments and further guidelines will recoupe our stuffs.



    This is just a snapshot the guidelines due to limited resources I am unable to write here all document. You can collect the document by sending me a mail :
    gUnderscorearoraAthotmailDotcom with subject: Guidelines-Code-Review.

    Sunday, July 13, 2008

    Database object naming conventions - SQLSERVER

    Database object naming conventions

    There is no such hard and fast rule to define database names, but I prefer to use some naming conventions which will polish your task(s):

    I always usee the following(s):-

    1. Tables
    Tables represent the instances of an entity. For example, you store all your customer information in a table. Here, 'customer' is an entity and all the rows in the customers table represent the instances of the entity 'customer'. So, why not name your table using the entity it represents, 'Customer'. Since the table is storing 'multiple instances' of customers, make your table name a plural word.

    Rules: Pascal notation; end with an ‘s’
    Examples: Employees, Customers, Headlines, Groups etc.

    This is a more natural way of naming tables, when compared to approaches which name tables as tblCustomers, tbl_Orders. Further, when you look at your queries it's very obvious that a particular name refers to a table, as table names are always preceded by FROM clause of the SELECT statement.

    If your database deals with different logical functions and you want to group your tables according to the logical group they belong to, it won't hurt prefixing your table name with a two or three character prefix that can identify the group.

    2. Views
    A view is nothing but a table, for any application that is accessing it. So, the same naming convention defined above for tables, applies to views as well, but not always. Here are some exceptions:

    a) Views not always represent a single entity. A view can be a combination of two tables based on a join condition, thus, effectively representing two entities. In this case, consider combining the names of both the base tables. Here's an example:

    If there is a view combining two tables 'Customers' and 'Addresses', name the view as 'CustomersAddresses'. Same naming convention can be used with junction tables that are used to link two many-to-many related base tables. Most popular example is the 'TitleAuthor' table from 'Pubs' database of SQL Server.

    b) Views can summarize data from existing base tables in the form of reports. You can see this type of views in the 'Northwind' database that ships with SQL Server 7.0 and above. Here's the convention that database follows. (I prefer this):

    'Product Sales for 1997'
    'Summary of Sales by Quarter'
    'Summary of Sales by Year'

    However, try to stay away from spaces within object names.

    3. Stored Procedure
    Stored procedures always do some work for you, they are action oriented. So, let their name describe the work they do. So, use a verb to describe the work.

    This is how I would name a stored procedure that fetches me the customer details given the customer identification number:
    'GetCustomerDetails'. Similarly, you could name a procedure that inserts a new customer information as 'InsertCustomerInfo'. Here are some more names based on the same convention: 'WriteAuditRecord', 'ArchiveTransactions', 'AuthorizeUser' etc.

    As explained above in the case of tables, you could use a prefix, to group stored procedures also, depending upon the logical group they belong to. For example, all stored procedures that deal with 'Order processing' could be prefixed with ORD_ as shown below:

    ORD_InsertOrder
    ORD_InsertOrderDetails
    ORD_ValidateOrder

    If you are using Microsoft SQL Server, never prefix your stored procedures with 'sp_', unless you are storing the procedure in the master database. If you call a stored procedure prefixed with sp_, SQL Server always looks for this procedure in the master database. Only after checking in the master database (if not found) it searches the current database.

    I do not agree with the approach of prefixing stored procedures with prefixes like 'sproc_' just to make it obvious that the object is a stored procedure. Any database developer/DBA can identify stored procedures as the procedures are always preceded by EXEC or EXECUTE keyword

    Rules: sp_[_]<table/logical instance>
    Examples: spOrders_GetNewOrders, spProducts_UpdateProduct

    4. User Defined Functions
    In Microsoft SQL Server 2000, User Defined Functions [UDFs] are almost similar to stored procedures, except for the fact that UDFs can be used in SELECT statements. Otherwise, both stored procedures and UDFs are similar. So, the naming conventions discussed above for stored procedures, apply to UDFs as well. You could even use a prefix to logically group your UDFs. For example, you could name all your string manipulation UDFs as shown below:

    str_MakeProperCase
    str_ParseString

    5. Triggers
    Though triggers are a special kind of stored procedures, it won't make sense to follow the same naming convention as we do for stored procedures.

    While naming triggers we have to extend the stored procedure naming convention in two ways:

    a) Triggers always depend on a base table and can't exist on their own. So, it's better to link the base table's name with the trigger name

    b) Triggers are associated with one or more of the following operations: Insert, Update, Delete. So, the name of the trigger should reflect it's nature

    Rules: TR_<TableName>_
    Examples: TR_Orders_UpdateProducts
    Notes: The use of triggers is discouraged

    6. Indexes
    Just like triggers, indexes also can't exist on their own and they are dependent on the underlying base tables. So, again it makes sense to include the 'name of the table' and 'column on which it's built' in the index name. Further, indexes can be of two types, clustered and nonclustered. These two types of indexes could be either unique or non-unique. So, the naming convention should take care of the index types too.
    Rules: IX_<TableName>_
    Examples: IX_Products_ProductID

    7. Columns
    Columns are attributes of an entity, that is, columns describe the properties of an entity. So, let the column names be meaningful and natural.

    Here's a simplest way of naming the columns of the Customers table:

    CustomerID
    CustomerFirstName
    CustomerAddress

    As shown above, it'll be a good idea to prefix the column names with the entity that they are representing.

    Here's another idea. Decide on a standard two to four character code for each table in your database and make sure it's unique in the database. For example 'Cust' for Customers table, 'Ord' for Orders tables, 'OrdD' for OrderDetails table, 'Adt' for Audit tables etc. Use this table code to prefix all the column names in that table. Advantage of this convention is that in multi-table queries involving complex joins, you don't have to worry about ambiguous column names, and don't have to use table aliases to prefix the columns. It also makes your queries more readable.

    If you have to name the columns in a junction/mapping table, concatenate the table codes of mapped tables, or come up with a new code for that combination of tables.

    So, here's how the CustomerID column would appear in Customers table:

    Cust_CustomerID

    The same CustomerID column appears in the Orders table too, but in Orders table, here's how it's named:

    Ord_CustomerID

    Some naming conventions even go to the extent of prefixing the column name with it's data type. But I don't like this approach, as I feel, the DBA or the developer dealing with these columns should be familiar with the data types these columns belong to.

    If a column references another table’s column, name it <table name>ID
    Example: The Customers table has an ID column
    The Orders table should have a CustomerID column

    8. Uer Defined DataTypes
    User defined data types are just a wrapper around the base types provided by the database management system. They are used to maintain consistency of data types across different tables for the same attribute. For example, if the CustomerID column appears half a dozen tables, you must use the same data type for all the occurrences of the CustomerID column. This is where user defined data types come in handy. Just create a user defined data type for CustomerID and use it as the data type for all the occurrences of CustomerID column.

    So, the simplest way of naming these user defined data types would be:
    Column_Name + '_type'.
    So, I would name the CustoerID type as:

    CustomerID_type

    9. Primary Keys
    Primary key is the column(s) that can uniquely identify each row in a table. So, just use the column name prefixed with 'pk_' + 'Table name' for naming primary keys.

    Rules: PK_<TableName>
    Examples: PK_Products

    10. Foreign Keys
    Foreign key are used to represent the relationships between tables which are related. So, a foreign key can be considered as a link between the 'column of a referencing table' and the 'primary key column of the referenced table'.

    I prefer the following naming convention for foreign keys:

    fk_referencing table + referencing column_referenced table + referenced column.

    Based on the above convention, I would name the foreign key which references the CustomerID column of the Customers table from the Order's tables CustomerID column as:

    fk_OrdersCustomerID_CustomersCustomerID

    Foreign key can be composite too, in that case, consider concatenating the column names of referencing and referenced tables while naming the foreign key. This might make the name of the foreign key lengthy, but you shouldn't be worried about it, as you will never reference this name from your code, except while creating/dropping these constraints.

    Rules: FK_<TableName1>_<TableName2>
    Example: FK_Products_Orderss

    11. Defaults and Check Constrains
    Use the column name to which these defaults/check constraints are bound to and prefix it with 'def' and 'chk' prefixes respectively for Default and Check constraints.
    I would name the default constraint for OrderDate Column as def_OrderDate and the check constraint for OrderDate column as chk_OrderDate.

    Rules: DF_<TableName>_
    Example: DF_Products_Quantity

    12. Variable
    For variables that store the contents of columns, you could use the same naming convention that we used for Column names.

    13. General Rules
    a)Do not use spaces in the name of database objects.
    b)Do not use SQL keywords as the name of database objects. In cases where this is necessary, surround the object name with brackets, such as [Year]
    c)Do not prefix stored procedures with ‘sp_’ Prefix table names with the owner name.

    13. Strucure
    a) Each table must have a primary key
    o In most cases it should be an IDENTITY column named ID
    b) Normalize data to third normal form
    o Do not compromise on performance to reach third normal form. Sometimes, a little denormalization results in better performance.
    c) Do not use TEXT as a data type; use the maximum allowed characters of VARCHAR instead
    d) In VARCHAR data columns, do not default to NULL; use an empty string instead
    e) Columns with default values should not allow NULLs
    f) As much as possible, create stored procedures on the same database as the main tables they will be accessing.

    14. Formatting
    · Use upper case for all SQL keywords
    o SELECT, INSERT, UPDATE, WHERE, AND, OR, LIKE, etc.
    · Indent code to improve readability
    · Comment code blocks that are not easily understandable
    o Use single-line comment markers(--)
    o Reserve multi-line comments (/*.. ..*/) for blocking out sections of code
    · Use single quote characters to delimit strings.
    o Nest single quotes to express a single quote or apostrophe within a string
     For example, SET @sExample = 'SQL''s Authority'
    · Use parentheses to increase readability
    o WHERE (color=’red’ AND (size = 1 OR size = 2))
    · Use BEGIN..END blocks only when multiple statements are present within a conditional code segment.
    · Use one blank line to separate code sections.
    · Use spaces so that expressions read like sentences.
    o fillfactor = 25, not fillfactor=25
    · Format JOIN operations using indents
    o Also, use ANSI Joins instead of old style joins4
    · Place SET statements before any executing code in the procedure.


    15. Coding
    · Optimize queries using the tools provided by SQL Server5
    · Do not use SELECT *
    · Return multiple result sets from one stored procedure to avoid trips from the application server to SQL server
    · Avoid unnecessary use of temporary tables
    o Use 'Derived tables' or CTE (Common Table Expressions) wherever possible, as they
    perform better.
    · Avoid using <> as a comparison operator
    o Use ID IN(1,3,4,5) instead of ID <> 2
    · Use SET NOCOUNT ON at the beginning of stored procedures7
    · Do not use cursors or application loops to do inserts8
    o Instead, use INSERT INTO
    · Fully qualify tables and column names in JOINs
    · Fully qualify all stored procedure and table references in stored procedures.
    · Do not define default values for parameters.
    o If a default is needed, the front end will supply the value.
    · Do not use the RECOMPILE option for stored procedures.
    · Place all DECLARE statements before any other code in the procedure.
    · Do not use column numbers in the ORDER BY clause.
    · Do not use GOTO.
    · Check the global variable @@ERROR immediately after executing a data manipulation statement (like INSERT/UPDATE/DELETE), so that you can rollback the transaction if an error occurs
    o Or use TRY/CATCH
    · Do basic validations in the front-end itself during data entry
    · Off-load tasks, like string manipulations, concatenations, row numbering, case conversions, type conversions etc., to the front-end applications if these operations are going to consume more CPU cycles on the database server
    · Always use a column list in your INSERT statements.
    o This helps avoid problems when the table structure changes (like adding or dropping a column).
    · Minimize the use of NULLs, as they often confuse front-end applications, unless the applications are coded intelligently to eliminate NULLs or convert the NULLs into some other form.
    o Any expression that deals with NULL results in a NULL output.
    o The ISNULL and COALESCE functions are helpful in dealing with NULL values.
    · Do not use the identitycol or rowguidcol.
    · Avoid the use of cross joins, if possible.
    · When executing an UPDATE or DELETE statement, use the primary key in the WHERE condition, if possible. This reduces error possibilities.
    · Avoid using TEXT or NTEXT datatypes for storing large textual data.9
    o Use the maximum allowed characters of VARCHAR instead
    · Avoid dynamic SQL statements as much as possible.10
    · Access tables in the same order in your stored procedures and triggers consistently.
    · Do not call functions repeatedly within your stored procedures, triggers, functions and batches.
    · Default constraints must be defined at the column level.
    · Avoid wild-card characters at the beginning of a word while searching using the LIKE keyword, as these results in an index scan, which defeats the purpose of an index.
    · Define all constraints, other than defaults, at the table level.
    · When a result set is not needed, use syntax that does not return a result set.
    · Avoid rules, database level defaults that must be bound or user-defined data types. While these are legitimate database constructs, opt for constraints and column defaults to hold the database consistent for development and conversion coding.
    · Constraints that apply to more than one column must be defined at the table level.
    · Use the CHAR data type for a column only when the column is non-nullable.14
    · Do not use white space in identifiers.
    · The RETURN statement is meant for returning the execution status only, but not data.

    What is the result when comparing two nulls in SQL?

    The answer is quite interesting with my stuff. Let me clear it in more writting:

    1. When we compare two nulls then the result always 'false'. The main reason is the null is not a value its neither an empty nor a empty space, so the actual result is null which places as null.
    2. When we compare a null with another which has some value like some int value then the result is false. The actual result is false and not null.

    Consider the following examples:

    --null = null is null which is false
    Declare @intNull1 int
    Set @intNull1 =null
    Declare @intNull2 int
    Set @intNull2=null
    If @intNull1=@intNull2
    Print 'null = null is true'
    Else
    Print 'null = null is false'

    --Now assign some value
    Set @intNull1 = 1
    If @intNull1=@intNull2
    Print 'null = int value is true'
    Else
    Print 'null = int value is false'

    Saturday, July 12, 2008

    What is difference between Union and Union All?

    I have a got a comment and a question from an anonymous for my post How to Insert multiple rows?. I must say thanks to you all to encourage my stuffs.

    Union vs. Union All
    In simple we can say that
    1. union is used to select distinct values from two tables,where as union all is used to select all values including duplicates from the tables.
    2. The UNION operator allows you to combine the results of two or more SELECT statements into a single result set. The result sets combined using UNION must all have the same structure. They must have the same number of columns, and the corresponding result set columns must have compatible data types.By default, the UNION operator removes duplicate rows from the result set. If you use UNION ALL, all rows are included in the results and duplicates are not removed.

    Lets consider following examples:

    1. UNION
    Select * from dbo.checkDuplicate
    Union --it will leave the duplicate rows
    Select * from dbo.checkDuplicate

    The above querry will retrieve all rows from checkduplicate table except duplicate entries.

    2. UNION ALL
    Select * from dbo.checkDuplicate
    Union --it will select all rows including duplicates
    Select * from dbo.checkDuplicate

    The above querry will select all rows from checkduplicate table including duplicate entries.

    Note: One can count the number of rows using following statement:

    SELECT rows FROM sysindexes WHERE id = OBJECT_ID('checkDuplicate') AND indid < 2

    What are New Features in Vs 2008 and .Net Framework 3.5?

    Vs 2008 and .Net Framework 3.5 [code name is Orcas] has many new features and improvements prior versions.

    The following are some of the features:

    1. VS 2008 Multi-Targeting Support
    VS 2008 support multiple versions .net framework i.e 2.0, 3.0, 3.5. Where VS 2002 supports only .Net 1.0, VS 2003 supports 1.1, and VS 2005 supports 2.0 . That means you can open an existing project or create a new one with VS 2008, you can pick which version of the .NET Framework to work with - and the IDE will update its compilers and feature-set to match this. And that features, controls, projects, item-templates, and assembly references that not work with that version of the framework will be hidden. Unfotunately it does not support .net1.0 and .net 1.1. but we can run VS 2008 side by side with VS 2005 , VS 2003 and VS 2002 on the same machine.


    2. JavaScript Intellisense
    I really like this feature. When ever I am writing java script in previous versions , i think about intellisense of java script. Now i got this feature in VS 2008. Now i can enjoy the coding of javascript. This makes developer easy write of coding java script. This built in support of javascript intellisense avoids java script errors and makes developing the code faster.


    3. JavaScript Debugging

    Now, you can stop putting alerts in your code unnecessarly to check the values of the variable or flow of control. Instead of alert boxes , now you can keep break points to look the values of the variables at client script within your server-side .aspx and .master source files. Its like putting break points in server script.
    Any JavaScript breakpoints you set will be saved auto matically in VS 2008 when you close the project/solution. When you open up the project again, the previous locations you set the breakpoints on will still have them enabled.

    4. Support of AJAX

    One of the main features of VS 2008 is ASP.NET AJAX Control Extenders. These controls are derived from the System.Web.UI.ExtenderControl base class, and which can be used to add additional functionality [usually AJAX or JavaScript support] to existing controls already declared on a page. They enable developers to nicely encapsulate UI behavior, and make it really easy to add richer functionality to an application.


    5. Split of Design view and Source view Editing

    In VS 2005 and previous versions , we have design view , source view .Besides this features it supports a new "split-view" mode when working on pages. This allows you to see both the HTML source and the Design View at the same-time, and easily have any changes you make in one view be updated in the other. We can set the split view as horizontal as well as vertical to use maximum screen.


    6. CSS Manager

    VS 2008 supports a new tool window inside the IDE called "Manage Styles". This shows all of the CSS stylesheets, and their corresponding rules, for the page you are currently editing. It can be used both when you are in design-view, as well as when you are in source view on a page.


    7. Nested Master Pages

    The great feature in asp.net 2.0 is Master page. By including master page we can avoid redundant code like header , footer and menus which contains in all pages. Now in VS 2008,we can create nested master pages.


    8. List View Control

    One of the new controls in ASP.NET 3.5 is the control. The ListView control supports the data editing, insertion, deleting, paging and sorting semantics of higher-level controls like the GridView. But - unlike the GridView - it provides you with complete control over the html markup generated.

    How to Insert Multiple Records Using Single Insert - SQL SERVER

    This is very interesting question, I have received from one of my colleague - Neeraj Tomar. How can I insert multiple values in table using only one insert? .

    To insert values in a table, there are many ways like :

    Use HrnPayroll --Change database name with yours

    --Here you can try with any table available under above chosen database

    INSERT INTO dbo.employees VALUES('0001', 'Gaurav','Arora',38)
    INSERT INTO dbo.employees VALUES('0005', 'Shuby','Arora',28)
    INSERT INTO dbo.employees VALUES('0007', 'Shweta','Arora',29)

    Go

    With the help of above lines, one can achieve the task but think for numerous insert statements to do the same one should repeat the Insert multiple times.

    --One can achieve the multiple insertion with the following statement:
    Insert Into dbo.employees (ID, FirstName, LastName, Age)
    Select '0008','Arun', 'Kumar',39
    Union All
    Select '0009','Vibha', 'Arora',19
    Union All
    Select '0018','Neeraj', 'Tomar',23
    Union All
    Select '0118','Laxmi', 'Farswan',24

    Go

    With the help of above line one can insert multiple data using single Insert statement. The above both statements are working fine when using SQLSerevr 2000/2005.

    The SQLServer2008 provides more stuff to add multiple values using single Insert statement.


    --The following querry will happen only with SQLServer2008:
    Insert Into dbo.employees (ID, FirstName, LastName, Age)
    Values('1018','Neeraj', 'Shivasam',18)
    Values('1118','Neeraj', 'Huda',38)
    Values('1028','Gaurav', 'Malhotra',30)
    Values('1128','Abhishek', 'Prasad',30)
    Values('2128','Pankaj', 'Nautiyal',36)
    Values('3128','Ritesh', 'Kashyap',33)