Tuesday, November 24, 2009

Sharepoint Tips n Tricks - Part 2

In continuation with earlier post -
Sharepoint Tips n Tricks

1) Check whether a given SPField exist or not before fetching value from it:


string columnValue = string.Empty;
string columnInternalName = string.Empty;
string fieldName = "Myfield";
SPListItem listItem; //Code to get SPListItem

//Check required SPField exist or not
if (listItem.ParentList.Fields.ContainsField(fieldName))
{
//Get internal name of SPField
columnInternalName = listItem.ParentList.Fields[fieldName].InternalName;

//Fetch column value based on internal name
if (listItem[columnInternalName] != null)
columnValue = listItem[columnInternalName].ToString();
}



2) SharePoint 2007 recommended guidelines for managing site collections, site, lists, and documents according to business needs:

· 50,000 site collections per content database

· 500 MB per site collection (default quota maximum)

· 50 MB file size limit (recommended) up to 2 GB (maximum)

· 2000 items per list view


3) Check whether page is in Edit Mode or not


if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Display)
{
// your code to support display mode
}
else if(Microsoft.SharePoint.SPContext.Current.FormContext.FormMode = SPControlMode.Edit)
{
// your code to support edit mode
}


OR


WebPartManager wp = WebPartManager.GetCurrentWebPartManager(Page);

if (wp.DisplayMode == WebPartManager.BrowseDisplayMode)
btnLink.InnerText = "Edit Page";
else if (wp.DisplayMode == WebPartManager.DesignDisplayMode)
btnLink.InnerText = "Exit Edit Mode";
else
btnLink.Visible = false;



Reference...
http://www.codeproject.com/KB/sharepoint/SwitchWPMode.aspx

http://mystepstones.wordpress.com/2008/09/23/detecting-the-current-mode-displayedit/


4) SPFeature to deploy page in a SharePoint site


Feature.xml
<?xml version="1.0" encoding="utf-8"?>
<Feature Id="f08674ee-2b0e-41aa-8d28-24e788d03c11"
Title="PageDeployment"
Description="Description for PageDeployment"
Version="12.0.0.0"
Hidden="FALSE"
Scope="Web"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="elements.xml"/>
<ElementFile Location="MyPage.aspx" />
</ElementManifests>
</Feature>


Elements.xml
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="Pages" Path="" Url="">
<File Name=" MyPage.aspx" Url=" MyPage.aspx" IgnoreIfAlreadyExists="FALSE" NavBarHome="True"></File>
</Module>
</Elements>

Code to download document from SharePoint Document Library

Following code snippet demonstrate the way to download a MS Word document (or any file) from SharePoint SPDocumentLibrary-


string siteURL = "http://localhost:80/"; //Write valid site URL
//Get SPSite and SPWeb instance
using (SPSite spSite = new SPSite(sireURL))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
//Get time stamp to download file with unique name
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");

//Get folder path
string directoryPath =
Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData),
"MyFolder");

//Create directory if it not exist
if (!(Directory.Exists(directoryPath)))
{
Directory.CreateDirectory(directoryPath);
}

//Get template url
string documentUrl; //Write valid document URL

//Download file in file system
SPFile myFile = spWeb.GetFile(documentUrl);
byte[] binFile = myFile.OpenBinary();

//Generate file name
filename = Path.Combine(directoryPath, strFileName + ".doc");

//Do file write operation
FileStream fs =
new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(binFile);
bw.Close();
}
}

MSMQ operations in C#

Following code snippet demonstrate the way to do some common operations with Microsoft Message Queuing (MSMQ)-

1) Send message in MSMQ -


string queueName = @".\Private$\MyMSMQ";
string myMessage = "Hello World";
MessageQueue messageQueue = null;
Message oMsg = null;

//Sending Messages to MSMQ
if (MessageQueue.Exists(queueName))
{
messageQueue = new MessageQueue(queueName);

oMsg = new Message(myMessage);
messageQueue.Send(oMsg);
}
else
{
//Create the MessageQueue
messageQueue = MessageQueue.Create(queueName);
//Set Queue permission
//messageQueue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl,
// AccessControlEntryType.Set);
messageQueue.SetPermissions("Everyone",
MessageQueueAccessRights.PeekMessage |
MessageQueueAccessRights.ReceiveMessage |
MessageQueueAccessRights.DeleteMessage |
MessageQueueAccessRights.WriteMessage,
AccessControlEntryType.Set);

oMsg = new Message(myMessage);
messageQueue.Send(oMsg);
}



2) Receive Message from MSMQ -


string myMessage= string.Empty;
string queueName = @".\Private$\MyMSMQ";

//Receiving Messages from MSMQ
MessageQueue messageQueue = new MessageQueue(queueName);

//To keep a check that if no messages present in MSMQ,
//control should return back in 1 second.
TimeSpan timeout = new TimeSpan(1);
Message message = null;

