Friday, October 2, 2009

Connect to CRM 1.2

#region "Connect to CRM 1.2"
///
/// This fucntion will connect to CRM 1.2
///

/// After sucessfully connection it will return CRM 1.2 user authentication
private Microsoft.CRM.Proxy.CUserAuth connectToCRM()
{
// BizUser proxy object
Microsoft.CRM.Proxy.BizUser bizUser = new Microsoft.CRM.Proxy.BizUser();
bizUser.Credentials = new System.Net.NetworkCredential(userName, password, domain);
bizUser.Url = strDir + "BizUser.srf";

try
{
userAuth = bizUser.WhoAmI();
//MessageBox.Show("Sucessfully connected to CRM 1.2");
}
catch (System.Web.Services.Protocols.SoapException ex)
{
MessageBox.Show("Unable to connect to CRM 1.2, Please check CRM 1.2 details.", ex.Message.ToString());
return null;
}

return userAuth;
}

#endregion

Download file form web / IE without Save/Open dialog box

string url = "http://"; // Download File path
System.Net.WebClient myWebClient = new System.Net.WebClient();
myWebClient.Credentials = new System.Net.NetworkCredential("User Name", "Password", "Domain");

string sFile ="C:\\"; //Path to save file

myWebClient.DownloadFile(url, sFile);

Update / Set CRM Opportunity State/ Status

public bool UpdateOpportunityState(Guid activityid, string astatuscode, string astatecode)
{

CrmService Crm4_service = connect();
try
{
if (astatecode == "Open")
{
SetStateOpportunityRequest state = new SetStateOpportunityRequest();

if (astatuscode == "1")
{
return true;
}
else if (astatuscode == "2")
{
state.OpportunityState = OpportunityState.Open;
state.OpportunityStatus = 2;/// Convert.ToInt32();
}

state.EntityId = activityid;
SetStateOpportunityResponse stateSet = (SetStateOpportunityResponse)Crm4_service.Execute(state);

return true;
}



opportunity src_opp = (opportunity)Crm4_service.Retrieve(EntityName.opportunity.ToString(), activityid, new AllColumns()); // = OpportunityState.Lost;


opportunityclose opp_close = new opportunityclose();
opp_close.actualrevenue = src_opp.actualvalue;
opp_close.opportunityid = new Lookup();
opp_close.opportunityid.Value = src_opp.opportunityid.Value;
opp_close.actualend = src_opp.actualclosedate;
opp_close.statuscode = src_opp.statuscode;
if (astatuscode == "3")
{
// this Opportunity was won
WinOpportunityRequest opp_won = new WinOpportunityRequest();
opp_won.OpportunityClose = opp_close;
opp_won.Status = 3;// src_opp.statuscode.Value;
Crm4_service.Execute(opp_won);
return true;
}
else
{
// this Opportunity was lost
LoseOpportunityRequest opp_lost = new LoseOpportunityRequest();
opp_lost.OpportunityClose = opp_close;
if (astatuscode == "4")
{
opp_lost.Status = 4;// src_opp.statuscode.Value;
}
else
{
opp_lost.Status = 5;// src_opp.statuscode.Value;

}
Crm4_service.Execute(opp_lost);
return true;
}

}
catch (System.Web.Services.Protocols.SoapException ex)
{
return false;
}

return true;


}

Update / Set CRM Invoice Status/ state

internal bool updateInvioceState(Guid InvioceId, string statusCode, string stateCode)
{
try
{
CrmService Crm4_service = connect();
SetStateInvoiceRequest state = new SetStateInvoiceRequest();

if (stateCode == "Active")
{
state.InvoiceState = InvoiceState.Active;
}
else if (stateCode == "Canceled")
{
state.InvoiceState = InvoiceState.Canceled;
}
else if (stateCode == "Closed")
{
state.InvoiceState = InvoiceState.Closed;
}
else if (stateCode == "Paid")
{
state.InvoiceState = InvoiceState.Paid;
}

state.InvoiceStatus = Convert.ToInt32(statusCode);
state.EntityId = InvioceId;
SetStateInvoiceResponse stateSet = (SetStateInvoiceResponse)Crm4_service.Execute(state);

}
catch (System.Web.Services.Protocols.SoapException ex)
{
return false;
}
return true;
}

Tuesday, September 22, 2009

