C# Unable to Bind EmailMessage - c#

I have a method which converts Email to .eml format.
However, the statement of EmailMessage.Bind suddenly stops working without any error.
Below is my code snippet:
public static string convertEmailToEml(EmailMessage emailMessage, string caseNumber, string EMLSaveFilePath)
{
Console.WriteLine(emailMessage.Subject); //correct value
Console.WriteLine(caseNumber); //correct value
Console.WriteLine(EMLSaveFilePath); //correct value
Console.WriteLine(emailMessage.Id); //correct value
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
PropertySet props = new PropertySet(EmailMessageSchema.MimeContent);
var email = EmailMessage.Bind(service, emailMessage.Id, props); //not executed
string emlFullPath = EMLSaveFilePath + caseNumber + ".eml"; //not executed
Console.WriteLine(emlFullPath); //code not reached
Console.ReadKey();
using (FileStream fs = new FileStream(emlFullPath, FileMode.Create, FileAccess.Write))
{
fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
}
return emlFullPath;
}
May I know if there are any places that I can look into?
There were warning messages upon solution building as follows, not sure if they are linked:
Found conflicts between different versions of the same dependent
assembly that could not be resolved. These reference conflicts are
listed in the build log when log verbosity is set to detailed.
Exception Thrown during Debug Mode:
'Microsoft.Exchange.WebServices.Data.ServiceLocalException' in
Microsoft.Exchange.WebServices.dll("The Url property of the
ExchangeService object must be set.")
I have verified that service, emailMessage.Id, and props values are not null.

Based on the documentation for `EmailMessage.Bind(...), it states that this method results in a call to Exchange Web Services (EWS).
You create an instance of ExchangeService but you do not provide a URL to it (documentation). This is a requirement. The exception that is thrown is pointing you directly at the missing data.

Related

WSDL generated service reference returning null

Im have some issues with a service reference to an external source (added it using the supplied wsdl in Visual Studio 2015).
The situation is that the request i run seems to reach the server fine. I also seems to get a response of the expected xml format (added TextWriterTraceListener). But the OutType class i get back in the code (in this case the GetBankCertificateOutType) is always null.
The console application ive built to illustrate is very simple, utilizing the public test account. It looks as follows:
static void Main(string[] args)
{
//instantiates client from the service reference
var client = new PkiServicePortTypeClient();
var time = DateTime.UtcNow;
Random r = new Random();
string reqId = r.Next(100, 999).ToString();
var outType = client.GetBankCertificate(*full params on github*);
//This line will throw nullexception since outType is always null
//BUT a valid response is actually received (although returning aa application statusCode that represents error at this stage)
var response = outType.GetBankCertificateResponse;
}
Ive tried to locate the problem but have been unsuccessful sofar. So wanted to see if someone has some good tip on how to debug this or perhaps has a solution.
I built a complete, minimal, console sample project (including the source wsdl) to illustrtate the issue which is located here.
I've downloaded and inspected your solution, and I found this in trace.log
GetBankCertificateRequest at tribute {http://www.w3.org/XML/1998/namespace}id had invalid value '360817' of type '{http://www .w3.org/2001/XML Schema}ID'
After I played with id value of GetBankCertificateRequest I got back the right value (instead of null).
var outType = client.GetBankCertificate(new GetBankCertificateInType {
RequestHeader = new RequestHeaderType {
SenderId = "360817",
CustomerId = "360817",
RequestId = reqId,
Environment = EnvironmentType.test,
EnvironmentSpecified = true,
InterfaceVersion = "1",
Timestamp = time
},
GetBankCertificateRequest = new GetBankCertificateRequest {
BankRootCertificateSerialNo = "1111110002",
//id = "",
RequestId = reqId,
Timestamp = time
}
});
There is no description for this property according to documentation (PKI service description v2.3.pdf) except some xml type annotation (xml:id). The concrete schema description is missing.

AWS Machine Learning RealTimePredictor returns UnknownoperationException in C#

Using Visual Studio, and AWS .NET V 3.0.
I'm trying to perform a real-time Predict operation, and to verify the basic setup works, I first perform a GetMLModel() which works and returns the endpoint (Somewhere in the documentation is was mentioned to use that result as the service endpoint, but it's the same that is listed in the console). Is has status "READY", so far so good.
The exception occurs below on the line below "Prediction P = RTP.Predict(Data)". Data contains a Dictionary with all the prediction values.
Error: Error making request with Error Code UnknownOperationException and Http Status Code BadRequest. No further error information was returned by the service.
public static APIResult GetRealTimePrediction(Dictionary<string, string> Data, string PayloadJSON = null) {
AmazonMachineLearningConfig MLConfig = new AmazonMachineLearningConfig();
MLConfig.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
MLConfig.Validate();
AmazonMachineLearningClient MLClient = new AmazonMachineLearningClient("xxx", "xxx", MLConfig);
GetMLModelResponse MLMOdelResp = MLClient.GetMLModel("xxx"); // <-- WORKS
MLConfig.ServiceURL = MLMOdelResp.EndpointInfo.EndpointUrl;
Console.WriteLine(MLConfig.ServiceURL);
MLConfig.Validate();
Amazon.MachineLearning.Util.RealtimePredictor RTP = new Amazon.MachineLearning.Util.RealtimePredictor(MLClient, "xxx");
Prediction P = RTP.Predict(Data); // <----------------EXCEPTION HERE
}
(Obviously replace xxx with relevant values) :)
It turns out that this line:
MLConfig.ServiceURL = MLMOdelResp.EndpointInfo.EndpointUrl;
cases the MLConfig.RegionEndpoint to be reset. Even though the documentation indicates the RegionEndpoint can be determined from the ServiceURL (I'm pretty sure I read that), the RegionEndpoint needs to be set again before the RTP.Predict(Data) call.
Once I figured that out, I was able to reduce the code to just this, in case anyone else needs help. I guess adding too much information to the Configuration is NOT a good thing, as the AWS. NET library seems to figure all this out on its own.
public static APIResult GetRealTimePrediction(Dictionary<string, string> Data, string PayloadJSON = null) {
AmazonMachineLearningConfig MLConfig = new AmazonMachineLearningConfig();
MLConfig.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
MLConfig.Validate(); // Just in case, not really needed
AmazonMachineLearningClient MLClient = new AmazonMachineLearningClient("xxx", "xxx", MLConfig);
Amazon.MachineLearning.Util.RealtimePredictor RTP = new Amazon.MachineLearning.Util.RealtimePredictor(MLClient, "xxx");
Prediction P = RTP.Predict(Data);
}

Google Drive API v2: InsertMediaUpload - Null response received

Using: Drive v2: 1.5.0.99 Beta, .NET Framework: 4.5
The authentication takes place properly (using impersonation) - via service account (AssertionFlowClient).
Access token is obtained. Service account has been granted domain wide privileges
I am able to get the parent folder - ID (strRootFolder) via Service.Files.List();
byte[] byteArray = System.IO.File.ReadAllBytes(FileName);
Google.Apis.Drive.v2.Data.File flUpload = new Google.Apis.Drive.v2.Data.File();
flUpload.Title = Title;
flUpload.Description = Description;
flUpload.MimeType = MimeType;
flUpload.Parents = new List<ParentReference>() { new ParentReference() { Id = strRootFolder } };
Google.Apis.Drive.v2.FilesResource.InsertMediaUpload drvRequest = drvService.Files.Insert(flUpload, new System.IO.MemoryStream(byteArray), "text/plain");
drvRequest.Upload();
However Upload method does not send any request. No exception is thrown. Fiddler trace shows no request has been sent and hence request.responsebody is always null.
Am I missing something ?
If some exception occur during the upload, the return object (IUploadProgress) should contain the exception (take a look at the Exception property).
Please check what is the exception.
You should also consider using UploadAsync which doesn't block your code (but first you should understand what is the exception)
You should look into Exception from your upload, that will give you a better idea of the actual problem.
Sample code:
var progress = request.Upload();
if (progress.Exception != null)
{
//Log execption, or break here to debug
YourLoggingProvider.Log(progress.Exception.Message.ToString());
}

Lists.AddAttachment throws object reference error

I'm trying to add an attachment to a list item I just created on a sharepoint server using CAML. The code below is simplified (for example the path is normally a variable and the 2nd field (the item id, here 16847) is normally the id I get back from my insert statement in CAML).
This is my code:
String desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
String savePath = desktopPath + #"\" + "tutorials.txt";
byte[] data = GetData(savePath);
lists.AddAttachment("Tasks", "16847", "tutorials.txt", data);
I'm getting this error:
Unable to update the security according your changes. The following exception occurred during ItemUpdating: Object reference not set to an instance of an object.
See Event Viewer for more information.0x81020089
getdata is a method which converts the file on my desktop to a byte[]. data is not empty and it looks okay.
Other than that Tasks is the List needed and 16847 is the task id in which to add the attachment.
Most of the info I can find is about a different error: the index out of range exception (like on the msdn page: http://msdn.microsoft.com/en-us/library/lists.lists.addattachment(v=office.12).aspx).
I've also tried a http put (unauthorized access, obviously) and the copy service (I can post this code if we can't find the solution to the simpler way above).
Can anyone tell me what is wrong?
EDIT 1:
private dcp.Lists lists = new dcp.Lists();
lists.Credentials = System.Net.CredentialCache.DefaultCredentials;
lists.Url = Values.SERVERADDRESS + "/_vti_bin/lists.asmx";
This initializes the connection to our web service. It works perfectly fine for updates, inserts...
GetData code:
private byte[] GetData(String savePath)
{
byte[] contents;
using (FileStream fStream = File.OpenRead(savePath))
{
contents = new byte[fStream.Length];
sFileName = fStream.Name;
fStream.Read(contents, 0, Convert.ToInt32(fStream.Length));
}
return contents;
}
EDIT 2:
Note that the following does work (I get a correct list of existing attachments from the task):
XmlNode ndAttach = lists.GetAttachmentCollection("Tasks", "16847");
MessageBox.Show(ndAttach.OuterXml);
And the following doesn't (same error as for the AddAttachment method):
lists.DeleteAttachment("Tasks", "16847", ndAttach.ChildNodes[0].InnerText);
Whereas I'm quite certain this should work since it does exactly the same as the example code on msdn: http://msdn.microsoft.com/en-us/library/lists.lists.deleteattachment(v=office.12).aspx
The code above is fine, the error occured on our server. When adding an attachment, no contenttype is given in the xml. This was programmed to throw an error because we've always used this method to update and add new items. So we removed the contenttype out of the underlying code and it works like a charm.

Programmatically access Enterprise Library Logging configuration (object model)?

I'm using Enterprise Library 3.1 and want to programmatically access the Logging Block (runtime, object model) specifically its Trace Listeners and Sources.
For example, I want to access the Filename property of a trace listener object so I can know where the log file is located on disk.
Update: Looking for answers that use the runtime object model, not by parsing the XML configuration.
You can access the logging configuration programmatically using the object model (used for configuration).
To get the specific data for the trace listener you should look at TraceListenerData (and the specific subclasses).
This example shows how to read in the configuration and then get the TraceListeners:
// Open config file
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = #"MyApp.exe.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
// Get EL log settings
LoggingSettings log = config.GetSection("loggingConfiguration") as LoggingSettings;
// Get TraceListener info
foreach(TraceListenerData listener in log.TraceListeners)
{
// Check for listener types you care about
if (listener is RollingFlatFileTraceListenerData)
{
RollingFlatFileTraceListenerData data = listener as RollingFlatFileTraceListenerData;
Console.WriteLine(string.Format("Found RollingFlatFileLIstener with Name={0}, FileName={1}, Header={2}, Footer={3}, RollSizeKB={4}, TimeStampPattern={5},RollFileExistsBehavior={6}, RollInterval={7}, TraceOutputOptions={8}, Formatter={9}, Filter={10}",
data.Name, data.FileName, data.Header, data.Footer, data.RollSizeKB,
data.TimeStampPattern, data.RollFileExistsBehavior, data.RollInterval,
data.TraceOutputOptions, data.Formatter, data.Filter);
}
else // other trace listener types e.g. FlatFileTraceListenerData
{
}
}
Apparently some needed info is privately encapsulated in a LogWriterStructureHolder instance (its field is named structureHolder) on the Enterprise Library Logger.Writer instance (of Type LogWriter).
So I'm effectively looking for: Logger.Writer.structureHolder (but that field is private).
I used reflection to pull it out....
These are the significant namespaces:
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Logging;
This is reflection code to pull out the needed private data:
// Get the private field.
FieldInfo fiLogStructHolder
= typeof(LogWriter).GetField("structureHolder", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
// Obtain field value to get the private data.
LogWriterStructureHolder structureHolder
= (LogWriterStructureHolder)fiLogStructHolder.GetValue(Logger.Writer);
// Access the value's .TraceSources property of Type Dictionary<string, LogSource>.
// The string is the name of the category from configuration.
int numSources = structureHolder.TraceSources.Count;
// Furthermore, access the listeners of any logging source by specifying:
int numListeners = structureHolder.TraceSources[0].Listeners.Count
// ^-- Note: Picked first source for example.
If anybody can find a non-private entry point for this same data please post it in an answer. Thanks.
Kudos to .NET Reflector for facilitating this answer.
public static EmailTraceListenerData GetEmailLogConfiguration()
{
var rootWebConfig1 = WebConfigurationManager.OpenWebConfiguration("/");
var section = rootWebConfig1.GetSection("loggingConfiguration");
var loggingSection = section as Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings;
if (loggingSection != null) {
// Reference to Microsoft.Practices.EnterpriseLibrary.Logging.dll and
// Microsoft.Practices.EnterpriseLibrary.Common.dll required for the code below
foreach (Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.TraceListenerData listener in loggingSection.TraceListeners) {
var emailTraceListenerData = listener as EmailTraceListenerData;
if (emailTraceListenerData != null) {
// Can obtain FromAddress, ToAddress, SmtpServer and SmtpPort
// as property of emailTraceListenerData;
return emailTraceListenerData;
}
}
}
return null;
}
Web.config file is as follow:
For Windows application, you can open the .config file withSystem.Configuration.ConfigurationManager.OpenExeConfigurationinstead of WebConfigurationManager.
The other answers seem very verbose, here is my solution:
public static TraceListenerData GetTraceListener(string name)
{
var log = ConfigurationManager.GetSection("loggingConfiguration") as LoggingSettings;
return log.TraceListeners.Single(tl => tl.Name == name);
}
Once you've called this helper method you can cast the result to whatever type the listener is such as RollingFlatFileTraceListenerData, EmailTraceListenerData, FormattedEventLogTraceListenerData, FormattedDatabaseTraceListenerData

Categories