Unable to parse tnef part from MimeMessage - mimekit

I have a MimeMessage which contains a winmail.dat attachment of type application/ms-tnef.
I believe this is an RTF formatted email, which is sent from Outlook client. I tried parsing it with the tnefpart but I'm running into the following error.
Here is my function:
ProcessMimeMessage(MimeMessage plainMime)
{
foreach (var attachment in plainMime.Attachments)
{
if (attachment.GetType() == typeof(MimeKit.Tnef.TnefPart))
{
ReportStatus("Processing Tnef Part (RTF Message): ");
MimeKit.Tnef.TnefPart tnefPart = (MimeKit.Tnef.TnefPart)attachment;
try {
MimeMessage mimeMessage = tnetPart.ConvertToMessage();
} catch (Exception ex) {printexception(ex);}
}
}
}
This is the exception that is thrown from ConvertToMessage
Invalid addr-spec token at offset 0
at MimeKit.InternetAddress.TryParseAddrspec(Byte[] text, Int32& index, Int32 endIndex, Byte[] sentinels, Boolean throwOnError, String& addrspec, Int32& at)
at MimeKit.MailboxAddress.set_Address(String value)
at MimeKit.Tnef.TnefPart.EmailAddress.TryGetMailboxAddress(MailboxAddress& mailbox)
at MimeKit.Tnef.TnefPart.ExtractMapiProperties(TnefReader reader, MimeMessage message, BodyBuilder builder)
at MimeKit.Tnef.TnefPart.ExtractTnefMessage(TnefReader reader)
at MimeKit.Tnef.TnefPart.ConvertToMessage()
Thanks

This just means that the "email address" in one of the TNEF fields is not a valid email address (syntactically).
It might just be that the address type field was not "SMTP" and MimeKit tried to parse it as if it were a rfc822 address field.
I've improved the robustness in the following commit: https://github.com/jstedfast/MimeKit/commit/15f955b49dc7743d1281afbedce6d327706e161b
You can use the MyGet packages listed in the README.md file to get the fix for this.

Related

Unable to add pdf and doc files using Recent files using Xamarin.Plugin.Filepicker

