Friday, December 5, 2008

Arrays in C# : Value type or Ref type

Array Class is the abstract class provides methods for manipulation of array....
int [] intArray;
intArray = new int[5]

string [] names;
names = new string[10];

now from above which one is value type and which one is refrence type (Int is value type and String is refrence type)
 
ok the topic is interesting lets's play with it
 
 
as we all know the difference in readonly and const keyword in C#
readonly can be applied with only ref type and const can be only with value type except string
 
and if you try to make the above said array to const it will show error while it will work fine with readonly
try using this line of code in your program
 
you may also try this see the error
public const int[] intArray = new int[5];

now lets do another test on these arrays
declare one readonly array and try to change it svalue

like readonly int [] intarray = {1,2,3}

intArray[1] = 4

it will execute fine

because array is ref type so ref remains same when readonly but value can be changed
 
 
so we can finally conclude that all array are refernce type whether it contains value type or reference type

Thursday, October 16, 2008

Introduction to Nullable types in C# 2.0

Content:
• Introduction
• System requirement
• Nullable type’s use
• Creating Nullable types
• The ?? Operator
• Sending Nullable types to the Database
• Nullable objects and the relational and logical operators
Introduction:
Prior to C# 2.0 there was an inability to assign a null value to certain types e.g. Int, DateTime, Float, Decimal. Microsoft C# 2.0 provides nullable type that allows you to assign a null to "value types" that have previously not allowed such an assignment. This article provides a walkthrough how to use nullable types in c# and working of ?? Operator with nullable types.


System requirement
The following software required to be installed
• .net framework & Visual studio 2005

Nullable type’s Use:
Databases use null as being distinct from values such as 0 and false. Without nullable types, mapping of c# data type to database null field depends on arbitrary decision taken by user. In different situations a null in a Boolean field may be equivalent to false or it may be equally valid to map it to true. Nullable types overcome this problem and allow any database value - including the “no value” of null - to be mapped directly to value types in C#. Databases are not the only example either. Any situation where something may not be defined, and only has a meaningful value if it is defined is benefit of nullable types. Optional parameters in XML or HTML also can be set equivalent to null which was not directly possible earlier. Likewise the square root of -1 in real number scenarios, the age of a customer who declined to say how old they are, or the time to completion of some batch process that’s not yet started are some perfect uses of nullable types. So Nullable types can save development time and ease program maintenance. In the past, handling the possibility of unused fields required the use of either placeholder values but this could only work if there was a value that would otherwise be invalid or an extra field that simply indicated whether a field was in use, but having to manually create and manage such a field is annoyance. The nullable type solves both the problems.

Creating Nullable types:
A nullable type is a special version of a value type that is represented by a structure. Nullable types are objects of System. Nullable, where T must be a non nullable type. Nullabe types can be declared in two different ways. First it can be explicitly declared as object of System.Nullable. For example, this creates int and bool nullable types –

System.Nullable intCount;
System.Nullable boolDone;


Secondly it can be declared using short hand method as follows:

int? intCount;
bool? boolDone;


There are two ways to determine if a variable of nullable type is null or contains a value. Nullable variable can be compared with null value or HasValue read-only property can be used.

int? intCount = null;
if (intCount != null )
Console.WriteLine(intCount);
if (intCount.HasValue)
Console.WriteLine(intCount);

If a nullable variable is null and its value is tried to obtain then System.InvalidOperationException will be thrown. Nullable variable’s value can be obtained by using the Value read-only property or by casting it into its underlying type.
Following code sample demonstrates this:-

using System;
using System.Collections.Generic;
using System.Text;

namespace NullableTypeBOK
{
class NullableType
{
static void Main(string[] args)
{
int? intCount = null;
if (intCount.HasValue)
Console.WriteLine(intCount.Value);
else
Console.WriteLine("Count has no value");

intCount = 100;
if (intCount.HasValue)
Console.WriteLine(intCount.Value);
else
Console.WriteLine("Count has no value");

Console.Read();

}
}
}


A nullable object can be used in expressions in the same way as its underlying type. When non-nullable and nullable types are mixed in an operation, the outcome is a nullable value.

The ?? Operator:
The ?? Operator is also called the null coalescing operator, which lets us specify a default value that will be used when nullable object contains null. If without using ?? Operator nullable object is tried to cast to its underlying type then System.InvalidOperationException will be thrown if the nullable object contains a null value. It can be declared as follows:-