Update/ Set AccountStateInfo in CRM 4.0 / 3.0

private bool UpdateAccountState(Guid accid, string astatuscode, string astatecode)
{
bool checkflag = false;
try
{
CrmService Crm4_service = connect();
// Create the request object.
SetStateAccountRequest state = new SetStateAccountRequest();

// Set the properties of the request object.
if (astatecode == "Inactive")
{
state.AccountState = AccountState.Inactive;
}
if (astatecode == "Active")
{
state.AccountState = AccountState.Active;
}
state.AccountStatus = Convert.ToInt32(astatuscode);

// EntityId is the GUID of the account whose state is being changed.
state.EntityId = accid;

// Execute the request.
SetStateAccountResponse stateSet = (SetStateAccountResponse)Crm4_service.Execute(state);
checkflag = true;
}
catch
{
return checkflag;
}
return checkflag;
}

Saturday, July 18, 2009

Send Email Activity using template from CRM 3.0 / 4.0 using C#

private void SendEmailFromTemplate()
{
CrmService service = connect();
// Create the 'From:' activity party for the email
activityparty fromParty = new activityparty();
fromParty.partyid = new Lookup();
fromParty.partyid.type = EntityName.systemuser.ToString();
fromParty.partyid.Value = new Guid("4D52A946-AE37-DE11-B372-000C29DF4A76");

// Create the 'To:' activity party for the email
activityparty toParty = new activityparty();
toParty.partyid = new Lookup();
toParty.partyid.type = EntityName.account.ToString();
toParty.partyid.Value = new Guid("B835890F-E23E-DE11-ACC7-000C29DF4A76");

// Create an email message.
email email = new email();

// Set email properties
email.to = new activityparty[] { toParty };
email.from = new activityparty[] { fromParty };
email.subject = "SDK Sample email";
email.description = "SDK Sample for SendEmailFromTemplate Message.";

CrmBoolean direction = new CrmBoolean();
direction.Value = true;
email.directioncode = direction;

TargetSendFromTemplateEmail emailTemplateTarget = new TargetSendFromTemplateEmail();
emailTemplateTarget.Email = email;

SendEmailFromTemplateRequest emailRequest = new SendEmailFromTemplateRequest();
emailRequest.Target = emailTemplateTarget;

// The regarding Id is requried and must be of the same type as the Email Template
emailRequest.RegardingId = new Guid("B835890F-E23E-DE11-ACC7-000C29DF4A76");
emailRequest.RegardingType = EntityName.account.ToString();

// Use a built-in email template of type "contact".
emailRequest.TemplateId = new Guid("B6C38BB9-2423-471D-8B38-E3B99ED80E7A");

SendEmailFromTemplateResponse emailResponse = (SendEmailFromTemplateResponse)service.Execute(emailRequest);
}

Send saved email activity / Message form crm 4.0 / 3.0

private void SendEmail(Guid emailActId)
{

#region Create and SendEmail request.
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailActId;
req.TrackingToken = "";
req.IssueSend = true;

// Send the email message.
SendEmailResponse res = (SendEmailResponse)service.Execute(req);
#endregion

}

Friday, July 17, 2009

Add / Upload attachment to Email activity in CRM 4.0/ 3.0

public void AddAttachmentToEmailActivity(string emailActId, string PDFFileNameName)
{
//Add an attachment
string currentPath = txtPath.Text;
Directory.SetCurrentDirectory(currentPath );

// Check to see if File exists
activitymimeattachment attachment = new activitymimeattachment();

if (File.Exists(currentPath + "\\" + PDFFileNameName.ToString() + ".pdf"))
{
// Get mimeType for File extension
string ext = System.IO.Path.GetExtension(currentPath + "\\" + PDFFileNameName.ToString() + ".pdf").ToLower();
string mimeType = string.Empty;
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();

//New Filestream Code for MS Word .doc and .docx extensions and PDF files .pdf extension
FileInfo pointer = new FileInfo(currentPath + "\\" + PDFFileNameName.ToString() + ".pdf");
FileStream fileStream = pointer.OpenRead();
byte[] byteData = new byte[(int)fileStream.Length];
fileStream.Read(byteData, 0, (int)fileStream.Length);
string encodedData = System.Convert.ToBase64String(byteData);
fileStream.Flush();
fileStream.Close();

attachment.activityid = new Lookup();
attachment.activityid.Value =new Guid(emailActId);
attachment.activityid.type = EntityName.email.ToString();
attachment.filename = PDFFileNameName.ToString() + ".pdf";
attachment.attachmentnumber = new CrmNumber();
attachment.attachmentnumber.Value = 1;
attachment.body = encodedData;
attachment.mimetype = mimeType;

service = CLM_CRM_Service.GetCrmService();

// Create the Attachment in CRM.
Guid attachmentId = service.Create(attachment);

}

}

