add

Wednesday, February 25, 2009

How to access SharePoint User Profile from C# code

Hi All,

We all know sharepoint user profile stores users information. Sometimes we use out of box features to update these profile values like mysite stc but many times we come across the situation where we need to access uer profile from code, update the properties and save the profile.

In this post, I will tell you the step by step way to access user profile and to access/update the property field.

Step 1: Refer the following dlls in the code:

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;



Step 2: Create the instance of SPSite object:

using (SPSite ospSite=new SPSite("http://servername:portname")
{}

where http://servername:portname is your sharepoint application url.
Here we have used using to create the instance of SPSite since 'using' automatically disposes the object when the block gets finished.

Withing 'using' block , add the following codes:


Step 3: Create the instance of servercontext object:

ServerContext ospServerContext = ServerContext.GetContext(ospSite);


Step 4: Create the instance of userporfile object propertycollection object:

UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);
UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(UniqueId);
Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection;

here uniqueid is the id by which each profile is recognized individually. Eacn user profile has a uniqueId many ny 5-2-1 id if it is an AD account or GUID.


Step 5: Check whether the USerprofile object is null or not

if (ospUserProfile != null && propColl != null)
{}

Step 6: Iterate thorugh all the proerties in property collection:

foreach (Property prop in propColl)
{}

In the for loop you can get the property name and value like this:

To get property name: prop.Name
To get property value: ospUserProfile[prop.Name].Value

To set a value to a proerty : ospUserProfile[prop.Name].Value ="SOME VALUE";

To save the user profile after updation: ospUserProfile.Commit();

This will get the userporfile of a user and update the profile.


The whole code is as follows:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using System.IO;
using System.Data;
using Microsoft.Office.Server.UserProfiles;

namespace Program1
{

public static void Main(string args[])
{
using (SPSite ospSite = new SPSite(webApp))
{
try
{
ServerContext ospServerContext = ServerContext.GetContext(ospSite);
UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);
UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(uniqueId);
Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection;

if (ospUserProfile != null && propColl != null)
{
foreach (Property prop in propColl)
{
Console.WriteLine("property Name : " + prop.Name);
Console.WriteLine("proerpty Value : " + ospUserProfile[prop.Name].Value);

//If updation is required
ospUserProfile[prop.Name].Value="SOME VALUE";

}
ospUserProfile.Commit();
}
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
}
}
}

Monday, February 23, 2009

How to get old index value of dropdown when index change occures

Many times user faces this situation: A dropdown with some values. User selected a value and SelectdIndexChanged event fires.
In the code block, one can get the current index value of dropdown but what if old value is required. that is value before selecting the new index.

The simple solution is to use viewstate to hold the old value:

Suppose we have a dropdown 'dropdown1' with some item values.

Steps:
1.In code behind, we defined a public property IndexVal that store and fetch dropdown index value from a viewstate variable:

public int IndexVal {
get
{
return Convert.ToInt32(ViewState["OldSelectedIndex"]);
}
set {
ViewState["OldSelectedIndex"] = DropDownList1.SelectedIndex;
}
}

2. When the page loads for 1st time, set the viewstate value to dropdown index value

if (!IsPostBack)
IndexVal = DropDownList1.SelectedIndex;

3. When SelectedIndexChanged event fires, we can get the old index value from viewstate and new index value from the dropdown itself.
Then set the viewstate with new value.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int oldValue IndexVal;
int newValue DropDownList1.SelectedIndex;
IndexVal = DropDownList1.SelectedIndex;
}


Varun Sharma

Saturday, February 21, 2009

Javascript call from Master page and content Page -Part I

