Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘example’

Site Workflow with While, IfElse, Code Activities

Posted by JP on October 17, 2012

In this article we can explore using multiple activities in a Site Workflow created using Visual Studio 2010. The core activities we use here are:

  • Code Activity to execute custom code
  • While Activity to execute inner activities upon condition is true
  • IfElse Activity to execute branching activities based on condition
  • LogToHistoryList Activity to log information to Workflow internal history list

Scenario

A typical approval scenario is being addressed here. An Expenses list is given for approval. The entries having Amount lesser than 100 are Approved.

Pre-Requisites

Create a custom list named Expenses for using this example. Add some items into the new list as shown below:


Create Workflow

Open Visual Studio 2010 and create a new Sequential Workflow Project as shown below:


In the next page choose your site collection and click the Next button to continue.

In the appearing page choose Site Workflow as shown below:


In the last page choose the option to start workflow manually.

    

Now you will be getting the Workflow designer with default activity inside it.


Add Activities

Open Visual Studio Now you can drag and drop the following activities from the Toolbox:

  • 1 Code Activity
  • 1 While Activity & IfBranch Activity
  • 2 Code Activity inside If, Else branches
  • 1 LogToHistory Activity

As shown below:


Our idea is following:

  • Create property named CurrentItem of type object, Index of type integer
  • In the first Workflow Activated, fetch all the Expenses items
  • In the Code Activity initialize the Index field
  • Set While Activity condition until CurrentItem is not null
  • Set the If branch condition as Amount less than 100
  • Set the Else branch condition as Amount greater than or equal to 100
  • Set the Code Activity inside If branch, to update status as Approved
  • Set the Code Activity inside Else branch, to update status as Rejected
  • Use the LogToHistory activity for logging the workflow completion information

Create Entity, Properties & Fields

Please create the following class to hold the Expense Item, in order to give an Object Oriented Look and Feel.

    namespace ExpenseApprovalWorkflow

  {


public class ExpenseItem

{


  public int ID;


  public double Amount;

}

}

Inside the Workflow class, add the following properties and fields.

namespace ExpenseApprovalWorkflow.Workflow1

{


public sealed partial class Workflow1 : SequentialWorkflowActivity

{


List<ExpenseItem> Expenses = new List<ExpenseItem>();


int Index;


ExpenseItem CurrentItem

{


get

{


if (Index < Expenses.Count)


return Expenses[Index];


return
null;

}

}

}

}

The Expenses list holds the ExpenseItem type items. The Index property represents the current index of the item being processed.

Initiation Code

Back to the workflow designer, double click on the onWorkflowActivated step and add the following code.

private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)

{


using (SPSite site = SPContext.Current.Site)

{


using (SPWeb web = site.OpenWeb())

{


var items = web.Lists[“Expenses”].GetItems(“ID”, “Amount”);


foreach (SPListItem item in items)

{


ExpenseItem expenseItem = new
ExpenseItem();

expenseItem.ID = (int)item[“ID”];

expenseItem.Amount = (double)item[“Amount”];

Expenses.Add(expenseItem);

}

}

}

}

The code fetches all Expenses list items from SharePoint and adds them to the Expenses field of our workflow class.

Code Activity

Double click on the Code Activity item from workflow design view (second activity). In the appearing code window enter the following code.

private void codeActivity1_ExecuteCode(object sender, EventArgs e)

{

Index = -1;

}

The code initializes the Index field to -1. This field will be incremented in the while loop later.

While Activity

Now select the While activity from the workflow design view and choose Properties window. Choose the Condition property as Code Condition and set the Inner Condition property as WhileCodeCondition.

    

The WhileCodeCondition
represents the name of the method which evaluates the While condition and returns true / false to continue / terminate the workflow.

Paste the following code in the Workflow class view.

private void WhileCodeCondition(object sender, ConditionalEventArgs e)

{

Index++;

e.Result = (CurrentItem != null);

}

You can see the method name matches the property we have specified. The method intakes the ConditionalEventArgs for specifying the condition of while activity.

IfElse Activity

You can see that there are 2 branch activities for the IfElse activity.

    

Select the first branch item and open the Properties window. Here we can specify the following properties:

  1. Condition as Declarative Rule Condition
  2. ConditionName as IfCondition
  3. Expression as this.CurrentItem.Amount < 100

You can see them in the Properties window as shown below:

    

The ellipsis button as highlighted in red color can be used to create the Expression. There is auto-completion enabled in the appearing editor dialog.