When I attach pdf and doc files using Recent files I'm getting the following exception. Can anyone help on this.
Working fine when i attach image file using Recent files
please help on this I m new to this Xamarin forms.
Thanks in advance.
at Java.Interop.JniEnvironment+InstanceMethods.CallNonvirtualObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniObjectReference type, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0008e] in <bd6bd528a8784b7caf03e9f25c9f0d7b>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeNonvirtualObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0001f] in <bd6bd528a8784b7caf03e9f25c9f0d7b>:0
at Android.Content.ContentResolver.Query (Android.Net.Uri uri, System.String[] projection, System.String selection, System.String[] selectionArgs, System.String sortOrder) [0x000a0] in /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-28/mcw/Android.Content.ContentResolver.cs:1098
at Plugin.FilePicker.IOUtil.GetDataColumn (Android.Content.Context context, Android.Net.Uri uri, System.String selection, System.String[] selectionArgs) [0x00013] in D:\a\1\s\src\Plugin.FilePicker\Android\IOUtil.android.cs:154
at Plugin.FilePicker.IOUtil.GetPath (Android.Content.Context context, Android.Net.Uri uri) [0x0017d] in D:\a\1\s\src\Plugin.FilePicker\Android\IOUtil.android.cs:111
at Plugin.FilePicker.FilePickerActivity.OnActivityResult (System.Int32 request Code, Android.App.Result resultCode, Android.Content.Intent data) [0x00054] in D:\a\1\s\src\Plugin.FilePicker\Android\FilePickerActivity.android.cs:168
--- End of stack trace from previous location where exception was thrown ---
at Plugin.FilePicker.FilePickerImplementation.PickFile (System.String[] allowedTypes) [0x00028] in D:\a\1\s\src\Plugin.FilePicker\Android\FilePickerImplementation.android.cs:60
at FileUploadPOC.MainPage.PickAndShow (System.String[] fileTypes) [0x0002e] in C:\Users\Gadda.Raju\Downloads\XamarinForms-FilePicker-master\FileUploadPOC\MainPage.xaml.cs:47
--- End of managed Java.Lang.NullPointerException stack trace ---
java.lang.NullPointerException: uri
at java.util.Objects.requireNonNull(Objects.java:245)
at android.content.ContentResolver.query(ContentResolver.java:1166)
at android.content.ContentResolver.query(ContentResolver.java:1124)
at android.content.ContentResolver.query(ContentResolver.java:1080)
at crc64424a8adc5a1fbe28.FilePickerActivity.n_onActivityResult(Native Method)
at crc64424a8adc5a1fbe28.FilePickerActivity.onActivityResult(FilePickerActivity.java:47)
at android.app.Activity.dispatchActivityResult(Activity.java:8469)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5364)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5412)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2317)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:255)
at android.app.ActivityThread.main(ActivityThread.java:8192)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
} ```
**The following code im using**
``` private async Task PickAndShow(string[] fileTypes)
{
try
{
var pickedFile = await CrossFilePicker.Current.PickFile(fileTypes);
if (pickedFile != null)
{
lblName.Text = pickedFile.FileName;
lblFilePath.Text = pickedFile.FilePath;
}
}
catch (Exception ex)
{
}
} ```
Yes, from Xamarin.Plugin.FilePicker,we know that :
This package has been deprecated as it is legacy and is no longer
maintained.
Just as SushiHangover said, you can use Xamarin.Essentials: File Picker to achieve this.
The FilePicker class lets a user pick a single or multiple files from the device.
FilePicker.PickAsync() method enables your user to pick a file from the device. You are able to specific different PickOptions when calling the method enabling you to specify the title to display and the file types the user is allowed to pick. By default.
You can refer to the following sample code:
async Task<FileResult> PickAndShow(PickOptions options)
{
try
{
var result = await FilePicker.PickAsync(options);
if (result != null)
{
Text = $"File Name: {result.FileName}";
if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
var stream = await result.OpenReadAsync();
Image = ImageSource.FromStream(() => stream);
}
}
return result;
}
catch (Exception ex)
{
// The user canceled or something went wrong
}
return null;
}
Default file types are provided with FilePickerFileType.Images, FilePickerFileType.Png, and FilePickerFilerType.Videos. You can specify custom files types when creating the PickOptions and they can be customized per platform.
For more,check:https://learn.microsoft.com/en-us/xamarin/essentials/file-picker?context=xamarin%2Fxamarin-forms&tabs=android .
Update:
For how to open an existing file, you can refer: Xamarin.Essentials; FilePicker; Save a new file .

NReco.PdfGenerator The pipe has been ended error on the server

I'm using NReco.PdfGenerator for my PDF documents(that component is based on WkHtmlToPdf tool), my code allow me to create a pdf calling a function with the parameters controller, action, model:
public static byte[] GeneratePdfDocument(System.Web.Mvc.Controller controller, string viewName, object model)
{
string result;
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
result = sw.ToString();
}
return (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(result);
}
With this code I can create a PDF easily from my views and it's working great on my development environment but on a server I'm getting this error:
The pipe has been ended.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: The pipe has been ended.
[IOException: The pipe has been ended.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +11185413
System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count) +10770013
System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count) +139
NReco.PdfGenerator.HtmlToPdfConverter.GeneratePdfInternal(String htmlFilePath, Byte[] inputBytes, String coverHtml, String outputPdfFilePath, Stream outputStream) +2166
[Exception: Cannot generate PDF: The pipe has been ended.]
NReco.PdfGenerator.HtmlToPdfConverter.GeneratePdfInternal(String htmlFilePath, Byte[] inputBytes, String coverHtml, String outputPdfFilePath, Stream outputStream) +2734
NReco.PdfGenerator.HtmlToPdfConverter.GeneratePdf(String htmlContent, String coverHtml, Stream output) +51
NReco.PdfGenerator.HtmlToPdfConverter.GeneratePdf(String htmlContent, String coverHtml) +42
I think that is maybe a problem with permissions or some configuration on my IIS, any idea?
You are probably missing Visual C++ Redistributable Packages for VS2013 (x86). Even if your server is running 64bit Windows, you need to install the x86 C++ Packages.

#HhtmlDropdown throw SerializationException Exception

I have a form that has a DropDownList. I am using SQLServer State mode to save the session in SQL Server. The form is displayed correctly; however, it throws an exception during the form submission. I've been looking and tried some of the suggested answer that were posted online with no luck. What am I doing wrong here?
//This is the section where I am building the SelectList Item in the controller
var ListDepartment = ManageUsersMembership.GetDepartment(SessionWrapper.studentBookTrade.SelectedSchoolID);
// book.DepartmentList = ListDepartment; //new SelectList(ListDepartment, "DepartmentID", "DepartmentName", SessionWrapper.studentBookTrade.SelectedDepartmentID);
List<SelectListItem> lDepartment = new List<SelectListItem>();
foreach (var item in ListDepartment)
{
if (SessionWrapper.studentBookTrade.SelectedDepartmentID > 0 && item.DepartmentID == SessionWrapper.studentBookTrade.SelectedDepartmentID)
{
lDepartment.Add(new SelectListItem { Text = item.DepartmentName, Value = item.DepartmentID.ToString(), Selected = true });
}
else
{
lDepartment.Add(new SelectListItem { Text = item.DepartmentName, Value = item.DepartmentID.ToString() });
}
}
book.DepartmentList = lDepartment;
//this is my property in the Model:
public virtual IEnumerable<SelectListItem> DepartmentList { get; set; }
//This is the HTML Code in my View:
#Html.DropDownListFor(model => model.DepartmentID, new SelectList(Model.DepartmentList, "Value", "Text"), "Select Department", new {#class="form-control", id="DepartmentID", onchange = "ValueSelected()" })
#Html.ValidationMessageFor(model => model.DepartmentID)
//The exception
Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SerializationException: Type 'System.Web.Mvc.SelectList' in Assembly 'System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +10751795
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +230
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +121
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder) +185
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) +565
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +446
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +131
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1666
[HttpException (0x80004005): Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.]
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1754
System.Web.SessionState.SessionStateItemCollection.WriteValueToStreamWithAssert(Object value, BinaryWriter writer) +34
System.Web.SessionState.SessionStateItemCollection.Serialize(BinaryWriter writer) +628
System.Web.SessionState.SessionStateUtility.Serialize(SessionStateStoreData item, Stream stream) +240
System.Web.SessionState.SessionStateUtility.SerializeStoreData(SessionStateStoreData item, Int32 initialStreamSize, Byte[]& buf, Int32& length, Boolean compressionEnabled) +62
System.Web.SessionState.SqlSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +135
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +565
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
I think you have too much here. Try changing your code this way
public IEnumerable<SelectListItem> DepartmentList { get; set; }
I usually use List but ienumerable should work too
then on your view you don't need to cast the list
#Html.DropDownListFor(model => model.DepartmentID, Model.DepartmentList, "Select Department", new {#class="form-control", id="DepartmentID", onchange = "ValueSelected()" })
the "for" helper will map the list for you. See if this helps

Windows Phone 8 send File HttpClient FileBody

Hello I'm just searching for more than 2 days...
My problem: I want to send a Post Request to a Server and send a File (FileBody) with this post.
I've found many examples for this with the WebClient class. But I am a newbee to C# and Windows Phone development and so i did not get it to work. Because the only method i see is "UploadStringAsync" but the method mentioned everywhere in the internet "UploadFile" is not available in my object.
string postdata = string.Format("cmd={0}&", "show");
postdata += string.Format("latitude={0}&", HttpUtility.UrlEncode("-1"));
...
WebClient wc = new WebClient();
wc.UploadStringAsync(new Uri("http://mydomain/myphp.php", UriKind.Absolute), "POST", postdata);
The problem is i have to send a FileBody as mentioned here: http://www.codescales.com/category/howto/
But i cant reference this project to my windows phone project.
I am very confused right now and hope anyone can help me with this.
You can use RestSharp, (Nuget it)
Contains several options to upload files:
public IRestRequest AddFile(string name, string path);
public IRestRequest AddFile(string name, Action<System.IO.Stream> writer, string fileName);
public IRestRequest AddFile(string name, byte[] bytes, string fileName);
public IRestRequest AddFile(string name, Action<System.IO.Stream> writer, string fileName, string contentType);
public IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType);

WCF REST upload file

When server side obtain a zip data package from client side.I unzip this package and parse xml data to sql server.Then return success message to client side!
but I run into problem. I woluld like to return success message to client side in time when client uploaded success but not after inserted into data to database!
Can you help me ?tks in advance! sorry for my bad english!
public IAsyncResult BeginAsyncUpload(string token, Stream data, string fileName, string Org, AsyncCallback callback, object asyncState)
{
if (BaseClass.HasPermission(token))
{
return new CompletedAsyncResult<Stream>(data, fileName,Org);
}
else
{
return null;
}
}
public string EndAsyncUpload(IAsyncResult ar)
{
Stream data = ((CompletedAsyncResult<Stream>)ar).Data;
string fileName = ((CompletedAsyncResult<Stream>)ar).FileName;
string Organization = ((CompletedAsyncResult<Stream>)ar).Org;
try
{
return _streamToFile(data, fileName, Organization);
}
catch
{
return "SUCCESS!";
}
}
THE _streamToFile method insert data into db
First thing is that you can seperate your database insertion code and call that funcation asynchronously.
refer for asynch http://msdn.microsoft.com/en-us/magazine/cc164036.aspx
Second method is, store file in folder A, create seperate win service application to read files from same folder A, extract and insert into sql.Then move to folder B.