Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, January 2, 2013

Get SPUser Object from SPListItem

Sometimes, you need to get SPUser object(to retrieve email, name,...) , however you have only SPListItem with SPFieldCollection. When you try to retrieve it, for example:


var field = item["user"]


you just get  a string with User ID , like : "123;#"

We need to cast this object to SPFieldUserValue.

This C# code can help us:



public SPUser GetSPUserObject(SPListItem spListItem, String fieldName)
    {
        SPUser spUser = null;
        try
        {
            if (fieldName != string.Empty)
            {
                SPFieldUser field = spListItem.Fields[fieldName] as SPFieldUser;
                if (field != null && spListItem[fieldName] != null)
                {
                    SPFieldUserValue fieldValue = field.GetFieldValue(spListItem[fieldName].ToString()) as SPFieldUserValue;
                    if (fieldValue != null)
                    {
                        spUser = fieldValue.User;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return spUser;
    }


Sunday, August 12, 2012

Create List Definition for Picture Library - C#


If you want to do it in Visual Studio, you're unable to see this definition in the drop down list. However it is very easy to do it:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint; 

namespace Console
{
    class Program
    {
        string listName = "Picture Library";
        string description = "My  Picture Library "; 

        public static void Main(string[] args)
        {
            using (SPSite oSite = new SPSite("http://contoso.com"))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oWeb.Lists.TryGetList(listName) != null)
                    {
                        // SPListTemplate class - Used to represent the list definition or a list template 
                        // oWeb.ListTemplates - Used to get the "Picture Library" list template
      
                        SPListTemplate oTemplate = oWeb.ListTemplates["PictureLibrary"];

                        //Creates a new list with Title, Descrription and List Template "Picture Library" type

                        oWeb.Lists.Add(listName, description, oTemplate);
                    }
                    else
                    {
                        System.Console.WriteLine(listName + " already exists in the " + oWeb.Title + " site");
                        System.Console.ReadLine();
                    }
                }
            }
        }
    }
}

Monday, July 9, 2012

Create and Retrieve a Social Comment - C#

The SocialCommentManager object enables you to create a social comment for any specified URL. This topic demonstrates how to use the SocialCommentManager to create and retrieve social comments in a custom application.

Creating Social Comments using c#:


using (SPSite site = new SPSite("http://contoso"))
{
SPServiceContext context = SPServiceContext.GetContext(site);
SocialCommentManager mySocialCommentManager = new SocialCommentManager(context);
mySocialCommentManager.AddComment(new Uri("My URL"), “My Comment”);
}



Retrieving Social Comments using c#:


public class PageComments
{
public string Comment { get; set; }
public UserProfile CommentOwner { get; set; }
public DateTime CommentDate { get; set; }
}


public class GetCommentsClass
{

public PageComments GetCommentsByPage(SPListItem item,int prevDates)
{
PageComments pc = new PageComments();

SocialCommentManager mySocialCommentManager = new SocialCommentManager(context);
SocialComment[] comments = mySocialCommentManager.GetComments(new Uri(Site + "/" + item.File.Url));

foreach (SocialComment comment in comments)
{
if (comment.LastModifiedTime.ToLocalTime().CompareTo(DateTime.Now.AddDays(previousDates)) >= 0)
{
pc.Comment = comment.Comment;
pc.CommentDate = comment.LastModifiedTime;
pc.CommentOwner = comment.Owner;

}
}

return pc;
}
}


Monday, June 18, 2012

How to delete the deployed Event Receiver in Sharepoint server 2010 By C#

I took it from this article




private void DeleteEventReceiverFromAList(string siteUrl)
{
using (SPSite site = new SPSite(siteUrl))
{
using(SPWeb web = site.OpenWeb())
{
try
{
SPList list = web.Lists["myList"];
if (list != null)
{
string className = "EventReceiverClass";
string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1111111111111111";
web.AllowUnsafeUpdates = true;
int receivers = list.EventReceivers.Count;
bool isAddedReceiverExist = false;
bool isUpdatedReceiverExist = false;
for (int i = 0; i < receivers; i++)
{
SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
{
eventReceiver.Delete();
break;
}
}
}
}
catch { }
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
}

Thursday, June 7, 2012

New feature of .NET Framework 4.5 - Await

Most of us , who uses Silverlight Client Object Model has encountered with the problems of asynchronous programming by the Microsoft blog : Async in 4.5: Worth the Await.
I just took a piece of code from this blog, to show how it makes our lives easier :)

Synchronous example:


public static void CopyTo(Stream source, Stream destination)
{
byte[] buffer = new byte[0x1000];
int numRead;
while((numRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
destination.Write(buffer, 0, numRead);
}
}


Asynchronous Programming Model:


public static IAsyncResult BeginCopyTo(Stream source, Stream destination)
{
var tcs = new TaskCompletionSource();

byte[] buffer = new byte[0x1000];
Action readWriteLoop = null;
readWriteLoop = iar =>
{
try
{
for (bool isRead = iar == null; ; isRead = !isRead)
{
switch (isRead)
{
case true:
iar = source.BeginRead(buffer, 0, buffer.Length, readResult =>
{
if (readResult.CompletedSynchronously) return;
readWriteLoop(readResult);
}, null);
if (!iar.CompletedSynchronously) return;
break;

case false:
int numRead = source.EndRead(iar);
if (numRead == 0)
{
tcs.TrySetResult(true);
return;
}
iar = destination.BeginWrite(buffer, 0, numRead, writeResult =>
{
try
{
if (writeResult.CompletedSynchronously) return;
destination.EndWrite(writeResult);
readWriteLoop(null);
}
catch(Exception e) { tcs.TrySetException(e); }
}, null);
if (!iar.CompletedSynchronously) return;
destination.EndWrite(iar);
break;
}
}
}
}
catch(Exception e) { tcs.TrySetException(e); }
};
readWriteLoop(null);

return tcs.Task;
}

public static void EndCopyTo(IAsyncResult asyncResult)
{
((Task)asyncResult).Wait();
}



New C# language async support:


public static async void CopyToAsync(Stream source, Stream destination)
{
byte[] buffer = new byte[0x1000];
int numRead;
while((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await destination.WriteAsync(buffer, 0, numRead);
}
}


Tuesday, May 22, 2012

Set user permissions to SPList

Sometimes I need to set permissions for special SPUser to special SPList.
Therefore , I developed winform solution, which helps me.

First of all, I use BackgroundWorker just to execute the operation on a separated thread.
Second, I aggregate fields from the form, which help me to bring a relevant data:
SiteURL - www.contoso.com
List - myList
ItemField - SPField("Display Name") For example item["ModifiedBy"]
ItemField Text - For example item["ModifiedBy"] = "Victor"
User - I use SPWeb.EnsureUser






using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace GivenPermissions
{
public partial class Form1 : Form
{

BackgroundWorker bg2 = new BackgroundWorker();

public Form1()
{
InitializeComponent();
}

private void btnRun_Click(object sender, EventArgs e)
{
bg2.DoWork += new DoWorkEventHandler(bg2_DoWork);
bg2.ProgressChanged += new ProgressChangedEventHandler(bg2_ProgressChanged);
bg2.RunWorkerAsync();
}

private void bg2_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{

}




void bg2_DoWork(object sender, DoWorkEventArgs e)
{
try
{
using (SPSite site = new SPSite(txtSiteUrl.Text))
{
using (SPWeb web = site.OpenWeb())
{

SPList list = web.Lists[txtList.Text];

SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";


SPListItemCollection col = list.GetItems(query);

foreach (SPListItem item in col)
{
if (item[txtItemField.Text] != null && string.Compare(item[txtItemField.Text].ToString(), txtItemFielText.Text) == 0)
{


SPUser user = web.EnsureUser(txtUser.Text);
SPRoleType roleType = SPRoleType.Contributor;


SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)user);
SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);

roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
item.RoleAssignments.Add(roleAssignment);

item.Update();

}
}


}
}




if (txtMessage.InvokeRequired)
{
txtMessage.Invoke(new MethodInvoker(delegate
{


txtMessage.AppendText("DONE ! ! !");



}));
}
}
catch (Exception ex)
{
if (txtMessage.InvokeRequired)
{
txtMessage.Invoke(new MethodInvoker(delegate
{

txtMessage.AppendText(ex.Message + "\n" + ex.StackTrace);

}));
}
}



}
}
}


Wednesday, September 16, 2009

The Greatest Exception Handling

public static class CheckYourNumber
{
public static ApplicationException EvenOrOdd(int integer)
{
if (integer % 2 == 0)
{
return new ApplicationException(“The integer is even.”);
}
else
{
return new ApplicationException(“The integer is odd.”);
}
}
}

protected void Button_Click(object sender, EventArgs e)
{
try
{
throw CheckYourNumber.EvenOrOdd(Convert.ToInt32(txtIntToTest.Text));
}
catch (ApplicationException ex)
{
lblResult.Text = ex.Message;
}
}

I loved it :)