Posts Tagged Convert
WCF and Email Attachments
Posted by Kelly's Chronicles in .NET, C#, MVC, WCF on September 27, 2015
First off I want to apologize for being away so long. It has been a crazy ride to say the least.
So a colleague of mine ran into an issue with WCF and emailing attachments and asked for help. In this block of code below it would always fail at:
Attachment attachment = new Attachment(fileAttachment.ContentStream, fileAttachment.Name);” The error is : “Value cannot be null.
Parameter name: stream”
EmailSendInput emailSendInput = new EmailSendInput
{
Attachments = new List<Attachment>(),
Body = model.Body,
To = new List<string> { model.EmailTo },
From = model.EmailFrom,
Subject = model.EmailSubject
};
if (model.Files != null)
{
foreach (var currAttachment in model.Files)
{
if (currAttachment != null && currAttachment.ContentLength > 0)
{
// the filename needs to be nice looking
string fileName =
currAttachment.FileName.Substring(
currAttachment.FileName.LastIndexOf(@”\”, System.StringComparison.Ordinal) + 1,
currAttachment.FileName.Length
– currAttachment.FileName.LastIndexOf(@”\”, System.StringComparison.Ordinal) – 1);
var attachment = new Attachment(currAttachment.InputStream, fileName);
emailSendInput.Attachments.Add(attachment);
}
}
}
B2BMortgageDataServiceAgent b2BMortgageDataServiceAgent = new B2BMortgageDataServiceAgent();
EmailSendResponse emailSendResponse = b2BMortgageDataServiceAgent.SendEmail(emailSendInput);
if (!emailSendResponse.Success)
{
throw new Exception(emailSendResponse.Message);
}
}
public EmailSendResponse SendEmail(EmailSendInput input)
{
EmailSendResponse retVal = new EmailSendResponse();
try
{
string smtpServer = “”
string smtpPort = “”
using (var client = new SmtpClient(smtpServer, Convert.ToInt32(smtpPort)))
{
var mail = new MailMessage
{
From = new MailAddress(input.From),
Subject = input.Subject,
Body = input.Body
};
input.To.ForEach(t => mail.To.Add(t));
if (input.Attachments != null && input.Attachments.Count > 0)
{
foreach (var fileAttachment in input.Attachments)
{
//Code Crashes here
Attachment attachment = new Attachment(fileAttachment.ContentStream, fileAttachment.Name);
mail.Attachments.Add(attachment);
}
}
client.Send(mail);
}
retVal.Success = true;
}
catch (Exception exception)
{
retVal.Success = false;
LogUtil.LogException(exception);
retVal.Message = exception.ToString();
}
return retVal;
}
and then the contract:
[DataContract]
public class EmailSendInput
{
[DataMember]
public string From { get; set; }
[DataMember]
public List<string> To { get; set; }
[DataMember]
public string Subject { get; set; }
[DataMember]
public string Body { get; set; }
[DataMember]
public List<Attachment> Attachments { get; set; }
}
Implemented as:
public EmailSendResponse SendEmail(EmailSendInput input)
{
try
{
return this.dataAgent.SendEmail(input);
}
catch (Exception e)
{
this.logger.LogException(e, 2);
throw new FaultException(“An error occured in SendEmail. Error details : ” + this.BuildMessage(e));
}
}
and the Email response:
[DataContract]
public class EmailSendResponse
{
[DataMember]
public bool Success { get; set; }
[DataMember]
public string Message { get; set; }
}
So now we have the problem. I basically had to recreate his datamember for attachment in the contract EmailSendInput to a
public List<EmailEncodedAttachment> Attachments { get; set; }
and added a new contract called EmailEncodedAttachment and process how he was handling the attachment differently. I’ve also included the MVC controller calls in case it might help you as well.
SOLUTION:
[DataContract]
public class EmailSendInput
{
[DataMember]
public string From { get; set; }
[DataMember]
public List<string> To { get; set; }
[DataMember]
public string Subject { get; set; }
[DataMember]
public string Body { get; set; }
[DataMember]
public List<EmailEncodedAttachment> Attachments { get; set; }
}
[DataContract]
public class EmailEncodedAttachment
{
[DataMember]
public string Base64Attachment;
[DataMember]
public string Name;
/// <summary>
/// One of the System.Net.Mime.MediaTypeNames
/// </summary>
[DataMember]
public string MediaType;
}
}
retVal.Message = exception.ToString();
}
return retVal;
}
public EmailSendResponse SendEmail(EmailSendInput input)
{
EmailSendResponse retVal = new EmailSendResponse();
try
{
string smtpServer = ConfigurationManager.AppSettings[“SmtpServer”] ?? “url”;
string smtpPort = ConfigurationManager.AppSettings[“SmtpPort”] ?? “portnum”;
using (var client = new SmtpClient(smtpServer, Convert.ToInt32(smtpPort)))
{
var mail = new MailMessage
{
From = new MailAddress(input.From),
Subject = input.Subject,
Body = input.Body
};
input.To.ForEach(t => mail.To.Add(t));
if (input.Attachments != null && input.Attachments.Count > 0)
{
foreach (var fileAttachment in input.Attachments)
{
mail.Attachments.Add(this.CreateAttachment(fileAttachment));
}
}
client.Send(mail);
}
retVal.Success = true;
}
catch (Exception exception)
{
retVal.Success = false;
LogUtil.LogException(exception);
retVal.Message = exception.ToString();
}
return retVal;
}
The MVC controller action calls the service like so:
EmailSendInput emailSendInput = new EmailSendInput
{
Attachments = new List<EmailEncodedAttachment>(),
Body = model.Body,
To = new List<string> { model.EmailTo },
From = model.EmailFrom,
Subject = model.EmailSubject
};
if (model.Files != null)
{
foreach (var file in model.Files)
{
if (file != null && file.ContentLength > 0)
{
// the filename needs to be nice looking
string prettyFileName =
file.FileName.Substring(
file.FileName.LastIndexOf(@”\”, System.StringComparison.Ordinal) + 1,
file.FileName.Length
– file.FileName.LastIndexOf(@”\”, System.StringComparison.Ordinal) – 1);
var attachment = this.CreateAttachment(prettyFileName, file.InputStream);
emailSendInput.Attachments.Add(attachment);
}
}
}
B2BMortgageDataServiceAgent b2BMortgageDataServiceAgent = new B2BMortgageDataServiceAgent();
EmailSendResponse emailSendResponse = b2BMortgageDataServiceAgent.SendEmail(emailSendInput);
if (!emailSendResponse.Success)
{
throw new Exception(emailSendResponse.Message);
}
and finally the encoding method which makes this possible:
private EmailEncodedAttachment CreateAttachment(string fileName, Stream stream)
{
EmailEncodedAttachment att = new EmailEncodedAttachment
{
Name = fileName,
MediaType = System.Net.Mime.MediaTypeNames.Text.Plain
};
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
att.Base64Attachment = Convert.ToBase64String(buffer);
return att;
}
There you have it folks. I hope you have a great Sunday!
.NET, action, AppSettings, Attachment, Attachments, Body, BuildMessage, byte, c#, client, CODE, colleague, ConfigurationManager, ContentLength, ContentStream, controller, Convert, Count, Crashes, CreateAttachment, DataContract, DataMember, Email, EmailEncodedAttachment, EmailFrom, EmailSendInput, EmailSendResponse, EmailSubject, EmailTo, error, Exception, FaultException, filename, Files, foreach, From, InputStream, LastIndexOf, Length, List, LogException, LogUtil, MailMessage, MediaType, MediaTypeNames, Message, method, Mime, MVC, Name, Ordinal, parameter, Plain, prettyFileName, Read, response, retVal, Send, SendEmail, SmtpClient, SmtpPort, SmtpServer, solution, Stream, StringComparison, Subject, System, Text, Value, WCF
Encryption and Decryption of strings with C#
Posted by Kelly's Chronicles in .NET, C#, vb.net on July 11, 2014
Well I am checking out the Beale Street Historic District for the first time in Memphis, TN tonight. I have heard a lot about it since my arrival here so am excited to get to go. I think it will be fun.
Of course this would come up. I had written this previously in vb.net and I had the opportunity to use it again today. Of course in doing so, I discovered a bad coding practice violation I had committed. I had failed to return a value in my function’s Catch block of my code. C# doesn’t let you off the hook so easily and will bug you till you fix it. As noted previously, topic is encryption and decryption of strings. It is straightforward but you might find it useful. Simply pass in the string you want to encrypt/decrypt and the key you want to use.
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class Crypto
{
private static TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
private static MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
public static byte[] MD5Hash(string value)
{
return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value));
}
public static string Encrypt(string stringToEncrypt, string key)
{
DES.Key = Crypto.MD5Hash(key);
DES.Mode = CipherMode.ECB;
byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt);
return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length));
}
public static string Decrypt(string encryptedString, string key)
{
try
{
DES.Key = Crypto.MD5Hash(key);
DES.Mode = CipherMode.ECB;
byte[] Buffer = Convert.FromBase64String(encryptedString);
return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length));
}
catch (Exception ex)
{
MessageBox.Show(“Invalid Key”, “Decryption Failed”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
// Inserted the following ‘return’ since all code paths must return a value in C#:
return null;
}
}
And now it’s usage…..
public class Form1
{
private void Button1_Click(object sender, System.EventArgs e)
{
string key = Microsoft.VisualBasic.Interaction.InputBox(“Enter a Key:”, “”, “”, -1, -1);
Label1.Text = Crypto.Encrypt(TextBox1.Text, key);
TextBox1.Clear();
}
private void Button2_Click(object sender, System.EventArgs e)
{
string key = Microsoft.VisualBasic.Interaction.InputBox(“Enter a Key:”, “”, “”, -1, -1);
TextBox1.Text = Crypto.Decrypt(Label1.Text, key);
}
}
arrival, ASCII, Beale, Buffer, byte, Catch, CipherMode, Clear, ComputeHash, Convert, CreateDecryptor, CreateEncryptor, Crypto, Cryptography, Decrypt, Decryption, District, Encrypt, Encryption, Enter, EventArgs, Exception, Exclamation, Facebook, GetBytes, Historic, InputBox, Interaction, Invalid, Join, Length, Memphis, MessageBox, MessageBoxButtons, MessageBoxIcon, Microsoft, Mode, paths, sender, situation, Street, stringToEncrypt, System, Text, topic, TransformFinalBlock, TripleDESCryptoServiceProvider, usage, violation, VisualBasic
Create Computer Account in Active Directory and add it to Domain with C#
Posted by Kelly's Chronicles in .NET, C#, Computers and Internet on July 10, 2014
I was asked to convert this code from my original post to C# by a friend who obviously didn’t want to do it himself. There was one conversion issue along the way I also fixed which is why I suspect he didn’t convert it himself. In other news, my assimilation into Memphis, TN is going well. I am slowly becoming accustomed to the heat and humidity and am trying to fight off the urge to eat everything in sight because the food is just amazing if a tad bit unhealthy. I finally am getting my car fixed and am looking forward to getting out and seeing this town for myself. Let’s hope it will be a lot of fun. Ok back to what you came here for. Here you go…..
DirectoryEntry Entry = new DirectoryEntry(“LDAP://” + ActiveDirectoryTree.SelectedNode.Name, strDomain + “\\” + strUser, strPass, AuthenticationTypes.Secure);
string ComputerName = null;
string CompSystem = null;
int ComputerCount = ComputerList.Items.Count;
int i = 0;
for (i = 0; i <= ComputerCount – 1; i++)
{
CompSystem = ComputerList.Items(i).Text;
DirectoryEntry ComputerEntry = Entry.Children.Add(“CN=” + CompSystem + “”, “Computer”);
ComputerEntry.Properties(“sAMAccountName”).Value = “” + CompSystem + “”;
ComputerEntry.CommitChanges();
int exp = Convert.ToInt32(ComputerEntry.Properties(“UserAccountControl”).Value);
ComputerEntry.Properties(“UserAccountControl”).Value = exp | 0x1;
ComputerEntry.CommitChanges();
int val = Convert.ToInt32(ComputerEntry.Properties(“UserAccountControl”).Value);
ComputerEntry.Properties(“UserAccountControl”).Value = val & ~0x2;
ComputerEntry.CommitChanges();
ComputersCreated.Text = ComputersCreated.Text + CompSystem + Environment.NewLine;
ComputerEntry.Close();
ComputerEntry.Dispose();
}
ComputersCreated.Text = ComputersCreated.Text + “——————————” + Environment.NewLine;
Entry.Close();
Entry.Dispose();
and to add to the domain:
string[] args = new string[5];
string[] args2 = new string[3];
// The one difference from the vb.net version. Commented this declaration since looping variables in ‘foreach’
//loops are declared in the ‘foreach’ header in C#:
// ManagementObject comp = null;
ManagementObjectCollection comps = null;
ManagementClass clsComps = new ManagementClass(“Win32_ComputerSystem”);
comps = clsComps.GetInstances();
foreach (ManagementObject comp in comps)
{
// this == used to join the domain
args[0] = “DOMAIN to join”;
args[1] = “Password”;
args[2] = “User with domain privs”;
args[3] = “Specify OU Here (ou=test,dc=domain,dc=com)”;
args[4] = “1”;
UInt32 retVal = 0;
retVal = comp.InvokeMethod(“JoinDomainOrWorkgroup”, args);
retval2 = Convert.ToString(retVal);
if (retval2 == “0”)
{
MessageBox.Show(“Welcome to the domain”);
Close();
}
else
{
End If
}
.NET, Account, Active, ActiveDirectoryTree, assimilation, AuthenticationTypes, c#, Children, Close, clsComps, CommitChanges, CompSystem, computer, ComputerCount, ComputerEntry, ComputerList, ComputerName, Convert, Count, Create, declaration, difference, Directory, DirectoryEntry, Dispose, Domain, Entry, environment, Facebook, food, foreach, friend, GetInstances, header, Here, InvokeMethod, items, Join, JoinDomainOrWorkgroup, LDAP, ManagementClass, ManagementObject, ManagementObjectCollection, Memphis, MessageBox, Name, NewLine, news, Password, properties, retVal, Secure, SelectedNode, Specify, Text, user, UserAccountControl, Value, vb.net, version, Welcome
Convert Visio Pages to Images in vb.net
Posted by Kelly's Chronicles in .NET, C#, vb.net on January 22, 2012
I have been fooling around with Visio automation since attempting to help a friend with a project that did so. In the course of this I did this code snippet to convert the Visio page to an image. The code loops through and takes each page and converts it to an image. Pretty basic. I have not posted in a while and my apologies to those of you who were wondering….
Here is the code….
Sub SaveAsImage()
‘ creates an invisible Visio instance, opens a document, then
‘ saves all pages in the document as jpg images using
‘ page name and page number as file name
Dim vsoApp As Visio.Application
Dim vsoDoc As Visio.Document
Dim PathName As String, jpgName As String
Dim pg As Visio.Page
Set vsoApp = CreateObject(“Visio.InvisibleApp”)
‘ SET PATH/FILENAME BELOW TO VSD ON YOUR SYSTEM
Set vsoDoc = vsoApp.Documents.Open(“c:\TEST\test.vsd”)
PathName = vsoApp.Documents(1).Path ‘ Set pathname to that of first document
For Each pg In vsoApp.ActiveDocument.Pages
jpgName = PathName & Format(pg.Index, “0#”) & ” ” & pg.Name & “.jpg”
pg.Export jpgName
Next
vsoDoc.Close
vsoApp.Quit
Set vsoDoc = Nothing
Set vsoApp = Nothing
End Sub
.NET, ActiveDocument, apologies, Application, automation, Close, Convert, CreateObject, csharp, Document, Export, Format, friend, Images, index, instance, Name, PAGE, Pages, PathName, Quit, snippet, Visio, vsoApp, vsoDoc
Write Microsoft Word Document Header and Footer with C#
Posted by Kelly's Chronicles in .NET, C# on July 30, 2011
Again I am rewriting some of the more popular entries in this blog as C#. It’s good exercise for me and good for you because you get the code another way. Well at least that’s the theory! This entry writes to the header and footer of a document in Microsoft Word The vb.net version was here. The only downside to all of this is that this is only tested against Office 2010. The old version I had Office 2000, XP and 2003 on my machine. Essentially however it is the same code. If you have any questions of course please feel free to leave a comment or email me.
public void WriteHeaderandFooterinWordDocument()
{
Word.Document oDoc = new Word.Document();
oDoc.Application.Visible = true;
oDoc.Content.Application.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;// = Convert.ToInt32(Word.WdSeekView.wdSeekCurrentPageHeader);
oDoc.Content.Application.Selection.TypeText(“Martens “);
oDoc.Content.Application.Selection.Fields.Add(oDoc.Content.Application.Selection.Range, Word.WdFieldType.wdFieldEmpty, “PAGE”);
oDoc.Content.Application.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
oDoc.Content.Application.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
oDoc.Content.Application.Selection.TypeText(“Martens”);
oDoc.Content.Application.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
}
.NET, .NET Framework, ActivePane, Application, Content, Convert, csharp, Document, Facebook, Fields, Footer, header, Machine, Martens, Microsoft, Office, PAGE, Range, SeekView, Selection, TypeText, vb.net, version, View, Visible, WdFieldType, wdSeekCurrentPageHeader, WdSeekView, Word, Write
Recent Comments
Archives
- April 2018
- January 2018
- December 2017
- June 2017
- May 2017
- May 2016
- April 2016
- September 2015
- July 2014
- June 2014
- November 2012
- October 2012
- June 2012
- May 2012
- April 2012
- January 2012
- September 2011
- August 2011
- July 2011
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- August 2008
- July 2008
- June 2008
- May 2008
Get or Write Image Metadata with C#
Posted by Kelly's Chronicles in .NET, C#, vb.net on July 15, 2014
Good morning! it’s always fun when old code gets to get used again. And it gave me an opportunity to convert this snippet to C#. Basically what we are trying to do is write or get metadata to an image. As those folks who commented on the previous post noted, this code will not remove existing metadata. It is a problem I still have not found a solution for however. If any of you know the answer please let us know! Anyway here it is converted and still useable after all this time.
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.IO;
public class clsReadMetaData
{
public ImageMetadata ReadEXIFMetadata(string filepath)
{
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
Image image__1 = Image.FromStream(fs);
PropertyItem[] imagePropertyItems = image__1.PropertyItems;
ImageMetadata imageMetadata = new ImageMetadata();
foreach (PropertyItem pi in imagePropertyItems)
{
switch ((EXIFProperty)pi.Id)
{
case EXIFProperty.Title:
imageMetadata.Title = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Title = Encoding.UTF32.GetString(pi.Value)
break;
case EXIFProperty.Author:
imageMetadata.Author = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Author = Encoding.UTF8.GetString(pi.Value)
break;
case EXIFProperty.Keywords:
imageMetadata.Keywords = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Keywords = Encoding.UTF8.GetString(pi.Value)
break;
case EXIFProperty.Comments:
imageMetadata.Comments = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Comments = Encoding.UTF8.GetString(pi.Value)
break;
default:
break;
}
}
fs.Close();
return imageMetadata;
}
public void SaveEXIFMetadata(Image image, ImageMetadata metadata, string filepath)
{
SaveEXIFMetadataProperty(image, EXIFProperty.Title, metadata.Title, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Author, metadata.Author, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Keywords, metadata.Keywords, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Comments, metadata.Comments, filepath);
}
private void SaveEXIFMetadataProperty(Image image, EXIFProperty property, string propertyValue, string filepath)
{
PropertyItem propertyItem = CreatePropertyItem();
propertyItem.Id = Convert.ToInt32(property);
// Type=1 means Array of Bytes.
propertyItem.Type = 2;
propertyItem.Len = propertyValue.Length;
//propertyItem.Value = Encoding.Unicode.GetBytes(propertyValue)
propertyItem.Value = Encoding.UTF8.GetBytes(propertyValue);
image.SetPropertyItem(propertyItem);
image.Save(filepath);
}
private PropertyItem CreatePropertyItem()
{
System.Reflection.ConstructorInfo ci = typeof(PropertyItem).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null);
return (PropertyItem)ci.Invoke(null);
}
}
public enum EXIFProperty
{
Title = 40091,
Author = 40093,
Keywords = 40094,
Comments = 40092
}
public class ImageMetadata
{
private string _title = string.Empty;
private string _author = string.Empty;
private string _keywords = string.Empty;
private string _comments = string.Empty;
public ImageMetadata()
{
this._title = string.Empty;
this._author = string.Empty;
this._keywords = string.Empty;
this._comments = string.Empty;
}
public ImageMetadata(string title, string author, string keywords, string comments)
{
this._title = title;
this._author = author;
this._keywords = keywords;
this._comments = comments;
}
public string Title
{
get
{
return this._title;
}
set
{
this._title = value;
}
}
public string Author
{
get
{
return this._author;
}
set
{
this._author = value;
}
}
public string Keywords
{
get
{
return this._keywords;
}
set
{
this._keywords = value;
}
}
public string Comments
{
get
{
return this._comments;
}
set
{
this._comments = value;
}
}
}
Join me on Facebook
Anyway, Array, author, BindingFlags, Bytes, Close, Collections, Comments, ConstructorInfo, Convert, CreatePropertyItem, FileMode, filepath, FileStream, FromStream, Generic, GetBytes, GetConstructor, Image, ImageMetadata, imagePropertyItems, instance, Keywords, Length, Metadata, NonPublic, Open, PropertyItem, PropertyItems, propertyValue, Public, Read, ReadEXIFMetadata, Reflection, Save, SaveEXIFMetadata, SetPropertyItem, snippet, solution, System, Text, Title, Type, Unicode, Value, Write, _author, _comments, _keywords, _title
Leave a comment