Now select the second branch item and open the Properties window. Here we can specify the following properties:

  1. Condition as Declarative Rule Condition
  2. ConditionName as ElseCondition
  3. Expression as this.CurrentItem.Amount >= 100

Now our If and Else branches are ready to proceed with their Code activities.

Code Activity for If branch

Now double click on the Code Activity for the If branch.

    

In the appearing code view, enter the following code.

private void codeActivity2_ExecuteCode(object sender, EventArgs e)

{


using (SPSite site = SPContext.Current.Site)

{


using (SPWeb web = site.OpenWeb())

{


var item = web.Lists[“Expenses”].GetItemById(CurrentItem.ID);

item[“Status”] = “Approved”;

item.Update();

}

}

}

The code fetches the Expense Item by ID and updates the Status as Approved.

Code Activity for Else branch

Now double click on the Code Activity for the Else branch.

    

In the appearing code view, enter the following code.

private void codeActivity3_ExecuteCode(object sender, EventArgs e)

{


using (SPSite site = SPContext.Current.Site)

{


using (SPWeb web = site.OpenWeb())

{


var item = web.Lists[“Expenses”].GetItemById(CurrentItem.ID);

item[“Status”] = “Rejected”;

item.Update();

}

}

}

The code fetches the Expense Item by ID and updates the Status as Rejected.

LogToHistoryList Activity

This activity logs information into the History List of the site. Select the activity and set the following property:

    

This list is a hidden list and is not shown in the Quick Launch or All Site Content.

To view the list you need to type the List Name in address bar. For example:

    http://SERVER/Lists/workflow%20history/AllItems.aspx

You can see various entries in the History List as shown below:

Using the History List we can verify the workflow instances being executed and their log information for troubleshooting.

Deploy the Workflow

Now we are ready to execute our workflow. Build the project, Right click on the solution and Deploy it.

Inside SharePoint

Back in SharePoint choose the Site Workflows and start our workflow.

    

Wait for a while for the execution to be completed.


Back to the Expenses list you can see the Status column being updated for the items.


You can open the Workflow History list to view the log entry as shown below:


This concludes our playing with Workflow activities.

References

http://msdn.microsoft.com/en-us/library/ms446847.aspx

Summary

In this article we have explored creating a Site Workflow using multiple activities. To summarize with following are the activities we have explored.

  • IfElse activity
  • While activity
  • Code activity
  • LogToHistoryList activity

I hope this example should provide knowledge to address complex workflow scenarios in your programming life. The source code contains the example we have discussed.

Advertisements

Posted in C#, SharePoint | Tagged: , , , , , , | Leave a Comment »

Impersonation in SharePoint 2010

Posted by JP on October 2, 2012

In this article we can explore the methods of Impersonation inside SharePoint 2010.

What is Impersonation?

Impersonation is the security feature that enables to control the Identity under which code is executed. Impersonation gives the following advantages:

· Run a high privilege code through a low privilege user

· Record changes in account of another user

image

Example

A web part has to execute code that will update a List.  There are many users using this web part but they all do not have write permission on the list.  As the web part code is getting executed in the user’s context, exception occurs for some users.

Using Impersonation we can elevate the code privilege to high so that no exception occurs.

What are the Impersonation methods in SharePoint 2010?

SharePoint 2010 provides the following methods of Impersonation:

1. RunWithElevatedPrivileges to impersonate as System Account user

2. Passing User Token inside SPSite to impersonate as particular user

3. Using Windows API

Note: System Account (SHAREPOINT\system) is the application pool user of SharePoint. If you are using Developer Installations on client operating systems (Windows 7 / Vista) the account name will be different.

Now let us see how to use the above methods.

1. RunWithElevatedPrivileges

This is the most commonly used method to impersonate.

SPSecurity.RunWithElevatedPrivileges(() =>

{

// Your code here

});

Note: In the case of RunWithElevatedPrivileges the System Account is used to perform the activity.

2. Passing User Token

SPUserToken is the server model which we use for the purpose. Each user’s token can be represented by this class. The User Token is actually a byte array.

The SPUser class contains the property named UserToken. Passing SPUserToken instance into the SPSite constructor impersonates the particular user.

Eg: new SPSite(UrlText.Text, user.UserToken);

For enumerating all the users of a site the web.Users property can be used.

Eg: web.Users


Running the Code

The attached source contains the following samples:

1. Enumerate Users

For enumerating users for given website the following code can be used:

using (SPSite site = new SPSite(UrlText.Text))

