Sunday, May 23, 2010

DataColumn.MaxLength not working in C#

DataColumn.MaxLength

Visual Studio Intellisense: Gets or Sets the maximum length of a text column.
MSDN: The maximum length of the column in characters. If the column has no maximum length, the value is –1 (default).

But most of the developers didn't able to get the desired result. It always returns -1. Microsoft has confirmed that this is a bug in the Microsoft products.

To resolve this, you need to set the "MissingSchemaAction" of "SqlDataAdapter" object. If you did not have it set, the ColumnLength property always returns -1.

Reference: http://support.microsoft.com/kb/317175

Example:

string strQuery = "SELECT * FROM tbl_MyTable";
objConn = new SqlConnection(strConnString);
objConn.Open();
objCmd = new SqlCommand(strQuery, objConn);
objDA = new SqlDataAdapter(objCmd);
objDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
objDS = new DataSet();
int iCount = objDA.Fill(objDS);

Monday, May 17, 2010

When the heart is more beautiful than the face!!!

"One of my friend forwarded me an email with this beautiful story. It's awesome and so decided to share this through my blog."

The rain pouring out heavily invited me for a rendezvous but then I had a session. Just as I checked the time on my cell, the knock at the door announced the arrival.

The assistant informed me of the client and I asked her to send them in.. The couple in their late twenties. A second later the door opened again and I beckoned them to come in..

This man came in … straight out of Bollywood or rather Hollywood.

Accompanying this 6+ft guy was this lady… Very thin , and looking unwell.
I wondered what brought them here. They didn’t look like your usual battlefield couples that come for counseling. Generally when couples came in the first noticeable thing they did was pulling chairs apart. Here he pulled it closer. Asked her if she was fine. The body language suggested care and concern. I sat back amused and let them speak.

This couple was married about 10 years back. A love marriage.. Intercaste marriage they braved many storms to be together .Then a couple of years back destiny struck.

She was diagnosed with ovarian cancer..The disease took a toll on her, drained her physically and psychologically. Her husband stood like the rock of Gibralter.. A pillar of strength.

Yet….

She now feels inadequate for various reasons. One her inability now to conceive, Two her looks that she thought was her identity and description She could not come to terms with the way she looked now. Her health was bad enough and her depression she thought was contagious spreading all around wherever she went.
She thought him too young to be saddled with problems and wished him a better life. She wanted a separation. She wanted him to move on with life..
She didn’t want to be responsible for ruining his youth, his future. She said she loved him and wanted to let him go… to live better.

The moment she said that I looked at her husband. He looked hurt. Deeply hurt.
This is what he had to say and this is what prompted me to write this blog:

“ I love her for what she is. Yes I liked her looks when I first met her but that was because that was the first noticeable thing, As I got to know her I realized how much more beautiful she is on the inside. I can never love anyone after I have experienced this beauty. Everyone else fails in comparison. What I see her as is her real self and to see her for her beauty you need to look through my eyes and not the mirror. The mirror has its set of lies and one of that is about her looks. To know her, look through me. I do not want any other happiness, I promised to be with her through thick and thin and I will be there no matter what. I will never leave her. She can throw me out , but I will continue living on the doorstep. I need her to know that these suggestions by her are an insult to my love. Is love only about looks?. Is beauty just about skin? If I were to go through the same would she leave me? I would never be able to do that. For me she is highly fecund , producing a higher degree love everytime I look at her. I love her truly and deeply and this is why I’m here to take your help and let her know the value of a relationship that goes beyond all these fallacies of appearances.”

What a magnanimous man!

I wasn’t the only one with tears, there was this beauty in front of me crying yet unaware of it. I excused myself and walked out.. I was glad they came to me though honestly all I did was listen to them but I saw a lovely example of true love. Their coming here was important for them and for me. To witness such love is a blessing.

These days when relations are so fragile and break at the slightest of excuses like:
She/ He is too fat
She can’t cook
She doesn’t work
He is hardly earning enough
We need space
He/She smokes/drinks
She isn’t glamourous enough
He/She can’t satisfy me
She/He doesn’t get along with inlaws , friends etc.

And many such excuses so inane , obfuscating the whole concept of marriages,just desperately searching a way out. This person purely defined something so perfect. Perfect love that transcends all these fallacies of looks.

This especially is so important when people marry only on the basis of looks. Yes the matrimonial columns are all about how slim and beautiful your bride needs to be. But then one must realize that EXTERNAL BEAUTY IS SO TEMPORARY. Beauty is just skin depth.. The true beauty lies within. Appreciate that and see love blossom.

