Friday, 12 September 2014

Updating Images on the Fly

Streaming RAW Images to a Page. If you wish to stream an image to a page the easiest method is to convert it to a Binary 64 data type. Red dot This will enable IE to render the image as if it was stored on the server. Intrestingly this concept could work on the premise of playing a silent video clip at 1 frame per second in that if we store the Binary in a database we could in theory poll AJAX to and stream the image every second to the browsers image control updating it on the fly. In a company where I previously worked we used this approach to enable the user to scroll through footage as we took Keyframes every so many seconds that they could in essence watch the feed.

Monday, 1 September 2014

Force File Download

Sometimes instead of letting a user view an Image or PDF I would rather them download it, This method below Forces the File (Doc / MP3 / PDF / Images) etc.. to be downloaded rather than rendered. This can save time and bandwidth on a website rather than the user continaully streaming the data on a frequent basis.
namespace FieldOfSheep
{
public class FileDownloadExtensions
{
 public static void ForceFileDownload(MemoryStream s, string fileName)
        {
            if (HttpContext.Current != null)
            {
                var responseObject = HttpContext.Current.Response;

                if (responseObject.IsClientConnected && s != null)
                {
                    responseObject.Clear();
                    responseObject.ContentType = "application/octet-stream";
                    responseObject.AddHeader("Content-Disposition",
                        "attachment; filename=" + fileName);

                    responseObject.BinaryWrite(s.ToArray());

                    responseObject.Flush();

                    responseObject.Close();
                }
            }
        }
 }
}       

Saturday, 16 August 2014

ServiceStack Object Dump

There are times when you may need to dump an entire object to JSON for storing or for viewing, One example is to run an Object Dump on an Object or class at each step of a registraion page to see what the user is entering rather than getting final data at the end. This would help some people to see why users are dropping off the site for example. This is where 'ServiceStack.NET' comes into play - It has methods that support this functionality and one method is the 'Dump' method. Its rather simple and easy to use here is a working example.
  
  using ServiceStack.Text;
namespace FieldOfSheep
{  
  public static void Main(String[] args)
  {
     object myClass;
     var str = myClass.Dump();
    
     //Str now contains the JSON Values inside 'Object'
     
  }
}

Friday, 25 July 2014

Integer Extension

When using Linq & Lambda expressions I find it easier to write a word based approach than writing long hand. Take for example this query
var something = (from myObject in myTable where myObject.Number > 1 && myObject.Number < 10 select myObject);
We could simply make this code cleaner and easier to read by writing
var something = (from myObject in myTable where myObject.Number.IsWithin(1,10) select myObject);
And the brains behind this method is this little extension method.
namespace FieldOfSheep
{
public static class IntegerExtensions
    {
        public static bool IsWithin(this int value, int minimum, int maximum)
        {
            return value >= minimum && value <= maximum;
        }
    }
}

Thursday, 24 July 2014

Sanity Checker

