Convert Word document attached with note to PDF in CRM - c#

I need your help. I want to convert word document attached with note into PDF and send it to customer. I have retrieved note attachment with invoice entity, but unable to convert it into PDF. Please see below code.
Entity emailCreated = service.Retrieve("email", SourceEmailID, new ColumnSet(true));
QueryExpression QueryNotes = new QueryExpression("annotation");
QueryNotes.ColumnSet = new ColumnSet(new string[] { "subject", "mimetype", "filename", "documentbody" });
QueryNotes.Criteria = new FilterExpression();
QueryNotes.Criteria.FilterOperator = LogicalOperator.And;
QueryNotes.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, invoiceID.Id));
EntityCollection MimeCollection = service.RetrieveMultiple(QueryNotes);
if (MimeCollection.Entities.Count > 0)
{ //we need to fetch first attachment
Entity NotesAttachment = MimeCollection.Entities.First();
//Create email attachment
Entity EmailAttachment = new Entity("activitymimeattachment");
if (NotesAttachment.Contains("subject"))
EmailAttachment["subject"] = NotesAttachment.GetAttributeValue<string>("subject");
EmailAttachment["objectid"] = new EntityReference("email", emailCreated.Id);
EmailAttachment["objecttypecode"] = "email";
if (NotesAttachment.Contains("filename"))
EmailAttachment["filename"] = NotesAttachment.GetAttributeValue<string>("filename");
if (NotesAttachment.Contains("documentbody"))
EmailAttachment["body"] = NotesAttachment.GetAttributeValue<string>("documentbody");
if (NotesAttachment.Contains("mimetype"))
EmailAttachment["mimetype"] = NotesAttachment.GetAttributeValue<string>("mimetype");
service.Create(EmailAttachment);
}
// Sending email
SendEmailRequest SendEmail = new SendEmailRequest();
SendEmail.EmailId = emailCreated.Id;
SendEmail.TrackingToken = "";
SendEmail.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)service.Execute(SendEmail);

I change only few lines as, file name is static in this case but you can change it later.
if (NotesAttachment.Contains("filename"))
EmailAttachment["filename"] = "abc.pdf";
if (NotesAttachment.Contains("documentbody"))
EmailAttachment["body"] = Convert.ToBase64String(NotesAttachment.GetAttributeValue<string>("documentbody"));
if (NotesAttachment.Contains("mimetype"))
EmailAttachment["mimetype"] = "text/plain";
Try below code,
Entity emailCreated = service.Retrieve("email", SourceEmailID, new ColumnSet(true));
QueryExpression QueryNotes = new QueryExpression("annotation");
QueryNotes.ColumnSet = new ColumnSet(new string[] { "subject", "mimetype", "filename", "documentbody" });
QueryNotes.Criteria = new FilterExpression();
QueryNotes.Criteria.FilterOperator = LogicalOperator.And;
QueryNotes.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, invoiceID.Id));
EntityCollection MimeCollection = service.RetrieveMultiple(QueryNotes);
if (MimeCollection.Entities.Count > 0)
{ //we need to fetch first attachment
Entity NotesAttachment = MimeCollection.Entities.First();
//Create email attachment
Entity EmailAttachment = new Entity("activitymimeattachment");
if (NotesAttachment.Contains("subject"))
EmailAttachment["subject"] = NotesAttachment.GetAttributeValue<string>("subject");
EmailAttachment["objectid"] = new EntityReference("email", emailCreated.Id);
EmailAttachment["objecttypecode"] = "email";
if (NotesAttachment.Contains("filename"))
EmailAttachment["filename"] = "abc.pdf";
if (NotesAttachment.Contains("documentbody"))
EmailAttachment["body"] = Convert.ToBase64String(NotesAttachment.GetAttributeValue<string>("documentbody"));
if (NotesAttachment.Contains("mimetype"))
EmailAttachment["mimetype"] = "text/plain";
service.Create(EmailAttachment);
}
// Sending email
SendEmailRequest SendEmail = new SendEmailRequest();
SendEmail.EmailId = emailCreated.Id;
SendEmail.TrackingToken = "";
SendEmail.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)service.Execute(SendEmail);