Sunday, May 16, 2010

How to rename SharePoint Server?

Sometimes you may need to rename your Computer Name where SharePoint is installed. This also applies to Virtual Machines. I recently tried to do this, but after doing that, I found that SharePoint is not working. So I need to do few activities to bring it back, which I have been listed below:

Step 1: Rename my Computer/Server from My Computer -> Properties -> Computer Name - Change... -> Restart

Step 2: stsadm –o renameserver

Step 3: stsadm –o updatefarmcredentials

Step 4: Restart IIS

Step 5: Update all identity accounts(basically machine names) in IIS

Step 6: stsadm.exe -o setconfigdb

Step 7: All Programs -> Microsoft Office Server -> SharePoint Product and Technologies Configuration Wizard

Step 8 Open Central Admin and change Alternate Access Mappings, wherever applicable.

You are done. I found few other steps also while goggling. But the above steps work for me. The following references may help in case there are some issues:

http://blogs.sharepointlabs.com/Lists/Posts/Post.aspx?List=9312760c%2Dc235%2D4cc0%2Da25f%2D481a34785c3d&ID=6

http://moss-exchange.blogspot.com/2007/12/renaming-sharepoint-server.html

http://vspug.com/nrdev/2008/07/15/tip-how-to-rename-a-sharepoint-server-machine-name/http://vspug.com/nrdev/2008/07/15/tip-how-to-rename-a-sharepoint-server-machine-name/

Monday, March 15, 2010

SharePoint SPSite.AllowUnsafeUpdates

The Microsoft idea behind introducing the AllowUnsafeUpdates property is to protect you from cross-site scripting attacks.

MSDN Definition: Gets or sets a Boolean value that specifies whether to allow updates to the database as a result of a GET request or without requiring a security validation. Setting this property to true opens security risks, potentially introducing cross-site scripting vulnerabilities.

If you try to do any updates to lists, webs or any SharePoint objects that require an SPSite to be created first, you need to set AllowUnsafeUpdates to TRUE, otherwise it will through an error saying "System.Exception: Microsoft.SharePoint.SPException: The security validation for this page is invalid."

In order for the AllowUnsafeUpdates to work, that the Update method of the SPSite object needs to be called as well:

SPSite.AllowUnsafeUpdates = true;
SPSite.Update();

Also, you may want to try using a POST, rather than a GET in order to avoid having to set this property. If your code is processing a POST request then make sure you call SPUtility.ValidateFormDigest() before you do anything else. This will ensure that the post request is validated (that it is not a cross-site scripting attack) and after that you will not have to worry about AllowUnsafeUpdates, because its default value will be “true” after the form digest is validated.

If the HTTPContext.Current is null then AllowSafeUpdates will be always true. This is the case in rich clients where no cross-scripting is possible as there are simply no web requests.

When any object that implements ISecurable (those are SPWeb, SPList and SPListItem) breaks or reverts their role definition inheritance. This means every time you call SPRoleDefinitionCollection.BreakInheritance(), BreakRoleInheritance(), ResetRoleInheritance() or set the value of HasUniquePerm the AllowUnsafeUpdates property of the parent web will reset to its default value and you may need to set it back to true in order to do further updates to the same objects. So always set AllowUnsafeUpdates back to true after you break inheritance in an environment with HTTPContext.

Additional References:

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.allowunsafeupdates.aspx
http://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/
http://hristopavlov.wordpress.com/2008/05/21/what-you-need-to-know-about-allowunsafeupdates-part-2/

SharePoint SPWeb.EnsureUser

MSDN Definition: Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.

This method can not be called by everyone, as it requires some high level permissions. Your solution is to wrap the EnsureUser within RunWithElevatedPrivileges call.

According to the SharePoint SDK it should be enough to call in your code:

using (SPSite site = new SPSite("http://mywebsite.com"))
{
using (SPWeb web = site.OpenWeb())
{
string login = "MyUserName";
string groupName = "MyGroup";
SPUser user = web.EnsureUser(login);
SPGroup group = web.Groups[groupName];
group.AddUser(user);
}
}

The above code works correctly: the EnsureUser method returns a valid SPUser object which can be added to the MyGroup group.

If you run the above piece of code with Forms Based Authentication (FBA), all you see is an SPException: SharePoint cannot find the user.

Surprisingly the same piece of code executed from a control or an Application Page runs correctly.

