Wednesday, June 18, 2008

To convert Text column to Date column format in Sharepoint column

Suppose you have a column(named,"DateText") with text format and the value it returning is of type datetime("2009-06-18T00:00:00"),
To convert it into datetime format(mm/dd/yyyy),

first create a calculated column named Expiration Date, with datatype as datetime and with the follwing formula:

=IF(ISNUMBER(FIND("T",[DateText])),TEXT(LEFT([DateText],FIND("T",[DateText])-1),"mm/dd/yyyy"),TEXT([DateText],"mm/dd/yyyy"))

Then create one more calculated column with DateTime data type and use the following formula:

=DATE(YEAR([Expiration Date]),MONTH([Expiration Date]),DAY([Expiration Date]))

Monday, June 16, 2008

Get current user roles in Sharepoint

string UserRoles = string.Empty;

SPSite SiteName = new SPSite(SITE_URL);

SPWeb web = SiteName.OpenWeb();

foreach (SPRole role in web.CurrentUser.Roles)
{
UserRoles += role.Name + ";";
}

Send an email with Attachment in C#.Net

Here is the method to send an attachment with mail.

using System.Web.Mail;

public string SendAttachmentEmail(string MailTo, string MailSubject, string MailBody, string AttachPDFPath, string MailFrom, string MailServer)
{
# region Email
try
{
try
{
MailMessage Message = new MailMessage();
Message.To = MailTo;
Message.From = MailFrom;
Message.Subject = MailSubject;
Message.Body = MailBody;
try
{
Message.Attachments.Add(new MailAttachment(AttachPDFPath));
}
catch (Exception ex)
{
return "Error while accessing attachemnt" + ex.ToString();
}
Message.BodyFormat = MailFormat.Html; //Specify mail format either text or html

try
{
SmtpMail.SmtpServer = MailServer; //Specify the exchange server name
SmtpMail.Send(Message);
return "true";
}
catch (System.Web.HttpException ehttp)
{
return ehttp.ToString();
}
}
catch (IndexOutOfRangeException ex)
{

return ex.ToString();
}
}
catch (System.Exception e)
{
return e.ToString();
}
# endregion
}

Generating PDFs in C#.Net using iTextSharp

//For PDF
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.rtf;

using System.Collections;