Related

"CSOMUnknownUser" It occurrs when I execute the draft project query

I am trying to create a new project in MS Project Server 2016 using PSI C#. It creates a new project along with the task but when I tried to set the values of some custom fields and try to load/execute the query, it returns "CSOMUnknownUser" error.
Can anyone help me out to sort out this problem. my sample code is here
worker = new Classes.ProjectServerWorker();
worker.projContext = new Microsoft.ProjectServer.Client.ProjectContext(SPContext.Current.Web.Url);
NetworkCredential cred = new NetworkCredential();
cred.Domain = "abc";
cred.UserName = "abc";
cred.Password = "abc";
worker.projContext.Credentials = cred;
ProjectCreationInformation newProj = new ProjectCreationInformation();
//ProjectContext projContext = new ProjectContext(SPContext.Current.Web.Url + "/sites/PWA");
try
{
newProj.Id = Guid.NewGuid();
string strGuidID = newProj.Id.ToString();
newProj.Name = "new project title";
newProj.Description = "new project requirement details";
PublishedProject newPublishedProj = worker.projContext.Projects.Add(newProj);
QueueJob qJob = worker.projContext.Projects.Update();
//jobState = worker.projContext.WaitForQueue(qJob, timeoutSeconds);
IsProjectCreated = true;
worker.projContext.Load(worker.projContext.Projects);
worker.projContext.ExecuteQuery();
var proj = worker.projContext.Projects.First(p => p.Name == newProj.Name);
worker.projContext.ExecuteQuery();
var draftProj = proj.CheckOut();
// Creating Task under project
TaskCreationInformation newtask = new TaskCreationInformation();
newtask.Name = "First Task";
newtask.Start = DateTime.Today;
newtask.Finish = DateTime.Today.AddDays(35);
newtask.Id = Guid.NewGuid();
newtask.IsManual = false;
DraftTask drafttask = draftProj.Tasks.Add(newtask);
draftProj.Update();
draftProj.Publish(true); // Publish and check-in the project
worker.projContext.ExecuteQuery();
// Setting Custom Fields data
var guidID = new Guid(strGuidID);
var projcs = worker.projContext.Projects.GetByGuid(guidID);
var draftProjCS = projcs.CheckOut().IncludeCustomFields;
worker.projContext.Load(draftProjCS);
worker.projContext.ExecuteQuery();
string WorkRequestTitle = "new project";
var field1 = worker.projContext.CustomFields.Where(a => a.InternalName== ProjectFields.WorkRequestTitle).FirstOrDefault();
draftProjCS.SetCustomFieldValue(field1.InternalName, WorkRequestTitle);

How to set tab values in a template in C# (Need to set value PDF template in Docusign)

TemplateRole templateRole = new TemplateRole();
templateRole.Email = "chetan.wani88#gmail.com";
templateRole.RoleName = "Developer";
templateRole.DefaultRecipient = "true";
templateRole.Name = "Month Year 2021";
//templateRole.Tabs.TitleTabs.Add(new Title { TabLabel = "title", Value = "1323232" });
templateRole.ClientUserId = string.Empty;
templateRole.Tabs = new Tabs();
templateRole.Tabs.TextTabs = new List<Text>();
templateRole.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
signHere.AnchorXOffset = "20";
signHere.AnchorYOffset = "10";
signHere.AnchorUnits = "pixels";
templateRole.Tabs.SignHereTabs.Add(signHere);
Text textTab = new Text();
textTab.TabLabel = "Test88";
textTab.Value = "12525252";
templateRole.Tabs.TextTabs.Add(textTab);
List templateRoles = new List();
templateRoles.Add(templateRole);
envDef.TemplateRoles = templateRoles;
envDef.Status = "sent";
var envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
Please read our article on this subject that includes code snippets in C# and other langs.
The code must match the recipients, since the tabs are associated with them. Often the tabs don't show up because you added a new recipient that has a different role.
templateRole.RoleName = "Developer";
|This must match your template.

NetSuite. How to select all attached files for current user (filter by InternalId)

I am using C# implementation of netsuite api from web reference com.netsuite.webservices
I released filter fileSearch.basic by name (you can see it commented) it is working fine.
Please help to write function to achieve all attached files for current user. Something is wrong in this code, it filters nothing and showing me all files as it is without any filter. Please help me.
public static void GetFileAttachmentByCustomerId(string customerId)
{
using (NetSuiteService netSuiteService = GetNetSuiteService())
{
FileSearch fileSearch = new FileSearch();
// this works fine (filter files by name)
//SearchStringField nameSearchParams = new SearchStringField
//{
// #operator = SearchStringFieldOperator.contains,
// operatorSpecified = true,
// searchValue = "some name",
//};
//fileSearch.basic = new FileSearchBasic() { name = nameSearchParams };
// this code not filter files at all
{
RecordRef nsCustomerRef = new RecordRef
{
internalId = customerId,
type = RecordType.customer,
typeSpecified = true,
};
SearchMultiSelectField shopperSearchParam = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new RecordRef[] { nsCustomerRef }
};
fileSearch.shopperJoin = new CustomerSearchBasic { internalId = shopperSearchParam };
}
SearchResult result = netSuiteService.search(fileSearch);
// Get connected objects
{
Customer customer = GetCustomerById(netSuiteService, customerId);
Account account = GetAccountById(netSuiteService, "301395"); //
Folder folder = GetFolderById(netSuiteService, "3962");
}
File file = (File)result.recordList.First();
byte[] fileContent = GetFileContentByInternalId(file.internalId);
}
}
.
Try this:
var nsCustomerRef = new RecordRef
{
internalId = "4",
type = RecordType.employee,
typeSpecified = true,
};
var currentUser = new SearchMultiSelectField()
{
operatorSpecified = true,
#operator = SearchMultiSelectFieldOperator.anyOf,
searchValue = new List<RecordRef>() {nsCustomerRef}.ToArray()
};
var fileSearchBasic = new FileSearchBasic() {owner = currentUser};
var fileSearch = new FileSearch() { basic = fileSearchBasic };
var result = netSuiteService.search(fileSearch);
var file = (File)result.recordList.First();