Some times I need to run RegEx Scripts on text boxes. Here is a simple RegEx Sanity Checker for ASP.NET - You can download this from my SourceForge Page
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FieldOfSheep
{
    [ToolboxData("<{0}:SanityChecker runat=server>")]
    public class SanityChecker : TextBox
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Page.ClientScript.RegisterClientScriptBlock(typeof(string), "SanityChecker.js", JScript.SanityChecker, true);

            this.Attributes.Add("onkeyup", string.Format("return SanityChecker(event,'{0}');", this.ClientID));

       }
    }
}
And the JavaScript code for this is
function SanityChecker(evt, element)
{
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if(charCode > 93 && charCode < 112 || charCode > 46 && charCode < 91 || charCode > 185 && charCode < 223)
    {
        var rex = /^[^<>&\"\';]*$/;
        var value = document.getElementById(element).value;
        if(rex.test(str))
        {
            return true;
        }
        else
        {
            
            value = str.substring(0,value.length -1);
            document.getElementById(element).value = value;
        }
    }
}

Thursday, 12 June 2014

Printing a Remote Document Using Aspose.Words to a Network Printer.

Sometimes clients need to print documents from Internal non public facing websites. At times there are also user access considerations in that we do not want to give them direct access to the file. For this we allow them the option to print the document to a designated printer on their network. We can do this by creating a simple printing method that takes a URL / Downloads It on the Server / Renders It Through Aspose and Prints it to a Network printer. Step 1. Identify the Network Printer we can display printers running this command
public static void Main(string[] args)
{
     DropDownList list = new DropDownList();
     
     System.Drawing.Printing.PrinterSettings.InstalledPrinters.Cast().ForEach
     (
         y => this.ddlPrinters.Items.Add(y)            
     );
}
Step 2. Run this method
var couldPrint = PrintDocument("http://www.somesite.com/somedocument.doc", this.ddlPrinters.SelectedValue);
Which in turn runs this block of code. Step 3.
public static bool PrintDocument(string uriToDocument, string printerName)
        {
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uriToDocument);
                myReq.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]);
                WebResponse myResp = myReq.GetResponse();

                StreamReader reader = new StreamReader(myResp.GetResponseStream());

                MemoryStream ms = new MemoryStream();

                reader.BaseStream.CopyTo(ms);

                if (Path.GetExtension(uriToDocument) == ".doc" || Path.GetExtension(uriToDocument) == ".docx")
                {
 
                    Aspose.Words.Document document = new Aspose.Words.Document(ms);

                    document.Print(printerName);

                }
                return true;
            }
            catch (Exception ex)
            {
                //Log to your database here.
            }

            return false;
        }

Friday, 23 May 2014

Insert Email Into Exchange Public Folder - Adding (2 of 2)

In one of our products we are required to insert an email item into exchange, After much nail biting after realising that Microsoft Exchange WebService Documentation is extremely poor. I have come up with a solution that accepts a FileInfo Object and a FileStream and puts the file into a 'Public Folder' into exchange. Heres the code