Nullable-object ?? Default-value
If nullable object contains a value, then the value of ?? Operator is that value. Otherwise the value of the ?? Operator is default value. For example, in the following code amount is null. This causes Interest to be assigned the value 0.0 and no exception will be thrown and if amount is set to some value then interest will be accordingly.
static void Main(string[] args)
{
float Interest;
System.Nullable pAmount = null;
// if pAmount=10.0F then Interest=40 otherwise 0
System.Nullable rate = 0.8F;
System.Nullable time = 5;
Interest = (pAmount * rate * time) ?? 0.0F;
Console.WriteLine(Interest);
Console.Read();
}

The right hand expression of ?? Operator is evaluated only if left hand side of the operator does not contain a value.

Sending Nullable types to the Database:
Nullable types can be sent to the database and have DBNull inserted for types that have a null value. To do this the ??Operator is used and DBNull is casted to an object. The cast is required because the objects on either side of the ??Operator must be compatible.

Nullable objects and the relational and logical operators:
Nullable objects can be used in relational expressions as same as their corresponding Non-Nullable types. However, when two nullable objects are compared using the <, >, <= or >= operators, the result is false if either of the object is null.
When a logical expression involves two bool? Objects, outcome will be true, false or null. Following truth table shows the entries for the & and operators that apply to bool?.



References:
http://www.blogger.com/www.msdn.com
http://www.blogger.com/www.techrepublic.com

Monday, January 28, 2008

Creating Sites and List folders in a SharePoint using C# programmatically

Purpose of the Content:
Objective of this document is to throw some light on object model in MOSS using C#
This article will cover following topics
1. Introduction
2. Prerequisites
3. SPWebCollection.Add Method
4. Creating sites in SharePoint
5.SPListItemCollection.Add Method:
6.Creating folders in SharePoint List:


Introduction
The Windows SharePoint Services object model consists of forty-two namespaces in ten assemblies that are used in SharePoint sites on the server that is running Windows SharePoint Services1. The Microsoft.SharePoint and Microsoft.SharePoint.Administration namespaces provide types and members that can be used with lists and sites, as well as to manage a server or collection of servers that are running Windows SharePoint Services.

Now creating sites programmatically is one of the features that SharePoint SDK provides. The following sections will focus on how we can achieve this functionality.



Prerequisites :
Creating sites may be one of the task or the only that a web part does। So one must know how to develop and configure the web parts using SharePoint. Here I m using a web part consist a button on click of which, the new site creation logic will execute.

While sites are created through SharePoint we associate a site template name with the site. So it will be helpful to know how to develop and configure custom site templates if you want to use in new site. You can also refer the existing site template provided by SharePoint

SPWebCollection.Add Method:
The method Creates a Web site object with the specified site-relative URL, title, description, locale ID, and site definition or site template object.

SPWebCollection.Add Method (String, String, String, UInt32, SPWebTemplate, Boolean, Boolean) (Microsoft.SharePoint)

Namespace: Microsoft.SharePointAssembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)
public SPWeb Add (
string strWebUrl,
string strTitle,
string strDescription,
uint nLCID,
SPWebTemplate WebTemplate,
bool useUniquePermissions,
bool bConvertIfThere
)

Parameters:


strWebUrl :A string that contains the new Web site URL relative to the root Web site in the site collection. For example, to create a Web site at http://MyServer/sites/MySiteCollection/MyNewWebsite, specify MyNewWebsite, or to create a Web site one level lower at http://MyServer/sites/MySiteCollection/Website/MyNewWebsite, specify Website/MyNewWebsite.

strTitle: A string that contains the title.

strDescription: A string that contains the description.

nLCID: An unsigned 32-bit integer that specifies the locale ID.

WebTemplate: An
SPWebTemplate object that represents the site definition or site template.

6· useUniquePermissions: true to create a subsite that does not inherit permissions from another site; otherwise, false.

bConvertIfThere: true to convert an existing folder of the same name to a SharePoint site. false to throw an exception that indicates that a URL path with the specified site name already exists.


Return ValueAn SPWeb object that represents the Web site.

Creating sites in SharePoint:

1· Add the following namespaces and reference the DLL Microsoft. SharePoint.dll
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

2· Get the sp web object of the current site in which site is to create as
SPWeb spCurrentWeb = new SPSite(strSiteURL).OpenWeb(); where strSiteURL is the URL of the site as http://chdsez108269d:999/

3· Place the site template in the following SharePoint directory
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\

4· Now call the following function with given required parameters
private SPWeb CreateNewSite(SPWeb spCurrentWeb, string siteName, string siteDesc, string siteTemplateName, string strWebUrl)

Usage:

SPWeb spEventWeb = this.CreateNewSite(spcurrentweb, ”MyNewSite”,”siteDescription”,”MyCustomTemplate”,”MyNewSiteURL”))

