Tuesday, March 23, 2010

Struct


  1. Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
     
    //public int UserId = 10; //Error

  2. A struct may not declare a default constructor (a constructor without parameters) or a destructor. Any private or otherwise inaccessible members can be initialized only in a constructor.
  3. Copy a struct to struct.
    If you copy a struct, C# creates a new copy of the object and assigns the copy of the object to a separate struct instance.
    Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary.
     
    Student s1 = new Student();
    Student s2;
    s1 = s2;
    Response.Write(s1.PUserId);
    Response.Write(s2.PUserId);

    Here all the values of s1 will be copied to s2.
  4. Structs are value types and classes are reference types.
  5. Unlike classes, structs can be instantiated without using a new operator.
     
    Student s1;
    s1.Address = "Savadipalayam";

  6. Initialize the fields through properties. Use of unassigned local variable 's1'.
     
    Student s1;
    Response.Write(s1.PUserId)

    In fact, when instantiating a struct without the new keyword, we must first initialize its fields explicitly.
     
    Student s1;
    s1.PUserId = 10;
    Response.Write(s1.PUserId)

  7. Structs can declare constructors that have parameters. But all the field variables should be fully initialzed.
     
    public Student(int UserId, int ZipCode, double Salary, string Address)
    {
    this.UserId = UserId;
    this.ZipCode = ZipCode;
    this.Salary = Salary;
    //this.Address = Address;
    }

    This will produce an error Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller". Since Address is not initialized.
  8. A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
  9. A struct can implement interfaces, and it does that exactly as classes do.
  10. Cannot convert null to 'StructTest.Student'

    Student s2 = null;

    DateTime is struct. We can't assign null to DateTime.
    Cannot convert null to 'System.DateTime' because it is a non-nullable value type.
    eg.

    DateTime dt = null;

  11. A struct can be used as a nullable type and can be assigned a null value.
    Working with Nullable Types in struct.
  12. If a field is not initialized whether it is a primitive data type it produce the error "Use of possibly unassigned field 'i'" when we didn’t create instance for the struct.

    Student1 s3;
    Response.Write(s3.i);


  13. When we create an instance for the struct but we don’t have any constructor to assing value, it will asign the default value for premitive datatype and for others it will assing null(null for string).


    public struct Student1
    {
    public int i;
    public string j;
    }

    Student1 s3 = new Student1();
    Response.Write(s3.i); //O/P = 0
    Response.Write(s3.j); //O/P = null


  14. struct can also have copy constructor but have to be fully initialzed.

    public Student(Student stud)
    {
    this.UserId = stud.UserId;
    this.ZipCode = stud.ZipCode;
    this.Salary = stud.Salary;

    //Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller
    //this.Address = stud.Address;

    this.Address = stud.Address;
    }

  15. Struct can contain methods. It may be static, and a static method can call only another static methods.

    public void sub()
    {

    }

    public static string multiply()
    {
    return Send();
    }

    public static string Send()
    {
    //An object reference is required for the non-static field, method, or property 'StructTest.Student.Address'
    //Address = "Mottur Road";
    //return Address;

    Street = "Mottur Road";
    return Street;
    }

  16. //The allowed modifiers are new, static, virtual, override, and a valid combination of the four access modifiers (public, internal and private).

    // Override the ToString method so the value appears in text
    public override string ToString()
    {
    return String.Format("({0},{1})", Street, Address);
    }

  17. Support access modifiers, constructors, indexers, methods, fields, nested types, operators, and properties.

    public int PUserId
    {
    get { return UserId; }
    set { UserId = value; }
    }

  18. Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal.. If we declare a struct inside a namespace with any of the access specifier as private, protected, or protected internal, we will get this error.
    So it is always public when we declare a struct inside a namespace.
  19. Abstract and sealed modifiers are not permitted in a struct declaration since it is always implicitly sealed.
    Since it is implicitly sealed, struct members may not be declared protected.
    So we can't able to inherit another struct.
    Since it is not abstract, struct can't be a base to a class or another structure.