{

using (SPWeb web = site.OpenWeb())

{

SPContext context = SPContext.GetContext(web);

var users = context.Web.Users;

// Display to grid

usersGrid.DataSource = users.Cast<SPUser>().ToList<SPUser>();

}

}

On clicking the button we can see the following users as shown below:

– Please note that there are only 2 users for the site I use

– The current user logged in is Admin

image

2. Create Data Impersonating each User

Now we can try creating list items impersonating each user. The created item will be having the system property > Created By set to different users:

Following code performs the same:

int count = 1;

foreach (SPUser user in web.Users)

{

SPSite newSite = new SPSite(UrlText.Text, user.UserToken); // Impersonate

SPWeb newWeb = newSite.OpenWeb();

SPListItem item = newWeb.Lists[ListName].AddItem();

item[“Title”] = “Item ” + count++.ToString();

item.Update();

newSite.Dispose();

newWeb.Dispose();

}

On running the code above we can see the items created as shown below:

– Please note that the Created By property is different for each row

image

Note: An exception will be thrown if any of the user above do not have write permission.

3. Create Data using RunWithElevatedPrivileges

Now we can try creating the list items using RunWithElevatedPrivileges block. In this case the user is impersonated to System Account.

The code for the same is shown below:

SPSecurity.RunWithElevatedPrivileges(() =>

{

using (SPSite site = new SPSite(UrlText.Text))

{

using (SPWeb web = site.OpenWeb())

{

SPListItem item = web.Lists[ListName].AddItem();

item[“Title”] = “Item created with RunWithElevatedPriveleges”;

item.Update(); // Item will be created with System Account

ShowData(web);

}

}

});

We can see that the new item is created with System Account as shown below:

image

References

http://msdn.microsoft.com/en-us/library/aa543158.aspx

Summary

In this article we have explored 2 methods of Impersonation in SharePoint 2010. The associated code contains the example we have discussed.

Posted in C#, SharePoint | Tagged: , , , | 5 Comments »

CRUD and BCS

Posted by JP on September 30, 2012

In this article we can experiment with BCS by connecting to an external database. After completing this article you will be able to:

· View Database Table inside SharePoint

· Perform Add/Edit/Delete operations

Following are the activities involved.

1. Create database and table

2. Using SharePoint Designer create BCS External Content Type

3. Using SharePoint Designer create Add/Edit/Delete operations metadata

4. Using SharePoint Designer create Lists & Form

5. Using Central Administration set Permissions for external Content Type

1. Create database and table

Create a database and table named Customer with following fields:

clip_image002

Add some data into it:

clip_image004

2. Using SharePoint Designer create BCS External Content Type

Now we can create an External Content type using SharePoint Designer. Start the Designer application and open our SharePoint web site > External Content Types as shown below.

clip_image006

Click on the External Content Type button from the top side. In the appearing window change the Name and Display Name (click on the links) as shown below.

clip_image008

Now click on the External System link and you will get the following dialog.

clip_image010

Click on the Add Connection button and select SQL Server in the appearing dialog.

clip_image012

In the appearing connection details dialog, enter your server details.

clip_image014

Click the OK button and your server connection is ready.

3. Using SharePoint Designer create Add/Edit/Delete operations metadata

From the appearing tables list select the Customer table and right click to get the context menu. Use the Create All Operations menu item to get the Add/Edit/Delete operations wizard.

clip_image016

Click on the Finish button in the appearing wizard.

clip_image018

Click on the Save button from the top tool bar.

clip_image020

4. Using SharePoint Designer create Lists & Form

Now the operations are ready and we need to create the List Form and the associated Add/Edit/Delete forms inside SharePoint.

clip_image022

From the toolbar, click on the Create Lists & Form button as highlighted above. In the appearing dialog box enter the name for the List and click the OK button as shown below.

clip_image024

Wait for a while and your List page will be ready.

clip_image026

5. Using Central Administration set Permissions for external Content Type

Now you can try viewing the Customer Data list inside SharePoint.

clip_image028

On clicking the list, you will be seeing an “Access Denied by Business Data Connectivity” error message. To resolve this we need to set permission for the External Content Type.

Open the SharePoint Central Administration website. Click on Manage Service Applicatoins.

clip_image030

In the appearing page click on the Business Data Connectivity Services link as shown below:

clip_image032

In the appearing list, hover over the Customer Data item and click on the Set Permissions menu item as shown below.

clip_image034

You will get the following dialog.

clip_image036