Viewing XML output from C#

I'm trying to work with the UPS api to create a shipping label. The UPS api uses a webservice to send an XML request to UPS. UPS then sends a response back. Here is my question.
Is there a way to view the XML that is outputted when I call the "shipmentRequest" method?
This is the first time I've used an API and a webservice so if you need me to provide more information just let me know.
Thanks!
EDIT: Here is my C# code
ShipService shpSvc = new ShipService();
ShipmentRequest shipmentRequest = new ShipmentRequest();
UPSSecurity upss = new UPSSecurity();
//shpSvc.Url = "https://onlinetools.ups.com/webservices/Ship";
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = apiCode;
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = userName;
upssUsrNameToken.Password = password;
upss.UsernameToken = upssUsrNameToken;
shpSvc.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "nonvalidate" };
request.RequestOption = requestOption;
shipmentRequest.Request = request;
ShipmentType shipment = new ShipmentType();
shipment.Description = "Ship webservice example";
ShipperType shipper = new ShipperType();
shipper.ShipperNumber = accountNumber;
PaymentInfoType paymentInfo = new PaymentInfoType();
ShipmentChargeType shpmentCharge = new ShipmentChargeType();
BillShipperType billShipper = new BillShipperType();
billShipper.AccountNumber = accountNumber;
shpmentCharge.BillShipper = billShipper;
shpmentCharge.Type = "01";
ShipmentChargeType[] shpmentChargeArray = { shpmentCharge };
paymentInfo.ShipmentCharge = shpmentChargeArray;
shipment.PaymentInformation = paymentInfo;
ShipWSSample.ShipWebReference.ShipAddressType shipperAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] addressLine = { "480 Parkton Plaza" };
shipperAddress.AddressLine = addressLine;
shipperAddress.City = "Timonium";
shipperAddress.PostalCode = "21093";
shipperAddress.StateProvinceCode = "MD";
shipperAddress.CountryCode = "US";
shipperAddress.AddressLine = addressLine;
shipper.Address = shipperAddress;
shipper.Name = "ABC Associates";
shipper.AttentionName = "ABC Associates";
ShipPhoneType shipperPhone = new ShipPhoneType();
shipperPhone.Number = "1234567890";
shipper.Phone = shipperPhone;
shipment.Shipper = shipper;
ShipFromType shipFrom = new ShipFromType();
ShipWSSample.ShipWebReference.ShipAddressType shipFromAddress = new ShipWSSample.ShipWebReference.ShipAddressType();
String[] shipFromAddressLine = { "Ship From Street" };
shipFromAddress.AddressLine = addressLine;
shipFromAddress.City = "Timonium";
shipFromAddress.PostalCode = "21093";
shipFromAddress.StateProvinceCode = "MD";
shipFromAddress.CountryCode = "US";
shipFrom.Address = shipFromAddress;
shipFrom.AttentionName = "Mr.ABC";
shipFrom.Name = "ABC Associates";
shipment.ShipFrom = shipFrom;
ShipToType shipTo = new ShipToType();
ShipToAddressType shipToAddress = new ShipToAddressType();
String[] addressLine1 = { "Some Street" };
shipToAddress.AddressLine = addressLine1;
shipToAddress.City = "Roswell";
shipToAddress.PostalCode = "30076";
shipToAddress.StateProvinceCode = "GA";
shipToAddress.CountryCode = "US";
shipTo.Address = shipToAddress;
shipTo.AttentionName = "DEF";
shipTo.Name = "DEF Associates";
ShipPhoneType shipToPhone = new ShipPhoneType();
shipToPhone.Number = "1234567890";
shipTo.Phone = shipToPhone;
shipment.ShipTo = shipTo;
ServiceType service = new ServiceType();
service.Code = "01";
shipment.Service = service;
PackageType package = new PackageType();
PackageWeightType packageWeight = new PackageWeightType();
packageWeight.Weight = "1";
ShipUnitOfMeasurementType uom = new ShipUnitOfMeasurementType();
uom.Code = "LBS";
packageWeight.UnitOfMeasurement = uom;
package.PackageWeight = packageWeight;
PackagingType packType = new PackagingType();
packType.Code = "02";
package.Packaging = packType;
PackageType[] pkgArray = { package };
shipment.Package = pkgArray;
LabelSpecificationType labelSpec = new LabelSpecificationType();
LabelStockSizeType labelStockSize = new LabelStockSizeType();
labelStockSize.Height = "6";
labelStockSize.Width = "4";
labelSpec.LabelStockSize = labelStockSize;
LabelImageFormatType labelImageFormat = new LabelImageFormatType();
labelImageFormat.Code = "SPL";
labelSpec.LabelImageFormat = labelImageFormat;
shipmentRequest.LabelSpecification = labelSpec;
shipmentRequest.Shipment = shipment;
ShipmentResponse shipmentResponse = shpSvc.ProcessShipment(shipmentRequest);
MessageBox.Show("The transaction was a " + shipmentResponse.Response.ResponseStatus.Description);
MessageBox.Show("The 1Z number of the new shipment is " + shipmentResponse.ShipmentResults.ShipmentIdentificationNumber);
You can inherit from the UPS service and read the response as xml by providing your own XmlWriter by overriding GetWriterForMessage(). You can see a working example here.
i am using this code display xml it may help you.
XDocument mySourceDoc = new XDocument();
mySourceDoc = XDocument.Load(shipmentResponse);
txtxml.Text = mySourceDoc.ToString();