struct Student : IOne, ITwo
{
int UserId;
//public int UserId = 10; //Within a struct declaration, fields cannot be initialized unless they are declared as const or static.

public static string Street = "Savadipalayam";

int ZipCode;
double Salary;
public string Address;

//Structs cannot contain explicit parameterless constructors(Default constructor)
/* public Student()
{
this.UserId = 10;
this.ZipCode = 637101;
this.Salary = 2000;
this.Address = "Idappadi";
}
*/

// all the members of the struct has to be initialized in this way
public Student(int UserId, int ZipCode, double Salary, string Address)
{
this.UserId = UserId;
this.ZipCode = ZipCode;
this.Salary = Salary;
this.Address = Address;
}

// struct can also have copy constructor but have to be fully initialzed
public Student(Student stud)
{
this.UserId = stud.UserId;
this.ZipCode = stud.ZipCode;
this.Salary = stud.Salary;

//Field 'StructTest.Student.Address' must be fully assigned before control is returned to the caller
//this.Address = stud.Address;

this.Address = stud.Address;
}

public int PUserId
{
get { return UserId; }
set { UserId = value; }
}

//new protected member declared in struct
//protected void add()
//{
//}

//Struct can contain methods. It may be static, and can call only another static methods.
public void sub()
{

}

public static string multiply()
{
return Send();
}

public static string Send()
{
//An object reference is required for the non-static field, method, or property 'StructTest.Student.Address'
//Address = "Mottur Road";
//return Address;

Street = "Mottur Road";
return Street;
}

//The modifier 'abstract' is not valid for this item
//public abstract void Return() { }

#region ITwo Members

void ITwo.add()
{
throw new System.NotImplementedException();
}

public void sum()
{
throw new System.NotImplementedException();
}

#endregion

#region IOne Members

void IOne.add()
{
throw new System.NotImplementedException();
}

void IOne.sum()
{
throw new System.NotImplementedException();
}

#endregion
}

//Nested Structures


public struct outer
{
public int i;
public struct inner
{
public int j;
}
}


How to call?.


outer.inner inn = new outer.inner();
inn.j = 10;


References
C# School
vijaymukhi
C# Online.net
codeproject
csharp-station

Can't access App_Code class in Code Behind file

I had created a struct in file in the App_Code. But I can't able to access the namespace.
 
namespace StructTest
{
public struct Student
{
int id;
int zipcode;
double salary;
}
}

Solution
Right click on the file and select properties then change the Build Action to Compile.

Friday, March 19, 2010

Generate Select and Update Procedure

Generates Select Procedure
Use the this link create-parameters to create paramaters for this.

declare @ProcName varchar(250)
declare @SchemaName varchar(250)
DECLARE @NewLineChar AS CHAR(2)
DECLARE @HorizontalTabChar AS CHAR(1)
DECLARE @VerticalTabChar AS CHAR(1)
DECLARE @ColNames AS varchar(8000)
DECLARE @TableName AS varchar(200)

SET @ProcName = 'Getcompany'
SET @SchemaName = 'dbo'
SET @NewLineChar =  CHAR(13) + CHAR(10)
SET @HorizontalTabChar = CHAR(9)
set @VerticalTabChar = CHAR(11)
SET @ColNames = REPLICATE(@HorizontalTabChar, 3)
SET @TableName = 'company'

SELECT
@ColNames = @ColNames + syscolumns.name + ',' + @NewLineChar + REPLICATE(@HorizontalTabChar, 3)
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
where sysobjects.ID = OBJECT_ID(@TableName)

SET @ColNames = Left(@ColNames, Len(@ColNames)-6)

PRINT 'if exists (select * from dbo.sysobjects where id = object_id(N''[' +@SchemaName+ '].[' + @ProcName +']'') and OBJECTPROPERTY(id, N''IsProcedure'') = 1)'
+ @NewLineChar + 'BEGIN'
+ @NewLineChar + @HorizontalTabChar + 'DROP PROCEDURE [' +@SchemaName+ '].[' + @ProcName +'] '
+ @NewLineChar + 'END'
+ @NewLineChar + 'GO'
+ @NewLineChar
+ @NewLineChar + 'CREATE PROCEDURE [' +@SchemaName+ '].[' + @ProcName +']'
+ @NewLineChar + 'AS'
+ @NewLineChar + @HorizontalTabChar + ' BEGIN'
+ @NewLineChar + REPLICATE(@HorizontalTabChar, 2) + ' SELECT'
+ @NewLineChar + @ColNames
+ @NewLineChar + REPLICATE(@HorizontalTabChar, 2)+  'FROM ' + @TableName
+ @NewLineChar + @HorizontalTabChar + ' END'

Generates Update Procedure
To pass parameters to the Update Procedure use the link to generate Parameters.
Generate Parameters
DECLARE @ProcName             VARCHAR(250)
DECLARE @SchemaName           VARCHAR(250)
DECLARE @NewLineChar AS       CHAR(2)
DECLARE @HorizontalTabChar AS CHAR(1)
DECLARE @VerticalTabChar AS   CHAR(1)
DECLARE @ColNames AS          VARCHAR(8000)
DECLARE @TableName AS         VARCHAR(200)