Create Email activity for CRM 4.0 form C#.net

public void CreateEmailActivity(string accountId, string PDFFileNameName, string invoiceId)
{
string[] splitName = PDFFileNameName.Split('-'); //Larry & Susan Craven - Invoice Processed For Month - Jan 2009.pdf
string[] splitExt = splitName[2].Split('.');
service = CLM_CRM_Service.GetCrmService();
email actpointer = new email();
actpointer.subject = "Christian Life Ministry - " + splitName[1].ToString() + " - " + splitExt[0].ToString();
actpointer.description = "body";

Guid ow = new Guid(ownerID.ToString());
actpointer.ownerid = new Owner();
actpointer.ownerid.type = EntityName.systemuser.ToString();
actpointer.ownerid.Value = ow;
activityparty party = new activityparty();
party.partyid = new Lookup();
party.partyid.type = EntityName.systemuser.ToString();
party.partyid.Value = ow;
actpointer.from = new activityparty[] { party };
Guid ow1 = new Guid(accountId.ToString());
activityparty party1 = new activityparty();
party1.partyid = new Lookup();
party1.partyid.type = EntityName.account.ToString();
party1.partyid.Value = ow1;
actpointer.to = new activityparty[] { party1 };
Guid ow2 = new Guid(invoiceId.ToString());
Lookup lookup = new Lookup();
lookup.Value = ow2;
lookup.type = EntityName.invoice.ToString();
actpointer.regardingobjectid = lookup;
Guid emailActId = service.Create(actpointer);
AddAttachmentToEmailActivity(emailActId.ToString(), PDFFileNameName);
}

Code to connect to CRM meta service

public static MetadataService.MetadataService GetMetaService()
{
#region for Online
CrmDiscoveryService.CrmDiscoveryService discoveryService = new CrmDiscoveryService.CrmDiscoveryService();
discoveryService.Url = String.Format("https://{0}/MSCRMServices/2007/{1}/CrmDiscoveryService.asmx", "dev.crm.dynamics.com", "Passport");
RetrievePolicyRequest policyRequest = new RetrievePolicyRequest();
RetrievePolicyResponse policyResponse = (RetrievePolicyResponse)discoveryService.Execute(policyRequest);
LogonManager lm = new LogonManager();
string passportTicket = lm.Logon(ConfigurationSettings.AppSettings["CRMUserName"], ConfigurationSettings.AppSettings["CRMPassword"], "crm.dynamics.com", policyResponse.Policy, "Production");
lm.Dispose();
RetrieveCrmTicketRequest crmTicketRequest = new RetrieveCrmTicketRequest();
crmTicketRequest.OrganizationName = ConfigurationSettings.AppSettings["Organization"];
crmTicketRequest.PassportTicket = passportTicket;
RetrieveCrmTicketResponse crmTicketResponse = (RetrieveCrmTicketResponse)discoveryService.Execute(crmTicketRequest);
MetadataService.MetadataService mdService =new CLMApplication.MetadataService.MetadataService();
mdService.Url = crmTicketResponse.OrganizationDetail.CrmMetadataServiceUrl;
MetadataService.CrmAuthenticationToken token = new MetadataService.CrmAuthenticationToken();
token.AuthenticationType = AuthenticationType.Passport;
token.CrmTicket = crmTicketResponse.CrmTicket;
token.OrganizationName = crmTicketResponse.OrganizationDetail.OrganizationName;
mdService.CrmAuthenticationTokenValue = token;
//CrmService myService = objConfig.RetrieveService();
//CreateDynamiceEntity(mdService, myService);

#endregion
return mdService;
}

Code to connect to CRM Online CRMService

you have to down load service and store it on hard disk and add reference to it in application.