//Get all the messages present in the MSMQ and iterate through it.
MessageEnumerator enumerator = messageQueue.GetMessageEnumerator2();

if (enumerator.MoveNext())
message = enumerator.RemoveCurrent(timeout);

if (message != null)
{
messageBody = message.Body.ToString();
}




3) Display all the messages present in the MSMQ (without removing messages from queue)


StringBuilder allMessages = new StringBuilder();
string queueName = @".\Private$\MyMSMQ";

//Enumerating Messages from MSMQ
MessageQueue oMq = new MessageQueue(queueName);

foreach (Message message in oMq)
{
stringBuilder.Append(message.Body + ";");
}



4) Deletes all the messages contained in the MSMQ queue


string queueName = @".\Private$\MyMSMQ";

//Deletes all the messages contained in the MSMQ queue
MessageQueue messageQueue = new MessageQueue(queueName);
messageQueue.Purge();



Nice link to refer -
Use Microsoft Message Queuing in C# for inter-process communication

Thursday, October 8, 2009

Code to add SPUser in SPGroup

Following code snippet demonstrate the way to programmatically add SPUser in SPGroup...





try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSiteTemp = new SPSite(SPContext.Current.Web.Url))
using (SPWeb spWebTemp = spSiteTemp.OpenWeb())
{
spWebTemp.AllowUnsafeUpdates = true;

SPGroup spGroup = spWebTemp.SiteGroups["MySPGroup"];

SPUser spUser = spWebTemp.EnsureUser("DomainName\" + msUser.UserName);

//Adding group name in temporary arraylist to check SPUser's existing group.
ArrayList arrayListGroups = new ArrayList();
foreach (SPGroup tempGroup in spUser.Groups)
{
arrayListGroups.Add(tempGroup.Name.ToLower());
}

if ((spUser.Groups.Count < 1)
|| ((spUser.Groups.Count > 1)
&& (!arrayListGroups.Contains("myspgroup"))))
{
spGroup.AddUser(spUser);
}

spWebTemp.AllowUnsafeUpdates = false;
}
});
}
catch (SPException)
{
throw;
}


Populate SharePoint's SPList with records from MSExcel file

In this post, I will focus on the way to retrieve the records from MS Excel file and then populate it in SPList of SharePoint.


Code snippet(comments are self-explainatory)...


int count = 0;
try
{
SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
using (var spSite = new SPSite(SPContext.Current.Site.ID, sysToken))
{
using (var spWeb = spSite.OpenWeb(SPContext.Current.Web.ID))
{
//Get Interviewers SPList
SPList oList = spWeb.Lists["ListName"];

#region uploading Excel

//Here for saving file in FileSystem, creating time stamp
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
//FileUpload file;
string strFileType
= System.IO.Path.GetExtension(file.PostedFile.FileName)
.ToString().ToLower();

//Check file type
if (strFileType == ".xls" || strFileType == ".xlsx")
{
//Create Directory specified in parameter for downloading
string directoryPath
= HttpContext.Current.Server.MapPath("~/UploadedExcel");

if (!(System.IO.Directory.Exists(directoryPath)))
{
System.IO.Directory.CreateDirectory(directoryPath);
}

//Save file in FileSystem
file.SaveAs(HttpContext.Current.Server.
MapPath("~/UploadedExcel/" + strFileName + strFileType));
}
else
{
throw new FormatException("Only excel file is allowed");
}

string strNewPath
= HttpContext.Current.Server.MapPath("~/UploadedExcel/" +
strFileName + strFileType);

//Connection String to Excel Workbook
string connectionString = string.Empty;
if (strFileType.Trim() == ".xls")
{
connectionString
= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
strNewPath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connectionString
= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
strNewPath +
";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}


OleDbConnection conn = new OleDbConnection(connectionString);
//This will open excel file
conn.Open();
//Get the Excel Sheet name from Config
string sheetName = "Sheet1";
if (!string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.
AppSettings["ExcelSheetName"]))
{
sheetName = System.Configuration.ConfigurationSettings.
AppSettings["ExcelSheetName"];
}

string strSQL = "SELECT * FROM [" + sheetName + "$]";

OleDbCommand cmd = new OleDbCommand(strSQL, conn);
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);

spWeb.AllowUnsafeUpdates = true;
SPListItem listItem = null;

foreach (DataRow dr in ds.Tables[0].Rows)
{
//Create new SPListItem
listItem = oList.Items.Add();

listItem["FirstName"]
= dr["First Name"] != null ? dr["First Name"].ToString() : null;
listItem["LastName"]
= dr["Last Name"] != null ? dr["LastName"].ToString() : null;

listItem.Update();

listItem = null;
}

spWeb.AllowUnsafeUpdates = false;

conn.Close();
//Delete the saved excel file from FileSystem
System.IO.File.Delete(strNewPath);

#endregion

//Increment the record count
count = oList.Items.Count;
}
}

return count;
}
catch (SPException)
{
throw;
}

Google