Send a mail that has Arabic characters using Gmail API - google-api

I am trying to send a mail using google.Apis.Gmail.v1 and MimeKit, but the issue is that when I use Arabic characters, the receiver receives gibberish text.
My code is below:
var mail = new MimeMessage();
mail.From.Add(new MailboxAddress("From Name", "DoNotReply#someDomain.com"));
mail.To.Add(new MailboxAddress("To Name","customerAddress#someDomain.com"));
mail.Subject = "كشف حساب من تاريخ " + dateTimePicker1.Text + " حتى تاريخ " + dateTimePicker2.Text;
var text_part = new TextPart(MimeKit.Text.TextFormat.Plain);
string body = #"<table border='1'><table style='background-color:#E5E4E2;'><tr><tr style='background-color:#1e90ff;color:#ffffff;'><td>تراكمي</td><td>دائن</td><td>مدين</td><td>البيان</td><td>المرجع</td><td>التاريخ</td></tr>";
foreach (ListViewItem lstitem in listView1.Items)
{
body += #"<tr><td>" + lstitem.SubItems[1].Text + "</td><td>" + lstitem.SubItems[2].Text + "</td><td>" + lstitem.SubItems[3].Text + "</td><td>" + lstitem.SubItems[4].Text + "</td><td>" + lstitem.SubItems[5].Text + "</td><td>" + lstitem.SubItems[6].Text + "</td></tr>";
}
body += #"</table></style></style>";
body += #"<br /><br /> المبلغ المطلوب " + sum1s.Text;
body += #"<br /><br /> Thank You";
mail.Body = new TextPart("html") { Text = body };
byte[] bytes = Encoding.UTF8.GetBytes(mail.ToString());
string raw_message = Convert.ToBase64String(bytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
UserCredential credential;
//read your credentials file
using (FileStream stream = new FileStream(Application.StartupPath + #"/credentials.json", FileMode.Open, FileAccess.Read))
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
path = Path.Combine(path, ".credentials/gmail-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Program.Scopes, "user", CancellationToken.None, new FileDataStore(path, true)).Result;
}
//call your gmail service
var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = Program.ApplicationName });
var msg = new Google.Apis.Gmail.v1.Data.Message();
msg.Raw = raw_message;
service.Users.Messages.Send(msg, "me").Execute();
MessageBox.Show("تم ارسال التقرير بنجاح", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
And what I receive is:
تراكمي دائن مدين البيان المرجع التاريخ
985.00 58228.00 57243.00 رصيد منقول - 01/03/2022 00:00:00 AM
985 58228 -57243 المجموع الكلي - 11/03/2022 09:49:42 AM
المبلغ المطلوب + 985 شيكل
Thank You

Related

HttpClient exception in Windows service, but not in WinForms and Console application

I am experiencing an issue where an async call works in my WinForms and Console test applications, but not when I implement the same code in my intended target format - a Windows service.
I always get the "A task was canceled" exception - and I can't figure out why :|
System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at TotalArchiveService.CustomerServices.<ValidateCustomerCoreWSGen2>d__2.MoveNext() in C:\DeveloperArea\Dev\src\TotalArchiveService\CustomerServices.cs:line 123
Using Fiddler, I can see that the Windows service doesn't even call the service. At least there are no traces of it in the Fiddler log.
The following are code examples, where the two first ones are the WinForms and Console variants respectively. The last on is the non functioning Windows service.
In the Windows Service, the ValidateCustomer method is called in the OnElapsedTime method of the Windows service. I have tried several intervals, as I suspected that there were some kind of overlap of calls due to the async here, but it doesn't change anything. Even if it had been, I'd thought that I'd seen some traces of the first call in Fiddler, but there's nothing.
I am using .NET Framework 4.8 for the service and WinForms variants. .NET 6.0 for the Console app.
Any help or suggestions would be greatly appreciated.
WinForms
private static async Task<string> ValidateCustomerCoreWSGen2(string customerNumber)
{
REMOVED SECTION WHERE INTERNAL PARAMS WERE UPDATED FROMN CONFIG.
}
catch (Exception _ex)
{
_status = "CONFIG_ERROR";
}
try
{
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(_timeout) })
{
// Create HTTP request.
var customerBuilder = new UriBuilder(new Uri($"{_endpoint}"));
var customerRequest = new HttpRequestMessage(HttpMethod.Post, customerBuilder.Uri);
// Set SOAP action
customerRequest.Headers.Add("SOAPAction", "");
// SOAP body content
string xmlSOAP = GetXmlSOAP("CUSTOMERREAD", _sourceApplication, _destinationApplication, _function, _version, _username, _channel, _orgId, _orgUnit, customerNumber);
customerRequest.Content = new StringContent(xmlSOAP, Encoding.UTF8, "text/xml");
// Add signature headers to request object
await SignHttpRequestMessage(customerRequest);
// Call service
var customerResponse = await client.SendAsync(customerRequest);
//Response handling
if (customerResponse.IsSuccessStatusCode)
{
// Do what you want with response body
var responseBody = await customerResponse.Content.ReadAsStringAsync();
_status = "CUSTOMER_EXISTS";
}
else
{
_status = "CUSTOMER_READ_EXCEPTION";
var responseBody = await customerResponse.Content.ReadAsStringAsync();
var message = $"Response returned with status {customerResponse.StatusCode}. Reason: {customerResponse.ReasonPhrase}";
}
}
}
catch (Exception _ex)
{
_status = "SERVICE_ERROR";
}
return _status;
}
static async Task SignHttpRequestMessage(HttpRequestMessage request)
{
// externalize configuration of these
string certPath = "";
string keyStorePassword = "";
string keyId = "";
certPath = Path.GetFullPath(#"c:\cert2\cert.pfx"); // path to keystorefile
keyStorePassword = "REMOVED";
keyId = "REMOVED";
X509Certificate2Collection certs = new X509Certificate2Collection();
X509Certificate2 cert = new X509Certificate2(certPath, keyStorePassword, X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable);
var services = new ServiceCollection()
.AddHttpMessageSigning()
.UseKeyId(keyId)
.UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning(cert, HashAlgorithmName.SHA256))
.UseDigestAlgorithm(HashAlgorithmName.SHA256)
.UseUseDeprecatedAlgorithmParameter()
.UseNonce(false)
.UseHeaders()
.Services;
using (var serviceProvider = services.BuildServiceProvider())
{
using (var signerFactory = serviceProvider.GetRequiredService<IRequestSignerFactory>())
{
var requestSigner = signerFactory.CreateFor(keyId);
await requestSigner.Sign(request);
}
}
request.Headers.Add("Signature", request.Headers.Authorization.ToString());
request.Headers.Authorization = null;
}
private static string GetXmlSOAP(string method, string sourceApplication, string destinationApplication, string function, string version, string username, string channel, string orgId, string orgUnit, string customerNumber)
{
string _xmlSOAP = "";
if (method.ToUpper() == "CUSTOMERREAD")
{
_xmlSOAP = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:wsc=""http://REMOVED""
xmlns:urn=""urn:REMOVED""
xmlns:urn1=""urn:REMOVED""
xmlns:urn2=""urn:REMOVED"">
<soapenv:Header>
<wsc:AutHeader>
<wsc:SourceApplication>" + sourceApplication + #"</wsc:SourceApplication>
<wsc:DestinationApplication>" + destinationApplication + #"</wsc:DestinationApplication>
<wsc:Function>" + function + #"</wsc:Function>
<wsc:Version>" + version + #"</wsc:Version>
<wsc:ClientContext>
<wsc:userid>" + username + #"</wsc:userid>
<wsc:credentials/>
<wsc:channel>" + channel + #"</wsc:channel>
<wsc:orgid>" + orgId + #"</wsc:orgid>
<!--Optional:-->
<wsc:orgunit>" + orgUnit + #"</wsc:orgunit>
<!--Optional:-->
<wsc:customerid>" + customerNumber + #"</wsc:customerid>
<!--Optional:-->
<wsc:locale>no_NO</wsc:locale>
<wsc:ip>127.0.0.1</wsc:ip>
</wsc:ClientContext>
</wsc:AutHeader>
</soapenv:Header>
<soapenv:Body>
<urn:customerReadRequest>
<urn:readQualification>
<urn1:internationalCustomerKey>
<urn2:internationalCustomerNumber>" + customerNumber + #"</urn2:internationalCustomerNumber>
</urn1:internationalCustomerKey>
</urn:readQualification>
</urn:customerReadRequest>
</soapenv:Body>
</soapenv:Envelope>";
}
return _xmlSOAP;
}
private void cmdCustomerRead_Click(object sender, EventArgs e)
{
lblStatus.Text = "Status:";
//ValidateCustomerCoreWSGen2(tbCustomerNumber.Text.Trim());
CallValidateCustomerAsync(tbCustomerNumber.Text.Trim());
}
private async void CallValidateCustomerAsync(string customerNumber)
{
string result = await ValidateCustomerCoreWSGen2(customerNumber);
lblStatus.Text = "Status: " + result;
}
Console
static async Task ExampleRequest()
{
var timeout = 30;
try
{
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(timeout) })
{
int textidx = 2;
// URL to soap service
var endpointUrlCustomer = "https://REMOVED";
// Create HTTP request.
var customerBuilder = new UriBuilder(new Uri($"{endpointUrlCustomer}"));
var customerRequest = new HttpRequestMessage(HttpMethod.Post, customerBuilder.Uri);
// set SOAP action
customerRequest.Headers.Add("SOAPAction", "");
// set SOAP body content
Console.WriteLine();
Console.WriteLine("************************* CUSTOMER ***********************");
string xmlSOAP = GetXmlSOAP("CUSTOMER", textidx);
customerRequest.Content = new StringContent(xmlSOAP, Encoding.UTF8, "text/xml");
// Add signature headers to request object
await SignHttpRequestMessage(customerRequest, textidx);
Console.WriteLine("Signed request HTTP");
Console.WriteLine("-----------------------------------------");
Console.WriteLine(customerRequest + Environment.NewLine);
Console.WriteLine("Signed request XML");
Console.WriteLine("-----------------------------------------");
Console.WriteLine(customerRequest.Content.ReadAsStringAsync().Result + Environment.NewLine);
// Perform request
Console.WriteLine("Send request");
Console.WriteLine("-----------------------------------------");
var customerResponse = await client.SendAsync(customerRequest);
Console.WriteLine();
Console.WriteLine("Response HTTP");
Console.WriteLine("-----------------------------------------");
Console.WriteLine(customerResponse + Environment.NewLine);
Console.WriteLine("Response result XML");
Console.WriteLine("-----------------------------------------");
Console.WriteLine(customerResponse.Content.ReadAsStringAsync().Result + Environment.NewLine);
if (customerResponse.IsSuccessStatusCode)
{
// Do what you want with response body
var responseBody = await customerResponse.Content.ReadAsStringAsync();
}
else
{
var responseBody = await customerResponse.Content.ReadAsStringAsync();
var message = $"Response returned with status {customerResponse.StatusCode}. Reason: {customerResponse.ReasonPhrase}";
throw new Exception(message);
}
}
}
catch (HttpRequestException e)
{
throw e;
}
}
static async Task SignHttpRequestMessage(HttpRequestMessage request, int testIdx)
{
// externalize configuration of these
string certPath = "";
string keyStorePassword = "";
string keyId = "";
if (testIdx == 1)
{
keyStorePassword = "REMOVED";
keyId = "REMOVED";
}
if (testIdx == 2)
{
certPath = Path.GetFullPath(#"c:\cert2\cert.pfx"); // path to keystorefile
keyStorePassword = "REMOVED";
keyId = "REMOVED";
}
else if (testIdx == 3)
{
certPath = Path.GetFullPath(#"REMOVED"); // path to keystorefile
keyStorePassword = "REMOVED";
keyId = "REMOVED";
}
X509Certificate2Collection certs = new X509Certificate2Collection();
X509Certificate2 cert = new X509Certificate2(certPath, keyStorePassword, X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable);
var services = new ServiceCollection()
.AddHttpMessageSigning()
.UseKeyId(keyId)
.UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning(cert, HashAlgorithmName.SHA256))
.UseDigestAlgorithm(HashAlgorithmName.SHA256)
.UseUseDeprecatedAlgorithmParameter()
.UseNonce(false)
.UseHeaders()
.Services;
using (var serviceProvider = services.BuildServiceProvider())
{
using (var signerFactory = serviceProvider.GetRequiredService<IRequestSignerFactory>())
{
var requestSigner = signerFactory.CreateFor(keyId);
await requestSigner.Sign(request);
}
}
request.Headers.Add("Signature", request.Headers.Authorization.ToString());
request.Headers.Authorization = null;
}
static string GetXmlSOAP(string operation, int testIdx)
{
string xmlSOAP = "";
if (operation == "CUSTOMER")
{
if (testIdx == 1)
{
REMOVED
}
if (testIdx == 2)
{
xmlSOAP = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:wsc=""http://REMOVED""
xmlns:urn=""urn:REMOVED""
xmlns:urn1=""urn:REMOVED""
xmlns:urn2=""urn:REMOVED"">
<soapenv:Header>
<wsc:AutHeader>
<wsc:SourceApplication>REMOVED</wsc:SourceApplication>
<wsc:DestinationApplication>REMOVED</wsc:DestinationApplication>
<wsc:Function>REMOVED</wsc:Function>
<wsc:Version>REMOVED</wsc:Version>
<wsc:ClientContext>
<wsc:userid>REMOVED</wsc:userid>
<wsc:credentials/>
<wsc:channel>REMOVED</wsc:channel>
<wsc:orgid>REMOVED</wsc:orgid>
<wsc:orgunit>REMOVED</wsc:orgunit>
<wsc:customerid>REMOVED</wsc:customerid>
<wsc:locale>no_NO</wsc:locale>
<wsc:ip>127.0.0.1</wsc:ip>
</wsc:ClientContext>
</wsc:AutHeader>
</soapenv:Header>
<soapenv:Body>
<urn:customerReadRequest>
<urn:readQualification>
<urn1:internationalCustomerKey>
<urn2:internationalCustomerNumber>REMOVED</urn2:internationalCustomerNumber>
</urn1:internationalCustomerKey>
</urn:readQualification>
</urn:customerReadRequest>
</soapenv:Body>
</soapenv:Envelope>";
}
if (testIdx == 3)
{
REMOVED
}
}
}
Windows service
internal class CustomerServices
{
private static bool _extendedLogging = true;
public static string ValidateCustomer(string customerNumber)
{
string _status = "";
string _servicesType = CommonMethods.GetAppSetting("ServicesType");
//TODO: Check format, ref. "UNSUPPORTED_FORMAT" in HandleValidateCustomerException
//TODO: Check existing, ref. "CUSTOMER_NOT_FOUND" in HandleValidateCustomerException
if (_servicesType == "COREWSGEN2")
{
_status = ValidateCustomerCoreWSGen2(customerNumber).GetAwaiter().GetResult();
}
return _status;
}
private static async Task<string> ValidateCustomerCoreWSGen2(string customerNumber)
{
string _status = "";
string _username = "";
string _orgId = "";
string _orgUnit = "";
string _channel = "";
string _sourceApplication = "";
string _destinationApplication = "";
string _function = "";
string _version = "";
int _timeout = 30;
string _endpoint = "";
string _values = "";
try
{
_extendedLogging = (CommonMethods.GetAppSetting("ExtendedLogging").ToUpper() == "TRUE" ? true : false);
_values += "ExtendedLogging" + Environment.NewLine;
_username = CommonMethods.GetAppSetting("Username");
_values += "Username" + Environment.NewLine;
_orgId = CommonMethods.GetAppSetting("OrgId");
_values += "OrgId" + Environment.NewLine;
_orgUnit = CommonMethods.GetAppSetting("OrgUnit");
_values += "OrgUnit" + Environment.NewLine;
_channel = CommonMethods.GetAppSetting("CoreWSGen2Channel");
_values += "CoreWSGen2Channel" + Environment.NewLine;
_sourceApplication = CommonMethods.GetAppSetting("CoreWSGen2SourceApplication");
_values += "CoreWSGen2SourceApplication" + Environment.NewLine;
_destinationApplication = CommonMethods.GetAppSetting("CoreWSGen2DestinationApplication");
_values += "CoreWSGen2DestinationApplication" + Environment.NewLine;
_function = CommonMethods.GetAppSetting("CoreWSGen2Function");
_values += "CoreWSGen2Function" + Environment.NewLine;
_version = CommonMethods.GetAppSetting("CoreWSGen2Version");
_values += "CoreWSGen2Version" + Environment.NewLine;
_timeout = Int32.Parse(CommonMethods.GetAppSetting("CoreWSGen2TimeoutSeconds"));
_values += "CoreWSGen2Version" + Environment.NewLine;
_endpoint = CommonMethods.GetAppSetting("CustomerServicesEndpointAddress");
if (_extendedLogging)
{
Logging.LogAction("Application settings used for customer read:" + Environment.NewLine
+ "-------------------------------------------------" + Environment.NewLine
+ "Username = " + _username + Environment.NewLine
+ "OrgId = " + _orgId + Environment.NewLine
+ "OrgUnit = " + _orgUnit + Environment.NewLine
+ "Channel = " + _channel + Environment.NewLine
+ "SourceApplication = " + _sourceApplication + Environment.NewLine
+ "DestinationApplication = " + _destinationApplication + Environment.NewLine
+ "Function = " + _function + Environment.NewLine
+ "Version = " + _version + Environment.NewLine
+ "Timeout (seconds) = " + _timeout + Environment.NewLine
+ Environment.NewLine
+ "Endpoint = " + _endpoint + Environment.NewLine);
}
}
catch (Exception _ex)
{
_status = "CONFIG_ERROR";
Logging.LogException(new Exception("CustomerServices - Error when reading configuration file. Successfully read values: " + Environment.NewLine + _values + Environment.NewLine, _ex.InnerException));
}
try
{
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(_timeout) })
{
// Create HTTP request.
var customerBuilder = new UriBuilder(new Uri($"{_endpoint}"));
var customerRequest = new HttpRequestMessage(HttpMethod.Post, customerBuilder.Uri);
// Set SOAP action
customerRequest.Headers.Add("SOAPAction", "");
// SOAP body content
string xmlSOAP = GetXmlSOAP("CUSTOMERREAD", _sourceApplication, _destinationApplication, _function, _version, _username, _channel, _orgId, _orgUnit, customerNumber);
customerRequest.Content = new StringContent(xmlSOAP, Encoding.UTF8, "text/xml");
// Add signature headers to request object
await SignHttpRequestMessage(customerRequest);
// Call service
var customerResponse = await client.SendAsync(customerRequest);
if (_extendedLogging)
{
Logging.LogAction("Response header:" + Environment.NewLine + customerResponse + Environment.NewLine);
Logging.LogAction("Response content:" + Environment.NewLine + customerResponse.Content.ReadAsStringAsync().Result + Environment.NewLine);
}
//Response handling
if (customerResponse.IsSuccessStatusCode)
{
// Do what you want with response body
var responseBody = await customerResponse.Content.ReadAsStringAsync();
// Log response content if extended logging
if (_extendedLogging)
{
Logging.LogAction(responseBody);
}
_status = "CUSTOMER_EXISTS";
}
else
{
_status = "CUSTOMER_READ_EXCEPTION";
var responseBody = await customerResponse.Content.ReadAsStringAsync();
var message = $"Response returned with status {customerResponse.StatusCode}. Reason: {customerResponse.ReasonPhrase}";
Logging.LogException(new Exception(message));
}
}
}
catch (Exception _ex)
{
_status = "SERVICE_ERROR";
Logging.LogException(_ex);
}
return _status;
}
static async Task SignHttpRequestMessage(HttpRequestMessage request)
{
// externalize configuration of these
string certPath = "";
string keyStorePassword = "";
string keyId = "";
certPath = Path.GetFullPath(#"c:\cert2\cert.pfx"); // path to keystorefile
keyStorePassword = "internal-sls-test";
keyId = "73ae28ed2f31";
X509Certificate2Collection certs = new X509Certificate2Collection();
X509Certificate2 cert = new X509Certificate2(certPath, keyStorePassword, X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable);
var services = new ServiceCollection()
.AddHttpMessageSigning()
.UseKeyId(keyId)
.UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning(cert, HashAlgorithmName.SHA256))
.UseDigestAlgorithm(HashAlgorithmName.SHA256)
.UseUseDeprecatedAlgorithmParameter()
.UseNonce(false)
.UseHeaders()
.Services;
using (var serviceProvider = services.BuildServiceProvider())
{
using (var signerFactory = serviceProvider.GetRequiredService<IRequestSignerFactory>())
{
var requestSigner = signerFactory.CreateFor(keyId);
await requestSigner.Sign(request);
}
}
request.Headers.Add("Signature", request.Headers.Authorization.ToString());
request.Headers.Authorization = null;
if (_extendedLogging)
{
Logging.LogAction("Signed request header:" + Environment.NewLine + request + Environment.NewLine);
Logging.LogAction("Signed request content:" + Environment.NewLine + request.Content.ReadAsStringAsync().Result + Environment.NewLine);
}
}
private static string GetXmlSOAP(string method, string sourceApplication, string destinationApplication, string function, string version, string username, string channel, string orgId, string orgUnit, string customerNumber)
{
string _xmlSOAP = "";
if (method.ToUpper() == "CUSTOMERREAD")
{
_xmlSOAP = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:wsc=""http://edb.com/ws/WSCommon_v22""
xmlns:urn=""urn:srv.cus.corews.enterprise.fs.evry.com:ws:customer:v20_1""
xmlns:urn1=""urn:srv.cus.corews.enterprise.fs.evry.com:domain:customer:v20_1""
xmlns:urn2=""urn:corews.enterprise.fs.evry.com:domain:common:v8"">
<soapenv:Header>
<wsc:AutHeader>
<wsc:SourceApplication>" + sourceApplication + #"</wsc:SourceApplication>
<wsc:DestinationApplication>" + destinationApplication + #"</wsc:DestinationApplication>
<wsc:Function>" + function + #"</wsc:Function>
<wsc:Version>" + version + #"</wsc:Version>
<wsc:ClientContext>
<wsc:userid>" + username + #"</wsc:userid>
<wsc:credentials/>
<wsc:channel>" + channel + #"</wsc:channel>
<wsc:orgid>" + orgId + #"</wsc:orgid>
<!--Optional:-->
<wsc:orgunit>" + orgUnit + #"</wsc:orgunit>
<!--Optional:-->
<wsc:customerid>" + customerNumber + #"</wsc:customerid>
<!--Optional:-->
<wsc:locale>no_NO</wsc:locale>
<wsc:ip>127.0.0.1</wsc:ip>
</wsc:ClientContext>
</wsc:AutHeader>
</soapenv:Header>
<soapenv:Body>
<urn:customerReadRequest>
<urn:readQualification>
<urn1:internationalCustomerKey>
<urn2:internationalCustomerNumber>" + customerNumber + #"</urn2:internationalCustomerNumber>
</urn1:internationalCustomerKey>
</urn:readQualification>
</urn:customerReadRequest>
</soapenv:Body>
</soapenv:Envelope>";
}
return _xmlSOAP;
}
}