public static void InsertIntoExchange(FileInfo file, FileStream stream)
        {
           
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    if (stream.Length == 0)
                        throw new Exception(string.Format("File Error: {0} Contains Zero Bytes",file.FullName));

                    Folder selectedPublicFolder = null;

                    //Set your Aspose Licence Here

                    MapiMessage mapiMessage = MapiMessage.FromStream(stream);
                    mapiMessage.Save(ms);

                    var properties = mapiMessage.NamedProperties.Values.Cast().ToList();

                    var propProjectId = properties.Where(y => y.NameId == "ProjectID").FirstOrDefault();
                    var propFileStatus = properties.Where(y => y.NameId == "FileStatus").FirstOrDefault();

                    if (propProjectId != null && propFileStatus != null)
                    {
                        string projectId = propProjectId.GetString();
                        Enumerators.FileStatus fileStatus = (Enumerators.FileStatus)Enum.Parse(typeof(Enumerators.FileStatus), propFileStatus.GetString());

                        if (fileStatus == Enumerators.FileStatus.Uploaded)
                        {
                              throw new Exception("File Already Uploaded");
                        }
                        else if (fileStatus == Enumerators.FileStatus.Failed)
                        {
                            throw new Exception("File Failed");
                        }
                        else
                        {
                            selectedPublicFolder = //Find Exchange Public Folder

                            if (selectedPublicFolder == null)
                            {
    throw new Exception("Public Folder Was Not Found");                                
                            }

                            FolderIdType f = new FolderIdType();
                            f.Id = selectedPublicFolder.Id.UniqueId;

                            try
                            {
                                CreateItemType ciType = new CreateItemType()
                                {
                                    MessageDisposition = MessageDispositionType.SaveOnly,
                                    MessageDispositionSpecified = true,
                                    SavedItemFolderId = new TargetFolderIdType()
                                    {
                                        Item = f
                                    },
                                    Items = new NonEmptyArrayOfAllItemsType()
                                };


                                using (MemoryStream tms = new MemoryStream())
                                {
                                    //Load AsposeLicence Again

                                    MailMessage m = MailMessage.Load(stream);
                                    m.Save(tms);

                                    MessageType msg = new MessageType()
                                    {

                                        MimeContent = new MimeContentType()
                                        {
                                            Value = Convert.ToBase64String(tms.ToArray())
                                        },

                                        IsRead = true
                                    };

                                    ExtendedPropertyType type = new ExtendedPropertyType();

                                    PathToExtendedFieldType epExPath = new PathToExtendedFieldType();
                                    epExPath.PropertyTag = "0x0E07";
                                    epExPath.PropertyType = MapiPropertyTypeType.Integer;

                                    type.ExtendedFieldURI = epExPath;
                                    type.Item = "1";

                                    msg.DateTimeSent = m.Date;
                                    
                                    msg.ExtendedProperty = new ExtendedPropertyType[1];
                                    msg.ExtendedProperty[0] = type;

                                    ciType.Items.Items = new ItemType[1];
                                    ciType.Items.Items[0] = msg;

                                    CreateItemResponseType response = Global.ExchangeServiceBinding.CreateItem(ciType);


                                    if (response.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
                                    {
                                        throw new Exception(response.ResponseMessages.Items[0].MessageText);
                                    }

                                }

                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                mapiMessage.NamedProperties.Remove(propFileStatus.Tag);

                                MapiNamedPropertyMappingStorage mappingStorage = mapiMessage.NamedPropertyMapping;
                                Guid PS_PUBLIC_STRINGS = new Guid("00020329-0000-0000-C000-000000000046");

                                // Create a named property
                                MapiProperty stringProperty = new MapiProperty(mappingStorage.GetNextAvailablePropertyId(Aspose.Email.Outlook.MapiPropertyType.PT_UNICODE),
                                                        Encoding.Unicode.GetBytes(((int)fileStatus).ToString()));

                                // Set message property
                                mapiMessage.SetProperty(stringProperty);
                                string stringNameId = "FileStatus";
                                mappingStorage.AddNamedPropertyMapping(stringProperty, stringNameId, PS_PUBLIC_STRINGS);

                                stream.Close();

                                mapiMessage.Save(file.FullName);
                            }
                        }


                    }


                    else if (propProjectId == null)
                    {
                        throw new Exception("File Failure: Project ID was not found in file: " + file.Name);

                    }
                    else if (propFileStatus == null)
                    {
                        throw new Exception("File Failure: FileStatus was not found in file: " + file.Name);
                    }
                    else
                    {
                        throw new Exception("File Failure: The File May Not Be a valid file: " + file.Name);                        
                    }
                }

            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

If however you are using Exchange 2010 the best way is to insert the object into the 'Inbox' First then perform a 'Move' operation as Exchange Mangles the Header and Mime object if a direct insert occurs. Add this at the end of the Insertion Method Above
//*Attempt to Move Item *//
                                            var newId = (((ExchangeWebServices.ItemInfoResponseMessageType)
                                                (((ExchangeWebServices.BaseResponseMessageType) (response))
                                                    .ResponseMessages.Items[0]))
                                                .Items.Items[0]).ItemId;

                                            if (newId != null)
                                            {
                                                MoveItemType t = new MoveItemType()
                                                {
                                                    ItemIds = new BaseItemIdType[]
                                                    {
                                                        newId
                                                    },

                                                };
                                                t.ToFolderId = new TargetFolderIdType();
                                                t.ToFolderId.Item = f;

                                                var moveItemResponse = Global.ExchangeServiceBinding.MoveItem(t);

                                                if (response.ResponseMessages.Items[0].ResponseClass ==
                                                    ResponseClassType.Error)
                                                {
                                                    throw new Exception("File Uploaded but it failed to move from Inbox");
                                                }

                                            }