Enter the user name, click the Add button and check all permissions. Click the OK button to close the wizard. (Make sure you are adding the username used to view SharePoint)

Now you are ready with the Permissions. Go back to the SharePoint > Customer Data list and you will be able to see the data as shown below.

 

Now you can try playing with the View/Edit/Delete features of the BCS list.

References

http://www.zimmergren.net/technical/access-denied-by-business-data-connectivity-solution

Summary

In this article we have seen how to create an External Content Type through Business Connectivity Services and view it inside SharePoint. In the real world scenario using BCS we can connect to WCF Services and other Business Applications like Microsoft CRM to view/update data inside SharePoint.

Posted in SharePoint | Tagged: , , , , , , | 2 Comments »

Windows Azure – BlockBlob PutBlock Method

Posted by JP on November 30, 2011

In this article we are discussing about uploading blob using PutBlock method. I would like to give a note that there are two types of blob in Windows Azure:

· Block Blob

· Page Blob

The Block Blob uploading is discussed here as Block Blobs are used for large file uploads. The associated code was developed to upload large files to Windows Azure Blob. The large file will be splitted into 4 MB chunks and then uploaded.

Method

Following are the important methods used:

· CloudBlockBlob.PutBlock()

· CloudBlockBlob.PutBlockList()

The PutBlock method is called for each 4MB file chunk and PutBlockList method is called at the end passing the file chunk ids.

Code

Following is the code of AzureBlobUtil.cs

public class AzureBlobUtil

{

private const int MaxBlockSize = 4000000; // Approx. 4MB chunk size

public Uri UploadBlob(string filePath, CloudStorageAccount account, string containerName)

{

byte[] fileContent = File.ReadAllBytes(filePath);

string blobName = Path.GetFileName(filePath);

return UploadBlob(fileContent, account, containerName, blobName);

}

public Uri UploadBlob(byte[] fileContent, CloudStorageAccount account, string containerName, string blobName)

{

CloudBlobClient blobclient = account.CreateCloudBlobClient();

CloudBlobContainer container = blobclient.GetContainerReference(containerName);

container.CreateIfNotExist();

CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

HashSet<string> blocklist = new HashSet<string>();

foreach (FileBlock block in GetFileBlocks(fileContent))

{

blob.PutBlock(

block.Id,

new MemoryStream(block.Content, true),

null

);

blocklist.Add(block.Id);

}

blob.PutBlockList(blocklist);

return blob.Uri;

}

private IEnumerable<FileBlock> GetFileBlocks(byte[] fileContent)

{

HashSet<FileBlock> hashSet = new HashSet<FileBlock>();

if (fileContent.Length == 0)

return new HashSet<FileBlock>();

int blockId = 0;

int ix = 0;

int currentBlockSize = MaxBlockSize;

while (currentBlockSize == MaxBlockSize)

{

if ((ix + currentBlockSize) > fileContent.Length)

currentBlockSize = fileContent.Length - ix;

byte[] chunk = new byte[currentBlockSize];

Array.Copy(fileContent, ix, chunk, 0, currentBlockSize);

hashSet.Add(

new FileBlock()

{

Content = chunk,

Id = Convert.ToBase64String(System.BitConverter.GetBytes(blockId))

});

ix += currentBlockSize;

blockId++;

}

return hashSet;

}

public Stream DownloadBlobAsStream(CloudStorageAccount account, string blobUri)

{

Stream stream = new MemoryStream();

CloudBlobClient blobclient = account.CreateCloudBlobClient();

CloudBlockBlob blob = blobclient.GetBlockBlobReference(blobUri);

if (blob != null)

blob.DownloadToStream(stream);

return stream;

}

public string DownloadBlobAsFile(CloudStorageAccount account, string blobUri)

{

Stream stream = DownloadBlobAsStream(account, blobUri);

string fileName = "Blob.file"; // Please change file name based on your need

if (stream != null)

{

FileStream fileStream = File.Create(fileName);

stream.Position = 0;

stream.CopyTo(fileStream);

fileStream.Close();

return fileName;

}

return string.Empty;

}

}

internal class FileBlock

{

public string Id

{

get;

set;

}

public byte[] Content

{

get;

set;

}

}

Testing Code

For uploading blob into the container use the following code:

// Upload

Uri blobUri = _blobUtil.UploadBlob(

filePathHere,

CloudStorageAccount.DevelopmentStorageAccount,

"files");

// Download

Stream stream = _blobUtil.DownloadBlobAsStream(

CloudStorageAccount.DevelopmentStorageAccount,

blobUri.ToString()

);