At some point the Roles class tries to retrieve the system.web/roleManager configuration section. Because that section is available in the web.config of a Web Application with FBA configured, the code works properly. But for Console Applications it doesn't. What you can do is to create a config file like ConsoleApplication1.exe.config (assuming that ConsoleApplication1.exe is the name of your executable after building) and copy there that particular piece of configuration from your web.config. If you run your Console Application now, it should work perfectly.

Note:

To add an User to SharePoint Group, we need to add the User to the Site Collection. For instance if we write the following lines of code to add user to a group, if will throw error is user does not exist.

group.Users.Add(item,"","","");

To resolve this, we can easily use the following line of code:

SPUser userTemp = web.EnsureUser(item);

If the user is known on the site collection there are three ways to get it:

1. Gets the collection of user objects that represents all users who are either members of the site or who have browsed to the site as authenticated members of a domain group in the site.

SPUserCollection users = portalSite.RootWeb.AllUsers;

2. Gets the collection of all users that belong to the site collection.

SPUserCollection users = portalSite.RootWeb.SiteUsers;

3. Gets the collection of user objects that are explicitly assigned permissions on the Web site.

SPUserCollection users = portalSite.RootWeb.Users;

Additional References:

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.ensureuser.aspx
http://blog.mastykarz.nl/inconvenient-programmatically-sharepoint-users-spweb-ensureuser/
http://vspug.com/mirjam/2007/12/20/using-spweb-ensureuser-loginname-to-add-a-new-spuser-to-a-web/

Thursday, February 25, 2010

How can we create a new SharePoint 2010 Site using Power Shell scripts?

Step 1: We need to create a Power Shell script file, say, createsite.ps1

Write-Host
# define variables for script
$SiteTitle = "My First Site using Power Shell"
$SiteUrl = "http://www.mydomain.com/sites/SiteName"
$SiteTemplate = "STS#1"

# check to ensure Microsoft.SharePoint.PowerShell is loaded
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}

if ($snapin -eq $null)
{
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

# delete any existing site found at target URL
$targetUrl = Get-SPSite | Where-Object {$_.Url -eq $SiteUrl}

if ($targetUrl -ne $null)
{
Write-Host "Deleting existing site at " $SiteUrl
Remove-SPSite -Identity $SiteUrl -Confirm:$false
}

# create new site at target URL
Write-Host "Creating new site at " $SiteUrl
$NewSite = New-SPSite -URL $SiteUrl -OwnerAlias Administrator -Template $SiteTemplate -Name $SiteTitle
$RootWeb = $NewSite.RootWeb

# display site info
Write-Host
Write-Host "A new SharePoint Site has been created successfully" -foregroundcolor Green
Write-Host "-------------------------------------" -foregroundcolor Green
Write-Host "Site URL:" $RootWeb.Url -foregroundcolor Yellow
Write-Host "Site ID:" $RootWeb.Id.ToString() -foregroundcolor Yellow
Write-Host "Site Title:" $RootWeb.Title -foregroundcolor Yellow
Write-Host "-------------------------------------" -foregroundcolor Green

Step 2: To execute this script, you can create a bat file, say, setup.bat and execute the batch file

powershell -Command "& {Set-ExecutionPolicy bypass}" -NoExit
powershell -Command "& {.\createsite.ps1}" -NoExit
pause

Wednesday, February 24, 2010

Free SharePoint 2007 Video Tutorials

Today I was googling to find some video tutorials so that the begenners can have some initial understandings on SharePoint and found the following sites really helpful. And above all they are absolutely free to access.

http://sptraining.sharepointsite.net/

Thursday, February 18, 2010

How to add dynamic silverlight controls in runtime?

In Silverlight, While it is possible to create all your controls and objects in code, best practices dictate that it is usually better to do so in Xaml. The most compelling reason is that Xaml is highly "toolable" - that is, it lends itself to round-trip modification in tools such as Visual Studio and Expression and thus is easier to scale, modify and maintain.

On the other hand, there are times that you can't know at design time which or how many objects you'll need, and the ability to create objects dynamically can be a fundamental requirement.

So let's create a Silverlight page and add the following:

<Canvas x:Name="myCanvas">
<Button x:Name="myButton" Content="Hello" Canvas.Left="10" Canvas.Top="10"/>
<Button x:Name="Another" Content="Add Another" Canvas.Left="10" Canvas.Top="50" />
</Canvas>

The objective is to add a button to the page with the words "Add Another." When the user clicks on this button, we want to add a button to the UI and we want that button to have its own size, position and behavior. We do all of that in the code behind.

The first thing to do is to add an event handler for the new button in the Page Load event,

Another.Click += new RoutedEventHandler(Another_Click);

And to add its implementation, in which you'll create a new button and set its properties,

void Another_Click(object sender, RoutedEventArgs e)
{
Button b = new Button();
b.Content = "I live!";
b.SetValue(Canvas.LeftProperty, 10.0);
b.SetValue( Canvas.TopProperty,
this.newButtonPosition);
this.newButtonPosition += 30.0;
b.Width = 100;
b.Height = 20;
b.Click +=new RoutedEventHandler(new_button_click);
myCanvas.Children.Add(b);
}

void new_button_click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
btn.Content = "Don't do that!";
btn.IsEnabled = false;
}