//Method to generate PDF in C#
private static void CreateStandardNdaPDF(string pdfFilePath, StandardNDAConfig ndaConfigData, NDA ndaUserData)
{

//Define memory stream
System.IO.MemoryStream PDFStream = new System.IO.MemoryStream();

//Create pdf document object
Document document = new Document();

try
{

//Create a document at physical location
PdfWriter pdfwr = PdfWriter.GetInstance(document, PDFStream);

#region Method to add current date on footer of the PDF document
Phrase phrCurrentDate = new Phrase(System.DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt"));
//RtfHeaderFooter footer = new RtfHeaderFooter();
HeaderFooter footer = new HeaderFooter(phrCurrentDate, false);
footer.Border = Rectangle.NO_BORDER;
footer.Alignment = HeaderFooter.ALIGN_RIGHT;

document.Footer = footer;

#endregion

// open the document
document.Open();

//Define Fonts
float SMALL_FONT = 8.0f;
float BIG_FONT = 9.5f;
float LEADING = 12.0f;

//Define fonts
Font fontNormal = FontFactory.GetFont(FontFactory.TIMES_ROMAN, SMALL_FONT, Font.NORMAL);
Font fontBold = FontFactory.GetFont(FontFactory.TIMES_ROMAN, SMALL_FONT, Font.BOLD);
Font fontUnderLine = FontFactory.GetFont(FontFactory.TIMES_ROMAN, SMALL_FONT, Font.UNDERLINE);
Font fontBoldUnderLine = FontFactory.GetFont(FontFactory.TIMES_ROMAN, SMALL_FONT, Font.BOLD Font.UNDERLINE);
Font fontNormalBigger = FontFactory.GetFont(FontFactory.TIMES_ROMAN, BIG_FONT, Font.NORMAL);
Font fontBoldBigger = FontFactory.GetFont(FontFactory.TIMES_ROMAN, BIG_FONT, Font.BOLD);
Font fontUnderLineBigger = FontFactory.GetFont(FontFactory.TIMES_ROMAN, BIG_FONT, Font.UNDERLINE);
Font fontBoldUnderLineBigger = FontFactory.GetFont(FontFactory.TIMES_ROMAN, BIG_FONT, Font.BOLD Font.UNDERLINE);

//To add New line to the PDF document
Phrase phrNewLine = new Phrase("\n");
Phrase phrTab = new Phrase("\t");
Phrase phrSpace = new Phrase(" ",fontNormal);

//Header Table for NDA Logo and NDA Address
Table ndaTable = new Table(2, 1); // 2 columns,1 row
ndaTable.BorderWidth = 0;
ndaTable.Border = Rectangle.NO_BORDER;
ndaTable.DefaultCellBorder = Rectangle.NO_BORDER;
ndaTable.WidthPercentage = 100;
ndaTable.Cellspacing = 2.0f;

//Define and Add NDA Logo

//Image ndaLogo = Image.GetInstance(new Uri(Server.MapPath("../homepagetopzoneimage.jpg")));
//Image ndaLogo = Image.GetInstance(new Uri("http://idc-dk-is:801/sites/nda/PictureLibrary/lg_mchp.gif"));
Image ndaLogo = Image.GetInstance(ndaConfigData.NDALogo);
ndaLogo.Alignment = Image.ALIGN_LEFT;

Cell cellNDALogo = new Cell(ndaLogo);
Phrase ndaLogoText = new Phrase(ndaConfigData.NDALogoText, fontNormal);
cellNDALogo.AddElement(ndaLogoText);
cellNDALogo.VerticalAlignment = Cell.ALIGN_LEFT;
cellNDALogo.HorizontalAlignment = Cell.ALIGN_LEFT;
cellNDALogo.Leading = LEADING;
ndaTable.AddCell(cellNDALogo);

//Define and Add NDA Address
Phrase ndaSerialNumber = new Phrase(ndaUserData.SerialNumber, fontBoldBigger);
Phrase phrParticipant = new Phrase("PARTICIPANT ", fontBoldBigger);
Phrase phrParticipantLegalNameOfCompany = new Phrase(ndaUserData.ParticipantLegalNameOfCompany, fontBoldBigger);
Phrase phrParticipantDetails = new Phrase();
phrParticipantDetails.Add(phrParticipant);
phrParticipantDetails.Add(phrParticipantLegalNameOfCompany);

//Phrase phrParticipantName = new Phrase(ndaUserData.ParticipantLegalNameOfCompany, fontUnderLine);
Phrase ndaCompanyName = new Phrase(ndaConfigData.CompanyName, fontBoldBigger);
Phrase ndaAddress = new Phrase(ndaConfigData.Address, fontNormalBigger);
Phrase ndaCityStateZip = new Phrase(ndaConfigData.CityStateZip, fontNormalBigger);
Phrase ndaPhone = new Phrase(ndaConfigData.Phone, fontNormalBigger);
Phrase ndaFax = new Phrase(ndaConfigData.FAX, fontNormalBigger);

Cell cellNDAAddress = new Cell();
Phrase phrNDAAddress = new Phrase();

phrNDAAddress.Leading = LEADING;
phrNDAAddress.Add(ndaSerialNumber);
phrNDAAddress.Add(phrNewLine);
phrNDAAddress.Add(phrParticipantDetails);
phrNDAAddress.Add(phrNewLine);
phrNDAAddress.Add(ndaCompanyName);
phrNDAAddress.Add(phrNewLine);
phrNDAAddress.Add(ndaAddress);
phrNDAAddress.Add(phrNewLine);
phrNDAAddress.Add(ndaCityStateZip);
phrNDAAddress.Add(phrNewLine);
phrNDAAddress.Add(ndaPhone);
phrNDAAddress.Add(phrNewLine);
phrNDAAddress.Add(ndaFax);
phrNDAAddress.Add(phrNewLine);

cellNDAAddress.Add(phrNDAAddress);

ndaTable.AddCell(cellNDAAddress);
cellNDAAddress.VerticalAlignment = Cell.ALIGN_LEFT;
cellNDAAddress.HorizontalAlignment = Cell.ALIGN_LEFT;
cellNDAAddress.UseAscender = true;
document.Add(ndaTable);
document.Add(phrNewLine);
document.Add(phrNewLine);

//Define and Add NDA Document Title
Paragraph parNDADocTitle = new Paragraph(ndaConfigData.NDADocTitle, fontBoldBigger);
parNDADocTitle.Alignment = 1;
parNDADocTitle.Add(phrNewLine);
parNDADocTitle.Add(phrNewLine);

document.Add(parNDADocTitle);
//document.Add(phrNewLine);
//document.Add(phrNewLine);

//Define and Add NDA Doc Effective Date
Paragraph parNDAEffectiveDate = new Paragraph();
Chunk chnEffectiveDate = new Chunk("EFFECTIVE DATE: ", fontBold);
parNDAEffectiveDate.Add(chnEffectiveDate);
DateTime dtEffective = Convert.ToDateTime(ndaUserData.EffectiveDate);
Chunk chnDateEffective = new Chunk(dtEffective.ToString("MMMM dd, yyyy"), fontBoldUnderLine);
parNDAEffectiveDate.Add(chnDateEffective);
parNDAEffectiveDate.Add(phrNewLine);
parNDAEffectiveDate.Add(phrNewLine);
document.Add(parNDAEffectiveDate);
//document.Add(phrNewLine);
//document.Add(phrNewLine);

//Define and Add NDA Header
Phrase phrNDAHeader = ReplaceHtmlText(ndaConfigData.Header, SMALL_FONT);
phrNDAHeader.Font = fontNormal;
phrNDAHeader.Leading = LEADING;
phrNDAHeader.Add(phrNewLine);
phrNDAHeader.Add(phrNewLine);
document.Add(phrNDAHeader);

Table ndaSecTable = new Table(2, 3); // 2 columns,3 rows
ndaSecTable.TableFitsPage = true;
ndaSecTable.Border = Table.NO_BORDER;
ndaSecTable.BorderColor = iTextSharp.text.Color.WHITE;
ndaSecTable.WidthPercentage = 100;

#region Sections

#region Amendment Section1
Phrase phrSecTitle1 = new Phrase(ndaConfigData.SecTitle1, fontBoldUnderLine);

Phrase phrSec1 = new Phrase(ReplaceHtmlText(ndaConfigData.Sec1, SMALL_FONT));
Phrase phrSec1Details = new Phrase();
phrSec1Details.Leading = LEADING;
Phrase phr1 = new Phrase("1. ", fontBold);
phrSec1Details.Add(phr1);
phrSec1Details.Add(phrSecTitle1);
phrSec1Details.Add(phrTab);
phrSec1Details.Add(phrSec1);
phrSec1Details.Add(phrNewLine);
//Display Note only if the section note is not empty
if (ndaConfigData.SecNote1 != "")
{
Phrase phrSecNote1 = new Phrase(ReplaceHtmlText(ndaConfigData.SecNote1, SMALL_FONT));
phrSec1Details.Add(phrSecNote1);
phrSec1Details.Add(phrNewLine);
phrSec1Details.Add(phrSecNote1);
}
phrSec1Details.Add(phrNewLine);

Cell cellNDASec1 = new Cell();
cellNDASec1.AddElement(phrSec1Details);
cellNDASec1.Border = Table.NO_BORDER;
cellNDASec1.VerticalAlignment = Cell.ALIGN_JUSTIFIED;
cellNDASec1.HorizontalAlignment = Cell.ALIGN_JUSTIFIED;

ndaSecTable.AddCell(cellNDASec1);

#endregion

#region Amendment Section2
Phrase phrSecTitle2 = new Phrase(ndaConfigData.SecTitle2, fontBoldUnderLine);
Phrase phrSec2 = new Phrase(ReplaceHtmlText(ndaConfigData.Sec2+ " ", SMALL_FONT));
Phrase phrDisclosingParty = new Phrase(ndaUserData.DisclosingParties,fontUnderLine);
Phrase phr2 = new Phrase("2. ", fontBold);
Phrase phrSec2Details = new Phrase();
phrSec2Details.Leading = LEADING;
phrSec2Details.Add(phr2);
phrSec2Details.Add(phrSecTitle2);
phrSec2Details.Add(phrTab);
phrSec2Details.Add(phrSec2);
phrSec2Details.Add(phrSpace);
phrSec2Details.Add(phrSpace);
phrSec2Details.Add(phrSpace);
phrSec2Details.Add(phrDisclosingParty);
phrSec2Details.Add(phrNewLine);

//Display Note only if the section note is not empty
if (ndaConfigData.SecNote2 != "")
{
Phrase phrSecNote2 = new Phrase(ReplaceHtmlText(ndaConfigData.SecNote2, SMALL_FONT));
phrSec2Details.Add(phrSecNote2);
phrSec2Details.Add(phrNewLine);
}
phrSec2Details.Add(phrNewLine);


Cell cellNDASec2 = new Cell();
cellNDASec2.AddElement(phrSec2Details);
cellNDASec2.Border = Table.NO_BORDER;
cellNDASec2.VerticalAlignment = Cell.ALIGN_JUSTIFIED;
cellNDASec2.HorizontalAlignment = Cell.ALIGN_JUSTIFIED;

ndaSecTable.AddCell(cellNDASec2);

#endregion

#region Amendment Section3
Phrase phrSecTitle3 = new Phrase(ndaConfigData.SecTitle3, fontBoldUnderLine);
Phrase phrSec3 = new Phrase(ReplaceHtmlText(ndaConfigData.Sec3, SMALL_FONT));

Phrase phrSec3Details = new Phrase();
phrSec3Details.Leading = LEADING;
Phrase phr3 = new Phrase("3. ", fontBold);
phrSec3Details.Add(phr3);
phrSec3Details.Add(phrSecTitle3);
phrSec3Details.Add(phrTab);
phrSec3Details.Add(phrSec3);

phrSec3Details.Add(phrNewLine);

Phrase phrSecLabelA3 = new Phrase(ReplaceHtmlText(ndaConfigData.SecLabelA3 + " ", SMALL_FONT));
Phrase phrMCHPrepresentative = new Phrase(ndaUserData.MCHPRepersentative, fontUnderLine);
//Phrase phrMCHPConfidentialInfo = new Phrase(ndaUserData.DescriptionOfConfidentialInformationMCHP, fontUnderLine);

Phrase phrSecLabelB3 = new Phrase(ReplaceHtmlText(ndaConfigData.SecLabelB3 + " ", SMALL_FONT));
Phrase phrParticipantRepresentative = new Phrase(ndaUserData.ParticipantRepersentative, fontUnderLine);
//Phrase phrParticipantConfidentialInfo = new Phrase(ndaUserData.DescriptionOfConfidentialInformationParticipant, fontUnderLine);

phrSec3Details.Add(phrSecLabelA3);
phrSec3Details.Add(phrMCHPrepresentative);
phrSec3Details.Add(phrNewLine);
phrSec3Details.Add(phrSecLabelB3);
phrSec3Details.Add(phrParticipantRepresentative);
phrSec3Details.Add(phrNewLine);
//Display Note only if the section note is not empty
if (ndaConfigData.SecNote3 != "")
{
Phrase phrSecNote3 = new Phrase(ReplaceHtmlText(ndaConfigData.SecNote3, SMALL_FONT));

phrSec3Details.Add(phrSecNote3);
phrSec3Details.Add(phrNewLine);
}
phrSec3Details.Add(phrNewLine);



Cell cellNDASec3 = new Cell();
cellNDASec3.AddElement(phrSec3Details);
cellNDASec3.Border = Table.NO_BORDER;
cellNDASec3.VerticalAlignment = Cell.ALIGN_JUSTIFIED;
cellNDASec3.HorizontalAlignment = Cell.ALIGN_JUSTIFIED;

ndaSecTable.AddCell(cellNDASec3);

#endregion

#endregion

document.Add(ndaSecTable);

//Table for Footer for MCHP and Participant
Table tblNDASignature = new Table(2, 1); // 2 columns,1 row
tblNDASignature.BorderWidth = 0;
tblNDASignature.Border = Rectangle.NO_BORDER;
tblNDASignature.DefaultCellBorder = Rectangle.NO_BORDER;
tblNDASignature.WidthPercentage = 100;
tblNDASignature.TableFitsPage = true;

//Define and Add MCHP Signature Details
Phrase phrMCHPSignatureTitle = new Phrase(ReplaceHtmlText(ndaConfigData.SignatureTitle1, BIG_FONT));
phrMCHPSignatureTitle.Font = fontBoldBigger;
Phrase phrAddress = new Phrase("Address: ", fontNormal);
Phrase phrMCHPBy = new Phrase("By: ", fontNormal);
Phrase phrMCHPPrintName = new Phrase("Print Name: ", fontNormal);
Phrase phrTitle = new Phrase("Title: ", fontNormal);
Phrase phrLine1 = new Phrase("_________________________________________________", fontNormal);
Phrase phrLine2 = new Phrase("__________________________________________", fontNormal);
Phrase phrLine3 = new Phrase("_______________________________________________", fontNormal);

Cell cellMCHPSignature = new Cell();
cellMCHPSignature.Leading = LEADING;

cellMCHPSignature.Add(phrMCHPSignatureTitle);
cellMCHPSignature.Add(phrNewLine);
cellMCHPSignature.Add(phrNewLine);
cellMCHPSignature.Add(phrNewLine);
cellMCHPSignature.Add(phrMCHPBy);
cellMCHPSignature.Add(phrLine1);
cellMCHPSignature.Add(phrNewLine);
cellMCHPSignature.Add(phrNewLine);
cellMCHPSignature.Add(phrMCHPPrintName);
cellMCHPSignature.Add(phrLine2);
cellMCHPSignature.Add(phrNewLine);
cellMCHPSignature.Add(phrNewLine);
cellMCHPSignature.Add(phrTitle);
cellMCHPSignature.Add(phrLine3);
cellMCHPSignature.Add(phrNewLine);
cellMCHPSignature.VerticalAlignment = Cell.ALIGN_LEFT;
cellMCHPSignature.HorizontalAlignment = Cell.ALIGN_LEFT;
tblNDASignature.AddCell(cellMCHPSignature);

//Define and Add Participant Signature Details
Phrase strParticipant = new Phrase(ReplaceHtmlText(ndaConfigData.Participant + " ", BIG_FONT));
strParticipant.Font = fontBoldBigger;
Phrase phrParticipantName = new Phrase(ndaUserData.ParticipantLegalNameOfCompany, fontUnderLine);
Phrase phrParticipantStreet = new Phrase(ndaUserData.ParticipantStreet + ", ", fontUnderLine);
Phrase phrParticipantCity = new Phrase(ndaUserData.ParticipantCity + ", ", fontUnderLine);
Phrase phrParticipantState = new Phrase(ndaUserData.ParticipantState + ", ", fontUnderLine);
Phrase phrParticipantCountry = new Phrase(ndaUserData.ParticipantCountry + ", ", fontUnderLine);
Phrase phrParticipantZip = new Phrase(ndaUserData.ParticipantPinCode, fontUnderLine);
Phrase phrParticipantAddress = new Phrase();
phrParticipantAddress.Add(phrParticipantStreet);
phrParticipantAddress.Add(phrParticipantCity);
phrParticipantAddress.Add(phrParticipantState);
phrParticipantAddress.Add(phrParticipantCountry);
phrParticipantAddress.Add(phrParticipantZip);
phrParticipantAddress.Font = fontUnderLine;

Cell cellParticipantSignature = new Cell();
cellParticipantSignature.Leading = LEADING;

cellParticipantSignature.Add(strParticipant);
cellParticipantSignature.Add(phrParticipantName);
cellParticipantSignature.Add(phrNewLine);
cellParticipantSignature.Add(phrAddress);
cellParticipantSignature.Add(phrParticipantAddress);
cellParticipantSignature.Add(phrNewLine);
cellParticipantSignature.Add(phrNewLine);
cellParticipantSignature.Add(phrMCHPBy);
cellParticipantSignature.Add(phrLine1);
cellParticipantSignature.Add(phrNewLine);
cellParticipantSignature.Add(phrNewLine);
cellParticipantSignature.Add(phrMCHPPrintName);
cellParticipantSignature.Add(phrLine2);
cellParticipantSignature.Add(phrNewLine);
cellParticipantSignature.Add(phrNewLine);
cellParticipantSignature.Add(phrTitle);
cellParticipantSignature.Add(phrLine3);
cellParticipantSignature.Add(phrNewLine);
cellParticipantSignature.VerticalAlignment = Cell.ALIGN_LEFT;
cellParticipantSignature.HorizontalAlignment = Cell.ALIGN_LEFT;
tblNDASignature.AddCell(cellParticipantSignature);


document.Add(tblNDASignature);
}
catch (DocumentException de)
{

}
finally
{
document.Close();
}


byte[] PdfByte = PDFStream.GetBuffer();
PDFStream.Flush();
PDFStream.Close();
NDACommonFunctions.UploadFile(PdfByte, pdfFilePath);
}

Method to search a user in Active Directory and get all the user information

The following method is used for searching a user in Active directory of an organization and fetch the user details like user name, email, phone number, department , manager etc.

Import following two web services,

using System.DirectoryServices;
using System.Collections.Generic;

public List SerachUserInDomain(string UserName)
{

string Name, Email, Manager, Extension, Department;

NDAUserInfo UserInfo;

const string MCHP_DIRECTORY_PATH = LDAP://microsoft.com/DC=microsoft,DC=com; //Provide the Active directory path from where user details to be fetched

List SearchResult = new List();

DirectorySearcher MchpDirSearch = new DirectorySearcher(); //Create an object of DirectorySearcher

MchpDirSearch.Filter = "(&(objectCategory=person)(objectClass=user)(cn=*" + UserName + "*))"; //Add the filter condition

try
{
SearchResultCollection DirectorySearchResult = MchpDirSearch.FindAll(); // Searches AD for the filter condition and returns the result

int SearchResultCount = DirectorySearchResult.Count;

//AD may contain multiple users with the same name, it will return mutliple rows
for (int i = 1; i <= SearchResultCount; i++)
{
//get user name
Name = DirectorySearchResult[i - 1].Properties["cn"][0].ToString();

//get user email
Email = DirectorySearchResult[i - 1].Properties["mail"][0].ToString();

//get user manager name
Manager = DirectorySearchResult[i - 1].Properties["manager"][0].ToString();
if (Manager != "")
{
if (Manager.Contains("CN="))
{
int Length = Manager.IndexOf(',');
Manager = Manager.Substring(3, Length - 3);
}
else
{
Manager = string.Empty;
}
}

//get user Department name
Department = DirectorySearchResult[i - 1].Properties["department"][0].ToString();

//get user extension
Extension = DirectorySearchResult[i - 1].Properties["telephonenumber"][0].ToString();

//add the results into an userinfo object
UserInfo = new NDAUserInfo();
UserInfo.UserName = Name;
UserInfo.UserEmail = Email;
UserInfo.UserManager = Manager;
UserInfo.UserExtension = Extension;
UserInfo.UserDepartment = Department;

SearchResult.Add(UserInfo);

//To sort user names if it contains multiple users
if (DirectorySearchResult[i - 1].Properties["samaccountname"][0].ToString() == UserName)
{
for (int c = SearchResult.Count - 1; c > 0; c--)
{
SearchResult[c] = SearchResult[c - 1];
}
SearchResult[0] = UserInfo;
}
return SearchResult;
}

For the above method, NDAUserInfo is a class with properties UserName, UserEmail, UserDepartment, UserExtension, UserManager

How to open a document file in Sharepoint document library and load into an XML?

SPSite site = new SPSite(siteurl); //To get the site collection -http://localhost:801/sites/NDA - Sharepoint Site URL
SPWeb web = site.OpenWeb(); // To get the site
SPList list = web.Lists[DocLibraryName];//To get the list with the given list name -UBA - Document Library Name
//Loop through each item in the document library
foreach (SPListItem listitem in list.Items)
{
SPFile file = listitem.File; //get the list item
byte[] binaryFile = file.OpenBinary(); // open the list item and add it to binary file
MemoryStream inStream = new MemoryStream(binaryFile); //Load the binary file into memory stream
XmlTextReader reader = new XmlTextReader(inStream);
XmlDocument xd = new XmlDocument();
xd.Load(reader); // Load the document into an xml file
reader.Close();
inStream.Close();
}