Associated Example

On running the example, after opening and uploading an image file, you can see the following result. The first box shows the source image. The second box shows the uploaded image from Azure.

clip_image002

Pre-Requisites

Please ensure the Storage Emulator is running while testing the example

Reference

You can find more information on Block and Page blob using following link:

http://msdn.microsoft.com/en-us/library/windowsazure/ee691964.aspx

Summary

In this article we have seen the usage of Block Blob upload as chunks. The source code can be used to upload large files to Azure Blob. The associated example can be downloaded along with this article. The utility method was verified with 100MB file upload and download.

Posted in Azure | Tagged: , , , , , , , , , | 2 Comments »

Lambda Expressions Extension Methods Series 11 -SequenceEqual()

Posted by JP on November 13, 2011

In this small article, I would like to introduce the SequenceEqual() method. This method is very handy to compare two IEnumerable and return a Boolean stating whether each elements of both IEnumerable are same or not.

Method: SequenceEqual()

Arguments: IEnumerable<>

Operates On: IEnumerable

Returns: True/False

Example

Let us have two lists of integers.

List 1 having

1

2

3

List 2 having

1

2

3

Here both the list are of same elements. We can use the SequenceEquals() method to view the result:

bool result1 = list1.SequenceEqual(list2);

Output

The output of the above code will be:

True

Code Explained

Here on calling the SequenceEquals() method, each element of list1 is compared with corresponding element of list2. The default Equals() comparison is exercised here.

Elements of primitive types will have value comparison and

Elements of class types will have reference comparison (unless they override the Equals() method)

Sample Code with int and object Scenarios

// Creating list of int

IList<int> list1 = new List<int>() { 1, 2, 3 };

IList<int> list2 = new List<int>() { 1, 2, 3 };

IList<int> list3 = new List<int>() { 4, 5, 6 };

bool result1 = list1.SequenceEqual(list2); // True

bool result2 = list1.SequenceEqual(list3); // False

// Creating employee objects

Employee employee1 = new Employee() { Id = 1, Name = “Employee1” };

Employee employee2 = new Employee() { Id = 2, Name = “Employee2” };

IList<Employee> list4 = new List<Employee>();

list4.Add(employee1);

list4.Add(employee2);

IList<Employee> list5 = new List<Employee>();

list5.Add(employee1);

list5.Add(employee2);

bool result3 = list4.SequenceEqual(list5); // True – As Same ref of Employee objects

The Employee class would be having following structure:

public class Employee

{

public int Id;

public double Salary;

public int Age;

public string Name;

public override string ToString()

{

return this.Id.ToString() + ” ” + this.Name;

}

}

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Methods Series 9 – OfType()

Posted by JP on November 13, 2011

Then Enumerable.cs provides extension method OfType(). It can be used to select elements in an IEnumerable based on the type.

Method: OfType()

Arguments: None (Has Generic Argument)

Operates On: IEnumerable

Example: We have a list of objects, containing integer, float, string and character items. The OfType() method can be used to get elements which are integer.

IList<object> list = new List<object>();

list.Add(1);

list.Add(1.1);

list.Add(2);

list.Add(2.2);

list.Add(“string”);

list.Add(‘c’);

In order to select the elements which are int – the following code can be used.

var result = list.OfType<int>();

Here the OfType() method takes an int generic argument.

Output

The output of the above code will be:

1

2

Code Explained

In the above code we are having the following elements as inputs:

Element

Type

1

Integer

1.1

Float

2

Integer

2.2

Float

“string”

String

‘c’

Character

Extension Method Snapshot

You can find the snapshot of OfType () method usage as provided by Visual Studio.

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Methods Series 10 – Min, Max, Sum, Average

Posted by JP on November 13, 2011

Lambda Expressions Extension Methods Series 10 – Min, Max, Sum, Average

The Extension Methods also include the following 4 calculation methods – Min, Max, Sum and Average() for calculating the minimum value, maximum value, sum and average respectively.

Method

Description

Min()

Calculates the minimum value in the series

Max()

Calculates the maximum value in the series

Sum()

Calculates the sum of the values

Average()

Calculates the average of the values

The above methods saves a lot of time and code by discarding the need of creating a variable and for loop to iterate through the elements to find the Minimum, Maximum, Sum and Average of the items.

Example

The sample list would be a list of integers from 1 to 6.

public InitializeLIst()