public static CrmService.CrmService GetCrmService()
{
if (CLMservice == null)
{
CLMservice = new CrmService.CrmService();
//CrmAuthenticationToken token1 = new CrmAuthenticationToken();
//token1.AuthenticationType = 0;
//token1.OrganizationName = "CLM";


//CLMservice.CrmAuthenticationTokenValue = token1;
//CLMservice.Credentials = new System.Net.NetworkCredential("administrator", "syspro15*TX");

//
//-------------------
CrmDiscoveryService.CrmDiscoveryService discoveryService = new CrmDiscoveryService.CrmDiscoveryService();
discoveryService.Url = String.Format("https://{0}/MSCRMServices/2007/{1}/CrmDiscoveryService.asmx", "dev.crm.dynamics.com", "Passport");
//"http://clm.crm.dynamics.com/MSCrmServices/2007/Passport/CrmDiscoveryService.asmx?uniquename=clm";//
RetrievePolicyRequest policyRequest = new RetrievePolicyRequest();
RetrievePolicyResponse policyResponse = (RetrievePolicyResponse)discoveryService.Execute(policyRequest);
LogonManager lm = new LogonManager();
//string passportTicket = lm.Logon("syspro101@hotmail.com", "dxt31MS", "crm.dynamics.com", policyResponse.Policy, "Production");
// string passportTicket = lm.Logon("crmadmin@sysprotech.com", "sys35adm", "crm.dynamics.com", policyResponse.Policy, "Production");
string passportTicket = lm.Logon(ConfigurationSettings.AppSettings["CRMUserName"], ConfigurationSettings.AppSettings["CRMPassword"], "crm.dynamics.com", policyResponse.Policy, "Production");

RetrieveCrmTicketRequest crmTicketRequest = new RetrieveCrmTicketRequest();
//crmTicketRequest.OrganizationName = "clm";
crmTicketRequest.OrganizationName = ConfigurationSettings.AppSettings["Organization"];
//crmTicketRequest.OrganizationName = System.Configuration.ConfigurationSettings.AppSettings["Orgname"];
crmTicketRequest.PassportTicket = passportTicket;
RetrieveCrmTicketResponse crmTicketResponse = (RetrieveCrmTicketResponse)discoveryService.Execute(crmTicketRequest);


CrmService.CrmService crmService = new CrmService.CrmService();
crmService.Url = crmTicketResponse.OrganizationDetail.CrmServiceUrl;

CrmService.CrmAuthenticationToken token = new CrmService.CrmAuthenticationToken();
token.AuthenticationType = AuthenticationType.Passport;
token.CrmTicket = crmTicketResponse.CrmTicket;
token.OrganizationName = crmTicketResponse.OrganizationDetail.OrganizationName;
crmService.CrmAuthenticationTokenValue = token;
WhoAmIRequest whoRequest = new WhoAmIRequest();
WhoAmIResponse whoResponse = (WhoAmIResponse)crmService.Execute(whoRequest);
lm.Dispose();
CrmService.CrmService service = crmService;
CLMservice = crmService;
return CLMservice;// service;
}
return CLMservice;
}

Add Invoice to Product in CRM 4.0 with write in existing Product

Guid productId = new Guid(productid);
invoicedetail objDetails = new invoicedetail();
objDetails.productid = new Lookup();
objDetails.productid.Value = productId;
objDetails.productid.type = EntityName.product.ToString();
//if (!string.IsNullOrEmpty(product.description))
//{
// objDetails.description = product.description.ToString();
//}

CrmDecimal objDec = new CrmDecimal();
objDec.Value = Convert.ToDecimal("1", CultureInfo.InvariantCulture);
objDetails.quantity = objDec;

CrmMoney objDec1 = new CrmMoney();
objDec1.Value = Convert.ToDecimal(allocatedAmount, CultureInfo.InvariantCulture);
objDetails.priceperunit = objDec1;
objDetails.invoiceid = new Lookup();
objDetails.invoiceid.Value = invoiceId;
objDetails.invoiceid.type = EntityName.invoice.ToString();
CrmBoolean objOverride = new CrmBoolean();
objOverride.Value = true;//
objDetails.ispriceoverridden = objOverride;
CrmBoolean objProductOverride = new CrmBoolean();
objProductOverride.Value = false;//
// objDetails.ispriceoverridden = objOverride;
objDetails.isproductoverridden = objProductOverride;
objDetails.uomid = new Lookup();
objDetails.uomid.Value = new Guid(RetrieveUog());
objDetails.uomid.type = EntityName.uom.ToString();
service.Create(objDetails);