Create a JavaScript function on the fly and call the JavaScript function in the MasterPage Page_Load() event
C#
protected void Page_Load(object sender, EventArgs e)
{
string someScript = "";
someScript = "";
Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", someScript);
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim someScript As String = ""
someScript = ""
Page.ClientScript.RegisterStartupScript(Me.GetType(), "onload", someScript)
End Sub

The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind. More info can be found over here http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

Tuesday, February 10, 2009

Using Lambard Expression

Lambda Expressions are based on functional calculus—Lambda Calculus—from the 1930s, and Lambda Expressions exist in other languages.Think of Lambda Expressions as brief inline functions whose concise nature is an ideal fit for LINQ.


Lambda Expressions are written with a left side, the => symbol, and a right side, as in(x,y) => x + y;.
The left side represents the input arguments and the right side is theexpression to be evaluated.

For example(x,y) => x + y;is read x and y goes to—or as I read it gosinta—the function x + y.

Implicit in the expression is the return result of x + y.

The input argument or arguments can be inferred and generated by the compiler, called implicit arguments, or expressed explicitly by you.
The preceding Lambda Expression can also be rewritten as(int x, int y) => x + y;

class Program{

static void Main(string[] args) {

Func<int, int, int> add = (int x, int y) => x + y; Console.WriteLine(add(3, 4)); Console.ReadLine(); }}[/code]
You can begin exploring how Lamba Expressions support LINQ queries by seeing howLambda Expressions are used in extension methods such as Select, Where, orOrderBy.
Using Select<T> with Lambda Expressions
Check the following example:[code] var numbers = new int[]{1,2,3,4,5,6}; foreach(var result in numbers.Select(n => n)) Console.WriteLine(result);[/code]
Here we are executing the SELECT * behavior of SQL queries by initializing the Select extension method with n => n. n => n means that n is the input and you want to return n.
Using Where<T> with Lambda Expressions
The Where extension method is employed in scenarios where you would use conditional logic to filter the elements returned in a resultset. Like Select, Where returns an IEnumerable, where T is defined by the type of the result from the Lambda Expression.
[code] var words = new string[]{"Drop", "Dead", "Fred"}; IEnumerable<string> hasDAndE = words.Where(s => s.Contains('D') && s.Contains('e')); foreach(string s in hasDAndE) Console.WriteLine(s);[/code]
Using OrderBy<T> with Lambda Expressions
OrderBy is the extension method that supports sorting. OrderBy accepts a Func genericdelegate. The Func argument can be expressed with a literal Lambda Expression.
[code]
var numbers = new int[] {1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };IEnumerable<int> ordered = numbers.OrderBy(n=>n); foreach(var num in ordered) Console.WriteLine(num);[/code]

Using Conversion Types

A very common task is converting data from one form to another.
The new version of .NET has conversion operators ToArray, OfType, Cast, AsEnumerable, ToList, ToDictionary, and ToLookup. We will discuss each one by one:

ToArray : Arrays are fast but not very convenient. It is tedious to write array management code when collections like List make managing data easier.The main reason, dot net framework supprots ToArray because many legacy code and API supprots uses ToArray till now.
OfType : The conversion operator OfType returns an IEnumerable collection of only the types defined by the parameter T. For example, initializing a list of objects where some are integers, you can quickly extract just the integers
var numbers = new object[]{1, "two", null, "3", 4};
foreach(var anInt in numbers.OfType())
Console.WriteLine(anInt);
Cast: To receive an exception if elements of the source type cannot be converted to the target type, use the Cast conversion operator.
AsEnumerable : Many types implement IEnumerable.AsEnumerable Forces an Object That Implements IEnumerable to Use theBehaviors of the IEnumerable Interface.
ToList: The ToList conversion operator forces an immediate query evaluation and stores the results in a List.
ToDictionary:A dictionary is a collection of name and value pairs. ToDictionary converts anIEnumerable object—such as is returned from a LINQ query—into anIDictionary object.
ToLookup:ToLookup converts an IEnumerable to a Lookup type. Lookup is like a dictionary, but where a Dictionary uses a single key value, Lookup maps keys to a collection of values. Lookups have no public constructor and are immutable. You cannot add or remove elements or keys after they are created.

Summary:
Compound type initialization makes it easier to initialize arrays and lists and is an essential capability for initializing anonymous types. Conversion operators take some of the tedium out of converting between convenient types and other types. More important, this chapter demonstrates the classic onion layering of complexity in .NET that makes it possible to do a lot of work with relatively few lines of code.

Introduction to LINQ - Part 2 - Anonymous types

Before jumping right into the LINQ asnd its implementation, I would like to introduce some new features of dot net framwork 3.0/3.5 that were incorporated to support LINQ.

In this article, we will discuss Anonymous types

First thing about Anonymous types is that it uses the keyword var. The var introduced with .NET 3.5 indicates an anonymous types. A developer who has worked in VB6, may say that var was there in VB6 also. So what's the difference?

Anonymous types defined with var are not similar to VB variant. So what is var?
The var keyword signals the compiler to emit a strong type based on the value of the operator on the right side.

A simple anonymous type begines with a var keyword, the assignment operator and a not null initial value.

var title="Tutorial on LINQ";

here the data type of var will be set based on the data type of the right hand side. So the datatype of title will be string.

As you will notice that I have mentioned that we need to assigna 'not null initial value'.

Anonymous types must always have an initial assignment and it can’t be nullbecause the type is inferred and fixed to the initializer.

Summary
Anonymous types are strong typeswhere the compiler does the work of figuring out the actual type and writing the classimplementation, if the anonymous type is a composite type.

Introduction to LINQ - Part 1

Microsoft dot net framework 3.0 introduced new feature named LINQ.

What is LINQ :
Language Integrated Query (LINQ) is a methodology that simplifies and unifies the implementation of any kind of data access.

Why LINQ:


The main objective behind LINQ was to address the concept related problems and technical difficulties encountered when using databases with .NET programming languages.

The two main intention of introducing LINQ were:
  • provide a solution for the problem of object-relational mapping
  • simplify the interaction between objects and data sources

LINQ eventually evolved into a general-purpose language-integrated querying toolset. This toolset can be used to access data coming from in-memory objects (LINQ to Objects), databases (LINQ to SQL), XMLdocuments (LINQ to XML), a file-system, or any other source.


Advantage of LINQ

Developers can use LINQ with any data source.

They can express efficient query behavior in their programming language of choice, optionally transform/shape data query results into whatever format they want, and then easily manipulate the results.

LINQ-enabled languages can provide full type-safety and compile-time checking of query expressions, and development tools can provide full intellisense, debugging, and rich refactoring support when writing LINQ code.LINQ supports a very rich extensibility model that facilitates the creation of ery efficient domain-specific operators for data sources.