Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.
Showing posts with label Article. Show all posts
Showing posts with label Article. Show all posts

06 September 2012

Rollback Transaction for table variable in sql server


Table variable is special kind of data type which will store result set and the data will returned for processing. Table variable can be used in store procedures and functions.
Table variables have limited scope and data will be stored in temporary storage so they are not affected with transaction roll backs.
In the below script we will see practically how rollback behaves for table variable.
DECLARE @student AS Table (id INT,Name VARCHAR(50) NOT NULL)
 
BEGIN TRY
    BEGIN TRANSACTION       
    INSERT INTO @student Values(1,'Ram')
    INSERT INTO @student Values(2,'Rahim')
    INSERT INTO @student Values(3,NULL)
    INSERT INTO @student Values(4,'Rohan')
    COMMIT TRANSACTION
    SELECT *,Name FROM @student -- will not return data due to error at id=3
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
    SELECT *,id FROM @student
END CATCH
Output:
 

 In summary, we can say that Rollback Transaction does not work for table variables.

21 August 2012

Accessing and Changing TD text at runtime


In this article we will see how to access and change the TD text at runtime.
The TD tag belongs to table (HTML element) which will not be accessible in code behind page. So we will mark the TD tag with runat=”server” and provide an ID to access in code page. To set/get the td text we can use Inner Text property of td element.
 
In the below example we will see how to read/write text of td element.
 
Desing Page(.aspx)
<form id="form1" runat="server">
    <div>
    <h1>
        <table>
            <tr>
                <td runat="server" id="tdAccess">
                Design time td text
                </td>
            </tr>
        </table></h1>
        <asp:Label ID="lblTDText" runat="server"></asp:Label><br />
        <asp:Button ID="btnChangeTD" runat="server" Text="Change TD Text"
            onclick="btnChangeTD_Click" />
    </div>
    </form>
Code behind(.cs)
protected void Page_Load(object sender, EventArgs e)
    {
        lblTDText.Text = tdAccess.InnerText; // get td element text
    }
    protected void btnChangeTD_Click(object sender, EventArgs e)
    {
        tdAccess.InnerText = "Runtime td text from button click"; //// set td element text
    }
Explanation: we have TD tag inside table element which is marked with runat=”server” and id as tdAccess. On page load we are accessing td text (design time text) and assigning it to label control and from the button click, we are changing the td text at runtime.


11 August 2012

Can we access C#.NET same method names with different case sensitive in vb.net project

In this Article we will see, can we access C#.NET same method names with different case sensitive in vb.net project.

If we define same method names like Add and add (differs from case sensitive),in C#.NET it will taken as two different methods but where as in VB.NET we will get compile time error as "Add/add has multiple definitions with identical signatures".

In the below example we will create C# class library project which has Add and add methods and one subtract method.

C# Class Library Project
namespace CalcLibrary
{
    public class Calc
    {
        public int Add(int a, int b)
        {
            return a + b + 10;
        }
        public int add(int a, int b)
        {
            return a + b + 20;
        }
        public int subtract(int a, int b)
        {
            return a - b;
        }
    }

}



Build the the project, we will get CalcLibrary.dll in bin folder.

 Now create a VB.NET console application and add reference CalcLibrary.dll to Console Application.In the Below example we will see what happens when we try to access add/Add method from C# Class library project.

VB.NET Console Application
Public Class CalcClient
    Public Shared Sub Main()
        Dim obj As New Calc
        Dim resultPlus As Integer = obj.add(1, 2) 'Compile Error as 'Add' is ambiguous because multiple kinds of members with this name exist in class 'CalcLibrary.Calc'
        Dim resultMinus As Integer = obj.subtract(20, 10)
    End Sub

End Class



From the intellisense,if you can observe you will not get add/Add methods but you can get subtract method in intellisense because it has single method defination.So when we try to  explicitly call add/Add method we will get compile time error as "'Add' is ambiguous because multiple kinds of members with this name exist in class 'CalcLibrary.Calc'"


07 August 2012

Page.MetaKeywords and Page.MetaDescription feature in ASP.NET 4.0 with Example


The two new properties(Page.MetaDescription and  Page.MetaKeywords) are added to page class in ASP.NET4.0. In this article we will discuss about how to set/get page meta keywords/description data and also we will see in how many ways we can provide the data to meta keywords/description of page and priority of rendering to the client if we specify more than once in the webpage.


Advantage:Meta keywords, description tags  were a great little tools used by search engines to determine the rank of sites. So it’s always better to provide Meta tags information on the page.
  
Page.MetaDescription  – Gets or sets the content of the “discription” Meta element.
Page.MetaKeywords    - Gets or sets the content of the “keywords” Meta element.

Using Page.MetaDescription   and Page.MetaKeywords we can provide the input data from code behind file.The data could be from database or file system.

We can set  meta description/keyword properties in 3 ways
  1. Code behind (Using Page.MetaDescription   and Page.MetaKeywords)
  2. Page directive( using MetaDescription   and MetaKeywords attributes)
  3. Meta tag of head tag.( using meta names)

In the below example we will see how to use above methods in a webpage.