SET @ProcName          = 'zxcvbnm'
SET @SchemaName        = 'dbo'
SET @NewLineChar       = CHAR(13) + CHAR(10)
SET @HorizontalTabChar = CHAR(9)
SET @VerticalTabChar   = CHAR(11)
SET @ColNames          = REPLICATE(@HorizontalTabChar, 3)
SET @TableName   = 'company'

SELECT @ColNames       = @ColNames + syscolumns.name + ' = @' + syscolumns.name + ',' + @NewLineChar + REPLICATE(@HorizontalTabChar, 3)
FROM   sysobjects
JOIN syscolumns
ON     sysobjects.id = syscolumns.id
WHERE  sysobjects.ID        = OBJECT_ID(@TableName)

SET @ColNames = LEFT(@ColNames, LEN(@ColNames)-6)

PRINT 'if exists (select * from dbo.sysobjects where id = object_id(N''[' +@SchemaName+ '].[' + @ProcName +']'') and OBJECTPROPERTY(id, N''IsProcedure'') = 1)'
+ @NewLineChar + 'BEGIN'
+ @NewLineChar + @HorizontalTabChar + 'DROP PROCEDURE [' +@SchemaName+ '].[' + @ProcName +'] '
+ @NewLineChar + 'END'
+ @NewLineChar + 'GO'
+ @NewLineChar
+ @NewLineChar + 'CREATE PROCEDURE [' +@SchemaName+ '].[' + @ProcName +']'
+ @NewLineChar + 'AS'
+ @NewLineChar + @HorizontalTabChar + ' BEGIN'
+ @NewLineChar + REPLICATE(@HorizontalTabChar, 2) + ' UPDATE ' + @TableName
+ @NewLineChar + REPLICATE(@HorizontalTabChar, 3) + 'SET'
+ @NewLineChar + @ColNames
+ @NewLineChar + @HorizontalTabChar + ' END'

Thursday, March 18, 2010

Where column alows null

DECLARE @Test TABLE (ID INT  IDENTITY (1,1),  
Name VARCHAR(250) NOT NULL, Street VARCHAR(250) NULL)

INSERT INTO @Test
SELECT 'Ashok', NULL UNION ALL
SELECT 'Guru', NULL UNION ALL
SELECT 'Babu', 'Idappadi' UNION ALL
SELECT 'Gopi', NULL UNION ALL
SELECT 'Balaji', NULL UNION ALL
SELECT 'Senthil', NULL UNION ALL
SELECT 'Saravanan', NULL UNION ALL
SELECT 'Suresh', NULL

I want to get the records whose street not equal to 'Idappadi'

The query given below returns nothing.
SELECT Name, Street FROM @Test
WHERE Street != 'Idappadi'

Then I modified as below which returns correct result.
SELECT Name, Street FROM @Test
WHERE ISNULL(Street, '') != 'Idappadi'

Saturday, March 13, 2010

Get the Last charindex of a char in a string

DECLARE @TempTable TABLE (NewPK INT identity(1,1), Customer VARCHAR(100) NOT NULL)
DECLARE @SearchChars VARCHAR(10)

SET @SearchChars = '-'

INSERT
INTO  @TempTable (Customer)
SELECT 'BabuKumarasamy-100313-0001' UNION ALL
SELECT 'BabuKumarasamy-1003313-00110' UNION ALL
SELECT 'KrishnaMoorthi-Konganapuram-0020' UNION ALL
SELECT 'Saravanan-100313-0006' UNION ALL
SELECT 'Sankar-100313-0001'

SELECT (LEN(Customer) - CHARINDEX(@SearchChars, reverse(Customer))) AS LastIndex,
       SUBSTRING (Customer, 0, (LEN(Customer) - CHARINDEX(@SearchChars, reverse(Customer))) + 1) AS StringBeforeTheIndex,
       SUBSTRING (Customer,(LEN(Customer)- CHARINDEX(@SearchChars, reverse(Customer))) + 2, LEN(Customer) - (LEN(Customer) - CHARINDEX(@SearchChars, reverse(Customer)))) AS StringAfterTheIndex
FROM   @TempTable
WHERE  Customer LIKE 'BabuKumarasamy%'

Monday, March 1, 2010

null-coalescing operator

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

  
string partner = Request.QueryString["GoogleId"] ??

Request.QueryString["PartnerId"] ??

Request.QueryString["UserKey"] ??

string.Empty;