{

InitializeComponent();

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

The test code will be as following:

private void MinMaxSumAvgButton_Click(object sender, EventArgs e)

{

int min = _list.Min();

int max = _list.Max();

int sum = _list.Sum();

double average = _list.Average();

string message = “Min={0}\nMax={1}\nSum={2}\nAverage={3}”;

MessageBox.Show(string.Format(message, min, max, sum, average));

}

On execution of the code above we can see the output as below:

Extension Method Snapshot

You can find the snapshot of Min() method usage as provided by Visual Studio.

You can find the snapshot of Max() method usage as provided by Visual Studio.

You can find the snapshot of Sum() method usage as provided by Visual Studio.

You can find the snapshot of Average() method usage as provided by Visual Studio.

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 8 – Select() with Anonymous Type Creation

Posted by JP on November 13, 2011

Select() with Anonymous Type Creation


As a continuation of Select() method, we can have anonymous type creation as well.  The anonymous type are those without a name in our c# source code and the compiler will generate an automatic name for it.

It is convenient that we are free from creating a class and properties.  The following example shows

  • How to specify an anonymous class  in the Select Method
  • How to create the properties of anonymous class
  • How to retrieve the properties of anonymous class

Parameters: Input type and Transformation Method
Return Value: List of Items

Example

In the following example we are using a list of integers and converting them to a class having 2 properties:

  • Value which is the actual value of integer
  • Index which is the index of the element

The statement _list.Select((i, ix) => new { Value = i, Index = ix }) will do the job.

After converting we are storing the result in a var type.

For retrieving the properties back we use the same var keyword and iterate through a foreach.  The var type allows us to read the properties Value and Index with automatic type inference by IDE.

Code

private IList<int> _list = new List<int>();

  public InitializeList()
  {
  // Set data
  _list.Add(1);
  _list.Add(2);
  _list.Add(3);
  _list.Add(4);
  _list.Add(5);
  _list.Add(6); 
  }

  private void SelectAnonymousButton_Click(object sender, EventArgs e)
  {
  var result = _list.Select((i, ix) => new { Value = i, Index = ix });

  foreach (var v in result)  {
  string messsage = "Value={0} at Index={1}";
  MessageBox.Show(string.Format(messsage, v.Value, v.Index));
  }
  }

Input
1
2
3
4
5
6
Output
“Value=1 at Index=0”
“Value=2 at Index=1”
“Value=3 at Index=2”
“Value=4 at Index=3”
“Value=5 at Index=4”
“Value=6 at Index=5”
Extension Method Snapshot

You can find the snapshot of the Select() method usage as provided by Visual Studio.

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 7 – Select()

Posted by JP on November 13, 2011

Select() Extension Method

The Select() is a straight forward method. It converts the argument from one type to another type.

For eg: If we need to convert a list of integers to string, we can achieve that using Select() as given below.

Similarly we can use value types to custom class conversions, to anonymous type conversions etc.

Parameters: Input type and the Transform Functions

Return Value: List of Items

Example

In the following example we are using a list of integers and the Select() method to convert each elements in the list.

Code

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void SelectButton_Click(object sender, EventArgs e)

{

var result = _list.Select(a => a.ToString());

foreach (string s in result)

MessageBox.Show(s);

}

Input

1

2

3

4

5

6

Output

1

2

3

4

5

6

(Converted to string)

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 6 – SkipWhile()

Posted by JP on November 13, 2011

SkipWhile () Extension Method

The SkipWhile() is a tricky method. It takes one condition as argument and iterates over the elements. It will start returning the elements once the condition turned false. It will continue returning the elements until the end of the loop.

It is not similar to Where() condition. Let me give an example. We have 1, 2, 3, 4, 5, 6 in the list and given a condition SkipWhile(i => i != 5) it will return 5 and 6. The method works like below:

First it will take element 1 and as the condition is evaluated to true – it will skip the element.

It will go until element 5, and the condition turns false – then from current element onwards it will return all remaining elements.

Parameters: Condition

Return Value: List of Items

Example

In the following example we are using a list of integers and the Skip() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void SkipWhileButton_Click(object sender, EventArgs e)

{

/// SkipWhile method to get a sublist by skipping elements if condition is

/// true and continuing till end without checking condition.. Little tricky

var result = _list.SkipWhile(i => (i != 5));

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Input

1

2

3

4

5

6

Output

5

6

Extension Method Snapshot

You can find the snapshot of the SkipWhile() method usage as provided by Visual Studio.

Posted in C# | Tagged: , , | Leave a Comment »