Add product to Invoice (Write In Product)

invoicedetail objDetails = new invoicedetail();
CrmBoolean objProductOverride = new CrmBoolean();
objProductOverride.Value = true;//
objDetails.isproductoverridden = objProductOverride;
productName = ConfigurationSettings.AppSettings["ProductLineItem_Prefix"].ToString() + " - " + dt_kidsSupported.Rows[kd]["KidName"].ToString();
objDetails.productdescription = productName;
CrmDecimal objDec = new CrmDecimal();
objDec.Value = Convert.ToDecimal("1", CultureInfo.InvariantCulture);
objDetails.quantity = objDec;
CrmMoney objDec1 = new CrmMoney();
objDec1.Value = SponsordAmount;
objDetails.priceperunit = objDec1;
objDetails.invoiceid = new Lookup();
objDetails.invoiceid.Value = invoiceId;
objDetails.invoiceid.type = EntityName.invoice.ToString();
service.Create(objDetails);

Create Invoice in CRM 4.0 / 3.0

service = CLM_CRM_Service.GetCrmService();
invoice objInvoice = new invoice();
invioceName = accountName + " - Invoice Processed For Month - " + critiria[0].ToString() + " " + critiria[1].ToString();
objInvoice.name = invioceName;
Customer customerid = new Customer();
customerid.Value = new Guid(accountId);
customerid.type = EntityName.account.ToString();
objInvoice.customerid = customerid;
objInvoice.ownerid = new Owner();
objInvoice.ownerid.Value = new Guid(ownerID); // new Guid("C3182C2C-C266-DE11-A541-001E0B5E0BF6");//system userid
objInvoice.ownerid.type = EntityName.systemuser.ToString();
objInvoice.pricelevelid = new Lookup();
objInvoice.pricelevelid.Value = new Guid(RetrievePriceLevel());
objInvoice.pricelevelid.type = EntityName.pricelevel.ToString();
CrmBoolean objSync = new CrmBoolean();
objSync.Value = true;
objInvoice.new_issynchronized = objSync;
Guid invoiceId = service.Create(objInvoice);

Retrieve / Access picklist items form CRM.

string st = GetPickListItemValue("account", "new_frequency", "Frequency");


public static string GetPickListItemValue(string entityName, string pickListName, string itemLabel)
{
string itemValue = string.Empty;
try
{
MetadataService.MetadataService service =new CLMApplication.MetadataService.MetadataService();
service = GetMetaService();
RetrieveAttributeRequest attribReq = new RetrieveAttributeRequest();
attribReq.EntityLogicalName = entityName;
attribReq.LogicalName = pickListName;
// Get the attribute metadata for the pickListName attribute.
RetrieveAttributeResponse amRes = (RetrieveAttributeResponse)service.Execute(attribReq);
AttributeMetadata am = amRes.AttributeMetadata;
PicklistAttributeMetadata listData = (PicklistAttributeMetadata)am;
foreach (Option option in listData.Options)
{
foreach (CLMApplication.MetadataService.LocLabel label in option.Label.LocLabels)
{
// Show US English value:label pairs
if (label.LanguageCode.Value == 1033)
//if (label.Label.Equals(itemLabel))
//{
//itemValue = option.Value.Value;
itemValue = itemValue + option.Value.Value.ToString() + ";";
itemValue = itemValue + option.Label.LocLabels[0].Label.ToString() + ",";
//}
}
}
}
catch (Exception ex)
{
}

return itemValue;
}

Create Notes and attach document for Invoice in CRM 4.0 and 3.0