Because the canvas's Left and Top are not actually properties of the Button (but are extended properties) you set them with the SetValue method, which takes two parameters. The first is the actual name of the property you want to set (Canvas.LeftProperty and Canvas.TopProperty) which is not difficult to find as Intellisense will supply it) and the second is the value (in this case a double).

Also we have added an event handler registration to the button. This means that every button that is added is registered to call new_button_click when it is clicked. As the buttons are clicked, they change their message and become disabled.

Thursday, February 4, 2010

Anonymous Types

The ability to create new types 'on the fly' is done using Anonymous Types.

All of this happens at compile time, so anonymous types are still strongly typed. In reality, the compiler automatically creates a class that represents the anonymous type.

Example: var product = new {Name = "C# Rocks!", Price = 3};

-> When an anonymous type is assigned to a variable, that variable must be initialized with the var construct.

-> Anonymous types are reference types that derive directly from object.

-> If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.

-> Anonymous types cannot contain unsafe types as properties.

Note: While anonymous types might not seem all that useful on the surface, they are the cornerstone for LINQ. Without anonymous types, LINQ would not be able to create types dynamically. This is what allows LINQ to query for an arbitrary set of data, without first having the structure declared.

Implicitly typed local variable in C#

Implicitly typed local variable is a variable that can be declared without specifying the .NET type explicity. The type of that variable will be inferred by the complier from the expression on the right side of initialization statement.

Examples:

var i = 5;

When the compiler sees this in the code, it tries to figure out the type of the variable based on the value you assigned it. Hence, if you call GetType() on i, the type returned is actually System.Int32.

The following will give you an error because the compiler can't figure out what type the variable is:

var i = null;

You have to initialize the variable with something that the compiler understands so it can figure out the type. Calling GetType() on firstName here would give you System.String:

var firstName = "David";

Limitations:

-> The declarator must include an initializer. Unlike normal declarations, you can’t declare the implicitly type variable without initializing.

-> The compile-time type of the initializer expression cannot be the null type.

-> If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type.The implicitly-type local variable cann’t be initialized with different types more than one time. You can’t assign the string to varaible “test” after initializing with integer value “1".

-> Cannot initialize an implicitly-typed local variable with an array initializer like var test = { 1, 2, 3 }; Can only use array initializer expressions to assign to array types, like a new expression var test1 = new[] { 1, 2, 3 };

-> an implicitly typed local variable cannot be Nullable variable which means the following syntax to create a Nullable variable in C# will not work with implicitly typed variables - var? age = null;

-> Implicit Typed Variable cannot be used as class members such as field. They can only be used as local variables inside methods.

Extension Methods

It is a special kind of static method that allows you to add new methods to existing types without deriving, recompiling or modifying the original type. The extension methods are called as if they were instance methods from the extended type.

public static class MyExtensionClass
{
public static int Multiply(this int num)
{
return num * num;
}
}

class Program
{
static void Main(string[] args)
{
int i = 3;
Console.WriteLine(i.Multiply());
Console.ReadLine();
}
}

Here are the few things we should keep in mind while using Extension Methods:

-> This keyword has to be the first parameter in the extension method parameter list. The type of the first parameter will be the type that is extended.
-> Extension methods can't access the private methods in the extended type.
-> Extension methods can be defined only in a static class.
-> If you want to add new methods to a type, you don't have the source code for it, the ideal solution is to use and implement extension methods of that type.
-> If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called. Extension methods cannot be used to override existing methods.
-> If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced i.e. extension methods.
-> The concept of extension methods cannot be applied to fields, properties or events.