How to find Customer Entities logical name from Guid in Microsoft CRM

In CRM I am trying to automate the process of creating a new email from a previous email in the chain. This email has to go to the customer of the case, who could be either an account or a contact.
I can retrieve the Guid of the contact/account but I dont know how to retrieve the logical name.
This is what I have so far:
OrganizationServiceProxy service = CRMCentralCRMServiceInstance;
Guid customerId = GetCustomerIdFromCase(caseId);
Entity email = new Entity("email");
Entity activityPartyTo = new Entity("activityparty");
//"account" is a guess, it could be "contact"
EntityReference customerReferenceTo = new EntityReference("account", customerId);
activityPartyTo["partyid"] = customerReferenceTo;
EntityCollection toEntityCollection = new EntityCollection();
toEntityCollection.Entities.Add(activityPartyTo);
email["to"] = toEntityCollection;
.
.
.
newEmailId = service.Create(email);
public Guid GetCustomerIdFromCase(Guid caseId) {
Guid customerId = Guid.Empty;
List<CRMCase> caseList = GetCRMCasesById(caseId);
if (caseList.Count > 0)
{
CRMCase cmcCase = caseList.First();
customerId = cmcCase.CustomerId;
}
return (customerId);
}
public List<CRMCase> GetCRMCasesById(Guid caseId)
{
List<CRMCase> crmCases = new List<CRMCase>();
try
{
OrganizationServiceProxy service = CRMCentralCRMServiceInstance;
ConditionExpression condition1 = new ConditionExpression();
ConditionExpression condition2 = new ConditionExpression();
condition1.AttributeName = "incidentid";
condition1.Operator = ConditionOperator.Equal;
condition1.Values.Add(caseId.ToString("N"));
condition2.AttributeName = "statecode";
condition2.Operator = ConditionOperator.In;
condition2.Values.Add("Active");
condition2.Values.Add("Resolved");
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.Conditions.Add(condition1);
filter.Conditions.Add(condition2);
QueryExpression query = new QueryExpression();
query.EntityName = "incident";
query.ColumnSet = new ColumnSet(true);
query.Criteria = filter;
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = "incident";
retrieveAttributeRequest.LogicalName = "statuscode";
retrieveAttributeRequest.RetrieveAsIfPublished = true;
RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
StatusAttributeMetadata statusCodeAttribute = (StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = "incident";
retrieveAttributeRequest.LogicalName = "prioritycode";
retrieveAttributeRequest.RetrieveAsIfPublished = true;
retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata priorityCodeAttribute = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = "incident";
retrieveAttributeRequest.LogicalName = "statecode";
retrieveAttributeRequest.RetrieveAsIfPublished = true;
retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
StateAttributeMetadata stateCodeAttribute = (StateAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
EntityCollection casesColl = service.RetrieveMultiple(query);
foreach (Entity entity in casesColl.Entities)
{
Entity incidentCRMCase = entity;
CRMCase cRMCase = GetCRMCaseFromIncidentCase(incidentCRMCase, statusCodeAttribute.OptionSet.Options, stateCodeAttribute.OptionSet.Options, priorityCodeAttribute.OptionSet.Options);
crmCases.Add(cRMCase);
}
}
catch (SoapException se)
{
string action = MethodBase.GetCurrentMethod().DeclaringType.Name + " :: " + MethodBase.GetCurrentMethod().Name;
string message = "Unexpected error in action: " + action
+ Environment.NewLine + se.Message
+ Environment.NewLine + se.Detail.InnerText;
throw new Exception(message);
}
return (crmCases);
}
I found this brute force method but I would rather find a cleaner way if there is.
Ok. Really complicated code. Try to use something like following:
private EntityReference GetCustomerFromCase(Guid caseId)
{
Entity Case = CRMCentralCRMServiceInstance.Retrieve("incident", caseId, new ColumnSet("customerid"));
return Case.GetAttributeValue<EntityReference>("customerid");
}

Categories