Designer Page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page_MetaKeywords _MetaDescription.aspx.cs"
    Inherits="ASPNET.Page_MetaKeywords__MetaDescription" MetaDescription="MetaDescription from Page directive"
    MetaKeywords="MetaKeywords, from, Page, directive" %>

<html>
<head runat='server'>   
    <meta name="keywords" content="keywords,from,head,meta,tag" />
    <meta name="description" content="description of page from head meta tag" />
</head>
<body>
    <form runat="server">
    <div>
        <asp:Button ID="btnGetMetaKeywordsDesc" runat="server"
            Text="Retrieve Page keywords and description"
            onclick="btnGetMetaKeywordsDesc_Click" />
    </div>
    </form>
</body>
</html>
CodeBehind
public partial class Page_MetaKeywords__MetaDescription : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //setting Meta tags data
            Page.MetaKeywords = "MetaKeywords, from, Code, behind";
            Page.MetaDescription = "MetaDescription from Code behind";
        }
        protected void btnGetMetaKeywordsDesc_Click(object sender, EventArgs e)
        {
            //reading Meta tags data
            Response.Write(Page.MetaDescription);
            Response.Write(Page.MetaKeywords);
        }
    }


If we specify the meta data information more than once in a web page, in that case the priority of rendering the meta description/keywords data is
  1. Code behind
  2. Page directive
  3. Meta tags in head tag
Note: If we are using Page.MetaDescription and Page.MetaKeywords we must set runat=”server” for head  tag.otherwise we will get error as
"Using the Description property of Page requires a header control on the page. (e.g. <head runat="server" />)"

07 July 2012

Method overloading in C#

In this article we will discuss about method overloading concept with examples.

Definition: Method overloading is a concept of using same method name with differing in the number type and order of arguments.

 Example: if we want to add two integers or two float values we can write methods like
Before method overloading
After method overloading
public int AddIntValues(int a1, int a2)
            {
                return a1 + a2;
            }
public float AddFloatValues(float a1, float a2)
            {
                return a1 + a2;
            }
public int Add(int a1, int a2)
            {
                return a1 + a2;
            }
            public float Add(float a1, float a2)
            {
                return a1 + a2;
            }

The compiler will identify which method to execute based on number of arguments and their data types during compilation. 

Below is the example which shows method overloading.

Example:
class Base
    {
        public int Add(int a1, int a2)
        {
            return a1 + a2;
        }
        public float Add(int a1, float a2)
        {
            return a1 + a2;
        }
    }
    class Derived : Base
    {
        public int Add(int a1, int a2, int a3)
        {
            return a1 + a2 + a3;
        }
        public float Add(float a1, int a2)
        {
            return a1 + a2;
        }
    }
 
    class MethodOverloadingUsage
    {
        static void Main()
        {
            Derived obj = new Derived();
            Console.WriteLine(obj.Add(10, 20));
            Console.WriteLine(obj.Add(10, 12.5f));
            Console.WriteLine(obj.Add(10, 20, 30));
            Console.WriteLine(obj.Add(13.5f,10));
            Console.Read();
        }
    }
Output:
30
22.5
60
23.5

When to use: If a method is performing similar action but using different parameters then we can use method overloading.

Data points:
  • Return type of method will not considered for overloading usage
  • Same method name provides different forms so it is example of polymorphism.
  • In method overloading the method name should be same. Parameters (data type and order) and return type can be different for each method which is overloaded.

06 July 2012

Vairables in c# - Different type of variables


In this article we will discuss about variables in c#- variable definition, naming a variable, declaration and initialization of variable, different types of variables with example and finally about default values for data types.

“Variable” is simply storage location of data. Variable will take different values at different time during the execution of program.

Naming a variable:
Variable name can consists of alphabets, digits and underscore. 

Following cases should be taken care of while creating a variable.
  • Should not be a reserved keyword. ( like keyword base). If we try give name with keyword then error as "Identifier is expected. 'base' is a keyword".
  • White space is not allowed between the characters.
  •  Length of name is up to 511 characters.
  • Upper case and lower case are distinct. E.g.: Variable count is different from COUNT.
  • Must not begin with digit.
Some of variable names: count, total_count, incValue,var1,Test_123.

Declaration and Initialization of variable:
[access modifier] [data type] [name] = [value];
Every variable has a type (data types) that determines what value can be stored in the variable.
Examples: 
public string name = "DotNet Mirror";
int val1, val2 = 8;  //declaration and initialization of multiple variable at a time

Different type of variables:
  • Instance variable
  • Static variable
  • Value parameters
  • Reference parameters
  • Output parameters
  • Local variables
  • Array elements
Program
Variable identification
   public class TestClass
    {
        int i;
        static int j;
        public void Sample(string k, ref int l, out int m, int[] n)
        {
            m = 20;
            int var;
        }
    }
i - instance variable
j - static variable
k - value parameter
l - reference parameter
m - output parameter
n - array element
var - local variable
 

Note:if you are using out parameter in a method that should be assigned before control leaves the current method.

Variable default values for data types:
When we declare a variable and did not assign any value then it will takes below default values.
Data type
Default value
All integer types
0
bool
True
String
Null
enum
0
decimal
0.0 m
double
0.0d
float
0.0 f
byte
0
All reference types
null