public void CreateNoteAndAddAttachment(string PDFFileNameName , string InvoiceId)
{
service = CLM_CRM_Service.GetCrmService();
//Read File
string currentPath = txtPath.Text;
FileStream stream = File.OpenRead(currentPath + "\\" + PDFFileNameName.ToString() + ".pdf");
byte[] byteData = new byte[stream.Length];
stream.Read(byteData, 0, byteData.Length);
stream.Close();
// Encode the data using base64.
string encodedData = System.Convert.ToBase64String(byteData);
annotation note = new annotation();
note.objectid = new Lookup();
note.objectid.type = EntityName.invoice.ToString();
note.objectid.Value = new Guid(InvoiceId);
note.objecttypecode = new EntityNameReference();
note.objecttypecode.Value = EntityName.invoice.ToString();
note.subject = PDFFileNameName.ToString();
// note.notetext = inviocePDFFileNameName.ToString();
note.documentbody = encodedData;
note.filename = PDFFileNameName.ToString() + ".pdf";
note.mimetype = @"application\pdf";
// Create the note.
Guid newNoteID = service.Create(note);


}

Thursday, June 4, 2009

Retrieve Mail Items/ Email form outlook in C#.net

public void RetrieveEmailDetails(object oItem, string strMessageClass, string TypeofTrack)
{
Outlook.MailItem oMailItem;
try
{
if (strMessageClass == "MailItem")
{
oMailItem = (Outlook.MailItem)oItem; // Mail Entry.
bool flag = false;
for (int i = 0; i < dt_Mail.Rows.Count; i++)
{
if (dt_Mail.Rows[i]["EntryID"].ToString() == oMailItem.EntryID.ToString())
{
flag = true;
break;
}
}
if (flag != true)
{
if (! String.IsNullOrEmpty(oMailItem.Subject.ToString()))
{
DataRow dr = dt_Mail.NewRow();
dr["Type"] = "Email";

if (oMailItem.Subject != null)
{
dr["Subject"] = oMailItem.Subject.ToString();
}
if (oMailItem.Body != null)
{
dr["Body"] = oMailItem.Body.ToString();
}
if (oMailItem.SenderEmailAddress != null)
{
dr["SenderEmailAddress"] = oMailItem.SenderEmailAddress.ToString();
}
if (oMailItem.SenderName != null)
{
dr["SenderName"] = oMailItem.SenderName.ToString();
}
if (oMailItem.To != null)
{
dr["To"] = oMailItem.To.ToString();
}
if (oMailItem.CC != null)
{
dr["CC"] = oMailItem.CC.ToString();
}
if (oMailItem.BCC != null)
{
dr["BCC"] = oMailItem.BCC.ToString();
}
if (oMailItem.Subject != null)
{
dr["ReceivedTime"] = oMailItem.ReceivedTime.ToString();
}
if (oMailItem.SentOn != null)
{
dr["SentOn"] = oMailItem.SentOn.ToString();
}
if (oMailItem.EntryID != null)
{
dr["EntryID"] = oMailItem.EntryID.ToString();
}
// string c = oMailItem.Recipients[1].Address.ToString();
dt_Mail.Rows.Add(dr);
btnSaveToDatabase.Enabled = true;
}
}
}

}
catch
{
label1.Text = "Please Select Proper Mail Item.";
btnSaveToDatabase.Enabled = false;
}
}

Get Outlook Contact in C#.net

