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.