How can Dynamics CRM Statuscodes / Statecode Optionsets sort order be updated?

The UI Editor in Dynamics CRM won't allow system admins to directly edit status/statecode picklists on the Activity Entity. How can the order be edited programatically?
In another question, information is provided about how to get metadata about statuscodes and statecodes:
Dynamics Crm: Get metadata for statuscode/statecode mapping
Microsoft provides a class for sorting order of picklists:
https://learn.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg327607(v%3dcrm.8)
I have successsfully coded and can retrieve metadata for both standard picklists and for statuscodes picklists (both the statecode and statuscode). I can programatically update the sort order on standard picklists, but when attempting to do so on a statuscode optionset, no errors are thrown and no changes are published to the system.
How can the sort order on the activity statuscode field be updated?
Example code follows, complete with both tests:
namespace ConsoleApps
{
class EditAptStatusCodeOptionSetOrder
{
static void Main()
{
//Connect to Database
string CRMConnectionString = #"AuthType = Office365; URL = https://URLOFSERVER; Username=USERNAME; Password=PASSWORD;";
Console.WriteLine("Connecting to Auric Solar Sandbox Environment Using Ryan Perry's Credentials. ");
CrmServiceClient crmServiceClient = new CrmServiceClient(CRMConnectionString);
IOrganizationService crmService = crmServiceClient.OrganizationServiceProxy;
//Test Retrieving Stage (Statuscode) from Test Entity.
//Get the Attribute
RetrieveAttributeRequest retrieveStatusCodeAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "new_testentity",
LogicalName = "statuscode",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveStatusCodeAttributeResponse =
(RetrieveAttributeResponse)crmService.Execute(retrieveStatusCodeAttributeRequest);
Console.WriteLine("Retreived Attribute:" +
retrieveStatusCodeAttributeResponse.AttributeMetadata.LogicalName);
Console.WriteLine("Retreived Attribute Description:" +
retrieveStatusCodeAttributeResponse.AttributeMetadata.Description);
StatusAttributeMetadata statusCodeMetaData =
(StatusAttributeMetadata)retrieveStatusCodeAttributeResponse.AttributeMetadata;
Console.WriteLine("Metadata Description:" +
statusCodeMetaData.Description);
Console.WriteLine("Metadata IsValidForUpdate:" +
statusCodeMetaData.IsValidForUpdate.ToString());
Console.WriteLine("OptionSet Type:" +
statusCodeMetaData.OptionSet.Name.ToString());
Console.WriteLine("OptionSet Name:" +
statusCodeMetaData.OptionSet.OptionSetType.ToString());
Console.WriteLine("Retrieved Options:");
foreach (OptionMetadata optionMeta in statusCodeMetaData.OptionSet.Options)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Save Options in an array to reorder.
OptionMetadata[] optionList = statusCodeMetaData.OptionSet.Options.ToArray();
Console.WriteLine("Option Array:");
foreach (OptionMetadata optionMeta in optionList)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
var sortedOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
Console.WriteLine("Sorted Option Array:");
foreach (OptionMetadata optionMeta in sortedOptionList)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Create the request.
OrderOptionRequest orderStatusCodeOptionRequest = new OrderOptionRequest
{
AttributeLogicalName = "statuscode",
EntityLogicalName = "new_testentity",
Values = sortedOptionList.Select(X => X.Value.Value).ToArray()
};
Console.WriteLine("orderStatusCodeOptionRequest Created.");
//Execute Request. //////THIS DOESN'T THROW ERRORS, BUT DOESN'T UPDATE SYSTEM.
OrderOptionResponse orderStatusCodeResponse = (OrderOptionResponse)crmService.Execute(orderStatusCodeOptionRequest);
Console.WriteLine("Request Executed");
////////////////////////////////////////PICKLIST TEST//////////////////////////////////
Console.WriteLine("\n\nTestingPickList");
RetrieveAttributeRequest retrieveTestPicklistAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "new_testentity",
LogicalName = "new_testpicklist",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveTestPicklistAttributeResponse =
(RetrieveAttributeResponse)crmService.Execute(retrieveTestPicklistAttributeRequest);
PicklistAttributeMetadata pickListMetaData =
(PicklistAttributeMetadata)retrieveTestPicklistAttributeResponse.AttributeMetadata;
Console.WriteLine("Retrieved Picklist Options:");
foreach (OptionMetadata optionMeta in pickListMetaData.OptionSet.Options)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Save Options in an array to reorder.
OptionMetadata[] picklistOptionList = pickListMetaData.OptionSet.Options.ToArray();
Console.WriteLine("Picklist Option Array:");
foreach (OptionMetadata optionMeta in picklistOptionList)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
var sortedPicklistOptionList = picklistOptionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
Console.WriteLine("Picklist Sorted Option Array:");
foreach (OptionMetadata optionMeta in sortedPicklistOptionList)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Create the request.
OrderOptionRequest orderPicklistOptionRequest = new OrderOptionRequest
{
AttributeLogicalName = "new_testpicklist",
EntityLogicalName = "new_testentity",
Values = sortedPicklistOptionList.Select(X => X.Value.Value).ToArray()
};
Console.WriteLine("orderPicklistOptionRequest Created.");
//Execute Request.
OrderOptionResponse orderPicklistResponse = (OrderOptionResponse)crmService.Execute(orderPicklistOptionRequest);
Console.WriteLine("Order Picklist Request Executed");
//Publish All.
Console.WriteLine("Publishing. Please Wait...");
PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
crmService.Execute(publishRequest);
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}

Using Soap Creating new Record in Dynamics crm 2013?

I'm trying to create a new record using soap call but its getting error at GenerateAuthenticattionHeader is undefined.could any references appreciated.
function new_record()
{
debugger;
var firstname = "srini";
var lastname = "hsk";
var donotbulkemail = "true";
var address1_stateorprovince = "CHD";
var address1_postalcode = "160036";
var address1_line1 = "#1429/2";
var address1_city = "Chandigarh";
var authenticationHeader = GenerateAuthenticationHeader();
// Prepare the SOAP message.
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
authenticationHeader +
"<soap:Body>" +
"<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
"<entity xsi:type='contact'>" +
"<address1_city>" + address1_city + "</address1_city>" +
"<address1_line1>" + address1_line1 + "</address1_line1>" +
"<address1_postalcode>" + address1_postalcode + "</address1_postalcode>" +
"<address1_stateorprovince>" + address1_stateorprovince + "</address1_stateorprovince>" +
"<donotbulkemail>" + donotbulkemail + "</donotbulkemail>" +
"<firstname>" + firstname + "</firstname>" +
"<lastname>" + lastname + "</lastname>" +
"</entity>" +
"</Create>" +
"</soap:Body>" +
"</soap:Envelope>";
// Prepare the xmlHttpObject and send the request.
var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Create");
xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq.setRequestHeader("Content-Length", xml.length);
xHReq.send(xml);
// Capture the result
var resultXml = xHReq.responseXML;
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0) {
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
}
GetAuthenticationHeader undefined in dynamics crm 2013
Generally your code looks good with one exception. It is good for CRM 4.0. In case you use CRM 2013 your code would not work. Recheck following articles regarding Creation of records in CRM: http://msdn.microsoft.com/en-us/library/gg334427.aspx
Provided link demonstrates how to create records using REST. In case you anyway want to use SOAP recheck following article: http://mileyja.blogspot.com/2011/04/create-requests-in-net-and-jscript-in.html

List domain users with wmi

I want to list all users of a Windows domain with WMI in C#.
Can someone help me?
Here is my code:
try
{
ConnectionOptions connection = new ConnectionOptions();
connection.Username = user;
connection.Authority = "ntlmdomain:" + domain;
connection.Password = pwd;
SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");
ManagementScope scope = new ManagementScope(#"\\FullComputerName\\root\\CIMV2", connection);
scope.Connect();
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Account Type: " + queryObj["AccountType"]);
Console.WriteLine("Caption: " + queryObj["Caption"]);
Console.WriteLine("Description: " + queryObj["Description"]);
Console.WriteLine("Disabled: " + queryObj["Disabled"]);
Console.WriteLine("Domain: " + queryObj["Domain"]);
Console.WriteLine("Full Name: " + queryObj["FullName"]);
Console.WriteLine("Local Account: " + queryObj["LocalAccount"]);
Console.WriteLine("Lockout: " + queryObj["Lockout"]);
Console.WriteLine("Name: " + queryObj["Name"].ToString());
Console.WriteLine("Password Changeable: " + queryObj["PasswordChangeable"]);
Console.WriteLine("Password Expires: " + queryObj["PasswordExpires"]);
Console.WriteLine("Password Required: " + queryObj["PasswordRequired"]);
Console.WriteLine("SID: " + queryObj["SID"]);
Console.WriteLine("SID Type: " + queryObj["SIDType"]);
Console.WriteLine("Status: " + queryObj["Status"]);
Console.WriteLine("");
}
}
catch (ManagementException err)
{
Console.WriteLine("An error occured while querying for WMI data: " + err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
Console.WriteLine("Connection error " + "(user name or password might be incorrect): " + unauthorizedErr.Message);
}
There's a typo in the namespace path in your ManagementScope constructor:
ManagementScope scope = new ManagementScope(#"\\FullComputerName\\root\\CIMV2", connection);
The string should be either #"\\FullComputerName\root\CIMV2" or "\\\\FullComputerName\\root\\CIMV2".
Note that you cannot specify the user account for local connections. So if FullComputerName is a local computer, use this instead:
ManagementScope scope = new ManagementScope("root\\CIMV2");

Blackberry BrowserField : How to show images in Blackberry without rendering problems?

I'm trying to render images using BrowserField . But i'm having the problem that images shows like this (bad rendering):
The image is bigguer than screen , and i have used this code to load it:
public ImagesScreen(String urlImage,int number)
{
super(VERTICAL_SCROLL | HORIZONTAL_SCROLL);
BrowserFieldConfig config = new BrowserFieldConfig();
config.setProperty(BrowserFieldConfig.USER_SCALABLE, Boolean.TRUE);
browserField = new BrowserField(config);
scale = initscale = Float.valueOf(formatNumber(((float) 1 / (1703 / Display.getWidth())), 8, "."));
add(browserField);
Log.info("scala " + scale);//" + scale + "
String htmlContent = "<html><meta name='viewport' content='width = device-width,maximum-scale=10.0, minimum-scale=0.001, initial-scale=" + scale + ", user-scalable=yes' /><body style='margin: 0px;padding: 0px;float: left;'>";
for (int i = 1; i <= number;i++)
{
htmlContent += "<img width='1703' alt='' src='" + urlImage + "000"+i+".png"+"'/>";
}
System.out.println(urlImage);
htmlContent += "</body></html>";
browserField.displayContent(htmlContent, "http://localhost");
UiApplication.getUiApplication().pushScreen(this);
};
If i let the scale be 1 , it stills having that problem. Thanks for reading :) .
Let the BrowserField do all the work:
String imgFile = "..."; // here the image file pathname
String style = "..."; // here the css style
String imgTag = "<div class=\"image\"> <img src="
+ imgFile
+ "></img></div><div class=\"clear\"></div>";
String browserContent = "<html><style>" + style + "</style>" + imgTag + "</html>";
byte[] contentBytes;
try {
contentBytes = browserContent.getBytes("UTF-8");
browser.displayContent(contentBytes, "text/html; charset=UTF-8", "");
} catch (UnsupportedEncodingException e) {
...
}

Resources