public DataTable GetOutlookContact(string sender)
{
Outlook.Application oApp = new Outlook.Application();
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
oNS.Logon(Missing.Value, Missing.Value, true, true);
Outlook.MAPIFolder oContacts = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
Outlook.Items oItems = (Outlook.Items)oContacts.Items;
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("FullName"));
dt.Columns.Add(new DataColumn("PagerNumber"));
dt.Columns.Add(new DataColumn("MobileTelephoneNumber"));
dt.Columns.Add(new DataColumn("Email1Address"));
dt.Columns.Add(new DataColumn("WebPage"));
dt.Columns.Add(new DataColumn("BusinessTelephoneNumber"));
dt.Columns.Add(new DataColumn("GovernmentIDNumber"));
dt.Columns.Add(new DataColumn("Suffix"));
dt.Columns.Add(new DataColumn("LastName"));
dt.Columns.Add(new DataColumn("MiddleName"));
dt.Columns.Add(new DataColumn("NickName"));
dt.Columns.Add(new DataColumn("Department"));
dt.Columns.Add(new DataColumn("FirstName"));
dt.Columns.Add(new DataColumn("JobTitle"));
dt.Columns.Add(new DataColumn("CompanyName"));
Outlook.ContactItem oCt;
for (int i = 1; i <= oItems.Count; i++)
{
//Outlook.ContactItem oCt = (Outlook.ContactItem)oItems.GetFirst();
oCt = (Outlook.ContactItem)oItems[i];
if (oCt.Email1Address.ToString() == sender)
{
DataRow dr = dt.NewRow();
if (oCt.FullName != null)
{
dr["FullName"] = oCt.FullName.ToString().Replace("\'", "\'\'");
}
if (oCt.PagerNumber != null)
{
dr["PagerNumber"] = oCt.PagerNumber.ToString().Replace("\'", "\'\'");
}
if (oCt.MobileTelephoneNumber != null)
{
dr["MobileTelephoneNumber"] = oCt.MobileTelephoneNumber.ToString().Replace("\'", "\'\'");
}
if (oCt.Email1Address != null)
{
dr["Email1Address"] = oCt.Email1Address.ToString().Replace("\'", "\'\'");
}
if (oCt.WebPage != null)
{
dr["WebPage"] = oCt.WebPage.ToString().Replace("\'", "\'\'");
}
if (oCt.BusinessTelephoneNumber != null)
{
dr["BusinessTelephoneNumber"] = oCt.BusinessTelephoneNumber.ToString().Replace("\'", "\'\'");
}
if (oCt.GovernmentIDNumber != null)
{
dr["GovernmentIDNumber"] = oCt.GovernmentIDNumber.ToString().Replace("\'", "\'\'");
}
if (oCt.Suffix != null)
{
dr["Suffix"] = oCt.Suffix.ToString().Replace("\'", "\'\'");
}
if (oCt.LastName != null)
{
dr["LastName"] = oCt.LastName.ToString().Replace("\'", "\'\'");
}
if (oCt.MiddleName != null)
{
dr["MiddleName"] = oCt.MiddleName.ToString().Replace("\'", "\'\'");
}
if (oCt.NickName != null)
{
dr["NickName"] = oCt.NickName.ToString().Replace("\'", "\'\'");
}
if (oCt.Department != null)
{
dr["Department"] = oCt.Department.ToString().Replace("\'", "\'\'");
}
if (oCt.FirstName != null)
{
dr["FirstName"] = oCt.FirstName.ToString().Replace("\'", "\'\'");
}
if (oCt.JobTitle != null)
{
dr["JobTitle"] = oCt.JobTitle.ToString().Replace("\'", "\'\'");
}
if (oCt.CompanyName != null)
{
dr["CompanyName"] = oCt.CompanyName.ToString().Replace("\'", "\'\'");
}
dt.Rows.Add(dr);
}
}
//Show the item to pause.
//oCt.Display(true);
oNS.Logoff();
oApp = null;
oItems = null;
oContacts = null;
oNS = null;
oApp = null;
return dt;
}

Attach Notes to Contact / Account in CRM


public Guid InsertNotesForContact(string contactid, string body)
{
CrmService service = new CrmService();
service = MyService();
annotation note = new annotation();
//#2
//note.ownerid = new Owner();
//note.ownerid.type = "systemuser";
//note.ownerid.Value = new Guid("000-000-0000"); <-- don't use this value
//note.ownerid.name = "Administrator";
//#3
note.objectid = new Lookup();
// note.objectid.name = "contact name";
note.objectid.type = EntityName.contact.ToString();
note.objectid.Value = new Guid(contactid);
note.notetext = body;
//note.subject = "my attachment";
//#4
note.objecttypecode = new EntityNameReference();
note.objecttypecode.Value = EntityName.contact.ToString();
Guid newNoteID = service.Create(note);
return newNoteID;
}

Attach Notes to Contact / Account in CRM

public Guid InsertNotesForContact(string contactid, string body)
{
CrmService service = new CrmService();
service = MyService();
annotation note = new annotation();
//#2
//note.ownerid = new Owner();
//note.ownerid.type = "systemuser";
//note.ownerid.Value = new Guid("000-000-0000"); <-- don't use this value
//note.ownerid.name = "Administrator";
//#3
note.objectid = new Lookup();
// note.objectid.name = "contact name";
note.objectid.type = EntityName.contact.ToString();
note.objectid.Value = new Guid(contactid);
note.notetext = body;
//note.subject = "my attachment";
//#4
note.objecttypecode = new EntityNameReference();
note.objecttypecode.Value = EntityName.contact.ToString();
Guid newNoteID = service.Create(note);
return newNoteID;
}