Where spcurrentweb is spweb object of current site
o siteName and siteDesc is the name and description of the new site to create
o siteTemplateName is name of the template of the new site
o strWebUrl is the relative URL of the new site which can be different or same as the siteName
Full function body is below

private SPWeb CreateNewSite(SPWeb spCurrentWeb, string siteName, string siteDesc, string siteTemplateName, string strWebUrl)
{
try
{
if (spCurrentWeb != null)
{
if (spCurrentWeb.Webs[siteName].Exists == false)
{
//get the template collection from site based on locale Id
SPWebTemplateCollection Templates = spCurrentWeb.Site.GetWebTemplates(Convert.ToUInt32(1033));
if (Templates != null)
{
//get the template object from template collection based on locale Id
SPWebTemplate siteTemplate = Templates[siteTemplateName];
if (siteTemplate != null)
{
//create a new site and add it in web collection of the parent web
using (SPWeb spChildWeb = spCurrentWeb.Webs.Add(strWebUrl, siteName, siteDesc, (uint)1033, siteTemplate, false, false))
{
if (spChildWeb != null)
{
spChildWeb.AllowUnsafeUpdates = true;
spChildWeb.Update();
return spChildWeb;
}
else
{
throw new Exception("Site " + siteName + "can't be created");
}
}
}
}
}
else
{
throw new Exception("Site " + siteName + " already exist");
}
}
return null;
}
catch (Exception ex)
{
LogException(ex, "Site can't be created!!! some exception has occoured");
return null;
}
finally
{
if (spCurrentWeb != null)
spCurrentWeb.Dispose();
}
}

SPListItemCollection.Add Method:

The following method Create an item that uses the specified folder URL, object type, and leaf name but requires the Update method to actually add the item to the list.

SPListItemCollection.Add Method (String, SPFileSystemObjectType, String) (Microsoft.SharePoint)

Namespace: Microsoft.SharePointAssembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

public SPListItem Add
(
string folderUrl,
SPFileSystemObjectType underlyingObjectType,
string leafName
)
Parameters

o folderUrl : A string that contains the server-relative URL of the folder, beginning with a forward slash; for example, /sites/mysite/subweb/Lists/mylist/myfolder.

underlyingObjectType : A
Microsoft.SharePoint.SPFileSystemObjectType value that indicates the object type. Only File and Folder are valid types for the underlying object type.


leafName: A string that contains the leaf name, which is everything after the last forward slash in the URL, including the file extension.

Return Value: A
Microsoft.SharePoint.SPListItem object that represents the new item.
Creating folders in SharePoint List:
1· Add the following namespaces and reference the DLL Microsoft. SharePoint.dll
using Microsoft.SharePoint;

2· Get the sp web object of the current site in which site is to create as
SPWeb spCurrentWeb = new SPSite(strSiteURL).OpenWeb(); where strSiteURL is the URL of the site as http://chdsez108269d:999/

3· Now call the following function with given required parameters


private SPFolder GetFolder(SPWeb spCurrentWeb,string strSiteLink, string strListName, string strFolderName)
Usage:

spFolder spNewFolder = this.GetFolder(spcurrentweb, “MySiteLink”, “MyListName”, “MyFolderName”);
Where spcurrentweb is spweb object of current site
o MyListName and MyFolderName is the list name and folder name in the given list.
o MySiteLink is the relative URL of the new site which can be different or same as the siteName
Full function body is below


private SPFolder GetFolder(SPWeb spCurrentWeb,string strSiteLink, string strListName, string strFolderName)
{
using (spCurrentWeb)
{
if (!string.IsNullOrEmpty(strFolderName))
{
//create a folder with the given name in the event list if don't exist, otherwise return the existing folder
if (spCurrentWeb.GetFolder("Lists/" + strListName + "/" + strFolderName).Exists != true)
{
spCurrentWeb.AllowUnsafeUpdates = true;
SPList spListEvent = spCurrentWeb.Lists[strListName];
//create a new folder in the list
SPListItem spFolderEvent = spListEvent.Items.Add(strSiteLink + "/Lists/" + strListName, SPFileSystemObjectType.Folder, strFolderName);
spFolderEvent.Update();
spListEvent.Update();
spCurrentWeb.Update();
}
//return the existing folder from the list
return spCurrentWeb.GetFolder("Lists/" + strListName + "/" + strFolderName);
}
return null;
}
}




References:
http://msdn2.microsoft.com/en-us/library/ms439689.aspx
http://msdn2.microsoft.com/en-us/library/ms448720.aspx