Run two instances of the same application in Mac OS

Recently I came across a situation where I needed to run two instances of XCode application to compare two different versions of the project that I’m working.

Once a XCode application is opened and if you want to bring up another instance, you can’t do it by simply tapping on the XCode icon in the shortcut bar/via Applications folder.

You have to execute the following simple command using the Terminal.

open -n /Applications/Xcode.app

 

xCode 7.2 -> Interface Builder -> Problem resizing the view

I came across this situation, where it was bit hard to resize the view via the xCode 7.2 -> Interface Builder(Height x Width constraints are actually disabled). Web resources suggest different different options, but neither of them actually worked.

I was able to resolve it by removing the property called “useTraitCollections” in the relevant  XIB file.

Save image file content to Database with resizing (EF 4.1, SQLServer 2008 R2, MVC4)

File uploading is a very common task in nowadays specially with web applications. Normally what we do is we save the uploading files in the server-side. Recently, I have developed a software component which can be used to save images directly to a database table field(even with re-sizing if needed). For this module, I have used Entity Framework, Sql Server 2008 R2 and MVC4. How it has been achieved is described below.

Table – Content

table

Content table contains two fields FileName, FileContent and FIleType, which are nvarchar(64), varbinary(MAX) and nvarchar(64) respectively. The file contain was stored in FileContent field.

Entity Class – Content

public class Content : EntityBase
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Uid { get; set; }

    [StringLength(64)]
    [Display(Name = "File Name")]
    [Required]
    public string FileName { get; set; }

    [Required]
    public byte[] FileContent { get; set; }

    [StringLength(64)]
    [Display(Name = "File Type")]
    [Required]
    public string FileType { get; set; }

}

Entity Map – ContentMap

public class ContentMap : EntityTypeConfiguration<Entity.FileContent.Content>
{
    public ContentMap()
    {
        ToTable("Content");
        HasKey(t => t.Uid);
    }
}

Helper Class – ImageHelper 

I have implemented ToByteArray method as an extension method for HttpPostedFileBase. As this described if the image dimension is not meet your desired height or width it will be re-sized and stored.
public static class ImageHelper
{
    /// <summary>
    /// Checking whether the image needs to be resized
    /// </summary>
    /// <param name="uploadImage"></param>
    /// <param name="height"></param>
    /// <param name="width"></param>
    /// <returns>true or false depending on the size</returns>
    private static bool IsResizeNeeded(Image uploadImage, int height, int width)
    {
        var originalWidth = uploadImage.Width;
        var originalHeight = uploadImage.Height;
        return (originalHeight != height) || (originalWidth != width);
    }

    /// <summary>
    /// Resize the image depending on the size given
    /// </summary>
    /// <param name="uploadImage"></param>
    /// <param name="height"></param>
    /// <param name="width"></param>
    /// <returns></returns>
    private static Image ResizeBySize(Image uploadImage, int height, int width)
    {
        var originalWidth = uploadImage.Width;
        var originalHeight = uploadImage.Height;

        var modifiedHeight = height;
        var modifiedWidth = width;

        var bitmap = new Bitmap(modifiedWidth, modifiedHeight,
                                 PixelFormat.Format32bppPArgb);
        bitmap.SetResolution(uploadImage.HorizontalResolution, uploadImage.VerticalResolution);

        var graphics = Graphics.FromImage(bitmap);
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

        graphics.DrawImage(uploadImage,
                          new Rectangle(0, 0, modifiedWidth, modifiedHeight),
                          new Rectangle(0, 0, originalWidth, originalHeight),
                          GraphicsUnit.Pixel);

        graphics.Dispose();

        return bitmap;
    }

    /// <summary>
    /// Since we need the ImageFormat inorder to convert Image -> MemoryStream
    /// </summary>
    /// <param name="imageType"></param>
    /// <returns>ImageFormat according to the image type(Ex: jpg, jpeg etc.)</returns>
    private static ImageFormat GetImageFormat(string imageType)
    {
        ImageFormat imageFormat;
        switch (imageType)
        {
            case "image/jpg":
                imageFormat = ImageFormat.Jpeg;
                break;
            case "image/jpeg":
                imageFormat = ImageFormat.Jpeg;
                break;
            case "image/pjpeg":
                imageFormat = ImageFormat.Jpeg;
                break;
            case "image/gif":
                imageFormat = ImageFormat.Gif;
                break;
            case "image/png":
                imageFormat = ImageFormat.Png;
                break;
            case "image/x-png":
                imageFormat = ImageFormat.Png;
                break;
            default:
                throw new Exception("Unsupported image type !");
        }

        return imageFormat;
    }

    /// <summary>
    /// Convert files to byte array(Special function added for images which needs to be resized)
    /// </summary>
    /// <param name="fileUpLoad"></param>
    /// <returns>byte array of the image file</returns>
    public static byte[] ToByteArray(this HttpPostedFileBase fileUpLoad)
    {
        byte[] byteArray;

        if (IsImage(fileUpLoad))
        {
            //getting the height and width of the image to be uploaded
            var theHeight = Int32.Parse(WebConfigurationManager.AppSettings["UploadImageHeight"]);
            var theWidth = Int32.Parse(WebConfigurationManager.AppSettings["UploadImageWidth"]);

            //converting to a bitmap
            var uploadImage = new Bitmap(fileUpLoad.InputStream);

            //checking whether resize is needed
            if (IsResizeNeeded(uploadImage, theHeight, theWidth))
            {
                //resizing the image
                var resizedImage = ResizeBySize(uploadImage, theHeight, theWidth);
                //getting the image format(not the type)
                var resizedImageFormat = GetImageFormat(fileUpLoad.ContentType);

                using (resizedImage)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        //loading it to the memory stream
                        if (resizedImageFormat != null)
                        {
                            resizedImage.Save(memoryStream, resizedImageFormat);
                        }
                        memoryStream.Position = 0;
                        byteArray = memoryStream.ToArray();
                    }
                }
            }
            else
            {
                byteArray = ByteArrayConvertion(fileUpLoad);
            }
        }
        // for non-image files
        else
        {
            byteArray = ByteArrayConvertion(fileUpLoad);
        }

        return byteArray;
    }

    /// <summary>
    /// Default byte array creation
    /// </summary>
    /// <param name="fileUpload"></param>
    /// <returns>byte array</returns>
    private static byte[] ByteArrayConvertion(HttpPostedFileBase fileUpload)
    {
        byte[] byteArray;

        using (fileUpload.InputStream)
        {
            using (var memoryStream = new MemoryStream())
            {
                fileUpload.InputStream.CopyTo(memoryStream);
                byteArray = memoryStream.ToArray();
            }
        }
        return byteArray;
    }

    /// <summary>
    /// Checking the file is an image....
    /// </summary>
    /// <param name="fileUpload"></param>
    /// <returns>True if the file is an image</returns>
    /// http://yassershaikh.com/how-to-check-if-an-uploaded-file-is-an-image-or-not-in-asp-net-mvc-3/
    private static bool IsImage(HttpPostedFileBase fileUpload)
    {
        if (fileUpload.ContentType.Contains("image"))
        {
            return true;
        }

        var formats = new string[] { ".jpg", ".png", ".gif", ".jpeg" }; // add more if u like...

        // linq from Henrik Stenbæk
        return formats.Any(item => fileUpload.FileName.EndsWith(item, StringComparison.OrdinalIgnoreCase));
    }
}
Note: If you are hoping to store non-image files in DB, still it can be accomplished using ToByteArray extension method.
View
@using (Html.BeginForm("Upload", "ContentFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="FileUpload" />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
}
Controller – ContentFileController
I have used the extension method ToByteArray with the width and height parameters which obtained by web.config.
[HttpPost]
public ActionResult Upload(FileUploadModel fileUploadModel)
{
    HttpPostedFileBase file = Request.Files[0];

    if (file != null && file.ContentLength > 0)
    {
        //creating the content entity using repository
        Content fileUpload = _fileContentRepository.Create();
        fileUpload.FileName = Path.GetFileName(file.FileName);

        var extension = Path.GetExtension(file.FileName);
        if (extension != null)
            fileUpload.FileType = extension.TrimStart('.');

        //getting the height and width of the image to be uploaded
        var theHeight = Int32.Parse(WebConfigurationManager.AppSettings["UploadImageHeight"]);
        var theWidth = Int32.Parse(WebConfigurationManager.AppSettings["UploadImageWidth"]);

        fileUpload.FileContent = file.ToByteArray(theHeight, theWidth);

        _fileContentRepository.SaveOrUpdate(fileUpload);
        _unitOfWork.Commit();

    }

    var uploadedFiles = _fileContentRepository.GetAll();
    ViewData["UploadedFiles"] = uploadedFiles;

    return View(fileUploadModel);
}
View – Uploaded Files
@using DinotaMSM.Entity.FileContent
@using MvcContrib.UI.Grid
@using TekMVC.Models
@model FileUploadModel
@{
    ViewBag.Title = "Upload";
}

<div>
    @if (Model != null)
    {
        Html.Grid((IEnumerable<Content>) ViewData["UploadedFiles"])
            .Columns(column =>
                         {
                             column.For(c => @Html.ActionLink(c.Uid.ToString(), "GetFile", new {uid = c.Uid})).Named("ID");
                             column.For(c => c.FileName);
                             column.For(c => "<img src=" + string.Format("data:image/{0};base64,{1}", c.FileType, Convert.ToBase64String(c.FileContent)) + ">").Encode(false);
                         }).Render();
    }
</div>
Output
output

Binding WebGrid to Dynamic Collection (XML, SQL Server 2008 R2, dynamic, ExpandoObject, MVC 3, WebGrid)

Recently I have experienced with some of the new features (I guess these components are rarely used) of C# 4.0 such the dynamic type, ExpandoObject. My initial requirement was to build a dynamically created object collection out of XML formatted SQL result. Then it has to be used as a data-source for my grid.

Note: The select statement was dynamically generated and the result were vary from one query to another. My intent was to generate the data-source (list of objects) without using a well-structured mapping-class. With the use of ExpandoObject I was able to generate an object in run-time with dynamic properties.

SQL Query which return a XML formatted result

sql-query

XML Formatted result

query-result

For ease of explanation purpose I have copied the XML result to a XML file called “SQLResult1.xml”.

Helper Class – DynamicXmlConverter

public class XmlDynamicParser
{
    /// <summary>
    /// returns a List<dynamic> generated by xml datasource
    /// </summary>
    /// <param name="descendantName"></param>
    /// <param name="filePath"></param>
    /// <returns>List<dynamic></returns>
    public static List<dynamic> GenerateGridDataSource(string descendantName, string filePath)
    {
        //initialize list of dynamic objects
        var dataList = new List<dynamic>();

        //xml-string
        var doc = XDocument.Load(filePath);

        //selecting all the Descendats of Ex: "Result"
        var descendants = doc.Descendants(descendantName);

        //loop through each Descendats
        foreach (var descendant in descendants)
        {
            //creatingthe ExpandoObject
            dynamic expandoObject = new ExpandoObject();

            //casting it to a dictionary object
            var dictionaryExpandoObject = (IDictionary<string, object>)expandoObject;

            //loop through each elements of descendant
            foreach (var element in descendant.Elements())
            {
                //assiging of element name as propertyName
                string propertyName = element.Name.LocalName;

                //adding the property name and value to the dictionary
                dictionaryExpandoObject.Add(propertyName, element.Value);
            }

            //finally add each ExpandoObject to list
            dataList.Add(dictionaryExpandoObject);

        }

        return dataList;
    }
}

Controller – HomeController

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult LoadGrid()
    {
        var dataList = XmlDynamicParser.GenerateGridDataSource("Result", Server.MapPath("SQLResult1.xml"));
        return View(dataList);
    }
}

View – Load Grid

@{
    ViewBag.Title = "Load Grid";
}
@using System.Collections
@model IEnumerable
@{
    var grid = new WebGrid((IEnumerable<dynamic>)Model, canPage: true, rowsPerPage: 5);
}
@grid.GetHtml()

Output

grid

Accessing WCF Service via Android (WCF, EF 4.1, SQLServer 2008 R2, Android, Gson)

Recent past as an R&D Project I was working on a prototype basis Shopping cart application (assuming that the end-users are always in a connected environment-WiFi/3G) which has no local database so that it had to interact with WCF Service for data-manipulation.

WCF Service, data handling section was developed using Entity Framework(Code First approach). There were several modules like Item, Category, Order etc. Among those I picked Item module for further explanation.

Entity Class – Item

public class Item
{
	public string Id { get; set; }

	public string Name { get; set; }

	public string Url { get; set; }

	public int InStock { get; set; }

	public decimal Price { get; set; }
}

Entity Map – ItemMap

public class ItemMap : EntityTypeConfiguration<Item>
{
	public ItemMap()
	{
		ToTable("tbl_Item");
		HasKey(item => item.Id);
	}
}

Repository – ItemRepo

public class ItemRepo
{
    protected IDbSet<Item> ItemSet;
    protected DataContext Context;

    public ItemRepo(DataContext dataContext)
    {
        Context = dataContext;
        ItemSet = dataContext.Set<Item>();
    }

    public List<Item> GetItems(string from, string to)
    {
        IEnumerable<Item> items = (from a in ItemSet
                                   select a).OrderBy(a => a.Id).Skip(Convert.ToInt32(from)).Take(Convert.ToInt32(to));

        return items.ToList();
    }
}

WCF Service Method

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Html5Service
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public List<Item> GetItems(string From, string To)
    {
        var itemRepo = new ItemRepo(new DataContext());
        return itemRepo.GetItems(Convert.ToInt32(From), Convert.ToInt32(To));
    }
}

Client(Android) side implementation was as follows.

You have to access the WCF Service with a similar function like below. I have used a third party library called gson-1.7.1(not the latest one), which can be downloaded from the below link.
download google-gson

Item-Mapping [since my mapping properties had the same name with compared to the json result item list, i have not used the SerializedName annotation]

Class – Item

public class Item{

	private String Id;
	private String Name;
	private String Url;
	private int InStock;
	private Double Price;

	public String getId() {
		return Id;
	}
	public void setId(String id) {
		Id = url;
	}

	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}

	public String getUrl() {
		return Url;
	}
	public void setUrl(String url) {
		Url = url;
	}

	public int getInStock() {
		return InStock;
	}
	public void setInStock(int inStock) {
		InStock = inStock;
	}

	public Double getPrice() {
		return Price;
	}
	public void setPrice(Double price) {
		Price = price;
	}
}

WCF Service call

public List<Item> getItems(String from, String to) {

	List<Item> items = null;
	Gson gson = new Gson();

	try {

		String urlWithParam = String.format("http://app.dinotait.com/Items/HTML5Service.svc/GetItems?From=%s&To=%s",from, to);

		HttpGet request = new HttpGet(urlWithParam);

		request.setHeader("Accept", "application/json");
		request.setHeader("Content-type", "application/json");

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(request);

		HttpEntity responseEntity = response.getEntity();

		// Read response data into buffer
		char[] buffer = new char[(int) responseEntity.getContentLength()];
		InputStream stream = responseEntity.getContent();
		InputStreamReader reader = new InputStreamReader(stream);
		reader.read(buffer);
		stream.close();

		Type type = new TypeToken<List<Item>>(){}.getType();
		items = gson.fromJson(new String(buffer), type);

	} catch (Exception e) {
		e.printStackTrace();
	}

	return items;
}

Remember that you have to execute this function within an AsyncTask or similar approach since this is a network operation.

Multiple images uploading (with file size reduce uploading) MVC4, JQuery mobile, XMLHttpRequest, HTML5 File Api

I had to work with a project that had the functionality of multiple image files uploading. The specialty of the functionality was it had the ability of uploading larger images with reduced file sizes apart from uploading the original files. I thought of sharing the file uploading module of the project.

Here are some of the screenshots of the application.

F1F2F3

Here goes the implementation.

View – FileUpload

@{
    ViewBag.Title = "File Upload";
}

<div>
    <div>
        <p id="perror" style="color: white; background-color: red;"></p>
    </div>
    <div>
        <input type="file" accept="image/*" name="fileToUpload[]" id="fileToUpload" style='visibility: hidden;' name="img" onchange="fileSelected();"/>
        <input type = "button" value = "Choose image" onclick ="javascript:document.getElementById('fileToUpload').click();">
        <ul data-role="listview" id="uploadfilelist" data-inset="true" data-split-theme="d" data-split-icon="delete">
        </ul>
    </div>
    <div>
        <ul data-role="listview" data-inset="true">
            <li data-role="fieldcontain">
                <label id = "sizereducechkboxlbl" style="display: none">
                    <input type="checkbox" name="checkbox-0" id="sizereducechkbox" style="display: none"/> Reduce size and upload </label>
                <input type="button" onclick="uploadFiles();" value="Upload [max. 5 files]" />
            </li>
        </ul>
    </div>
</div>

There were several javascript functions I have written to fulfill the requirement.

  • fileSelected – this function is used to show preview of the selected file. Also I have written some validations such as only image types are allowed, maximum file size is 10MB, no.of files that can be uploaded at once cannot be higher than 5. Remember that your browser should be supported HTML5 File Api.
  • uploadFiles – loop through filequeue and popping up the file and the list-element.
  • resizeAndUpload – this function does the size reducing before uploading. At the moment I have used the MAX Height as 600 and MAX Width as 800. I have use the canvas element and redraw the original image with the max height, width dimensions.  XMLHttpRequest object is used to send the data(canvas element can be converted to base64string with the use of toDataURL(“image/jpeg”)) to server.

<script type="text/javascript">

    var count = 0;
    var progresscount = 0;
    var start;
    var chromeCount = 0;
    var i = 0;

    var filequeue = new Array();
    var jobimageuploadid = -1;

	//displaying selected file details
    function fileSelected() {

        try {

            count = 0;
            progresscount = 0;
            var selectedfile;
            var processingfile;
            var processingfileuniquekey;

            $("#perror").text('').fadeIn(1);
            $("#uploadfilelist").listview("refresh");

            var files = document.getElementById('fileToUpload').files;

            if (filequeue.length > 4) {
                errorDisplay('Maximum number of allowable file uploads has been exceeded!!');
            } else {

                selectedfile = files[0];

                if (!selectedfile.type.match('image.*')) {
                    errorDisplay('Only image files are allowed');
                } else if (selectedfile.size > 10485760) {
                    errorDisplay('Maximum file size exceeds');
                }

                if (selectedfile.type.match('image.*') && selectedfile.size < 10485760) {

                    $("#sizereducechkbox").show("slow");
                    $("#sizereducechkboxlbl").show("slow");

                    processingfileuniquekey = "PC:00" + chromeCount + "-";
                    var map = new Array(selectedfile, processingfileuniquekey);

                    if (window.File && window.FileReader && window.FileList && window.Blob) {

                        var reader = new FileReader();

                        reader.onload = (function(theFile) {
                            return function(e) {

                                var li = document.createElement("li");
                                li.setAttribute("data-icon", "delete");

                                var newlink = document.createElement('a');
                                newlink.setAttribute("href", "javascript:void(0);");
                                newlink.setAttribute("onclick", "removeImage('" + processingfileuniquekey + "');");

                                var img = document.createElement("img");
                                img.setAttribute("src", e.target.result);
                                img.setAttribute("height", "80");
                                img.setAttribute("width", "80");
                                newlink.appendChild(img);

                                var h3 = document.createElement("h3");
                                var h3Text = document.createTextNode(processingfileuniquekey + theFile.name);
                                h3.appendChild(h3Text);
                                newlink.appendChild(h3);

                                var p = document.createElement("p");
                                newlink.appendChild(p);

                                li.appendChild(newlink);

                                document.getElementById("uploadfilelist").appendChild(li);

                                $("#uploadfilelist").listview("refresh");

                                filequeue.push({ file: map, li: li });

                                chromeCount = chromeCount + 1;

                            };
                        })(selectedfile);

                        // Read in the image file as a data URL.
                        reader.readAsDataURL(selectedfile);

                    } else {

                        $("#uploadfilelist").append('<li data-icon="delete" id=' + i + '><a href="javascript:void(0);" onclick="remove(' + i + ');">' + processingfile.name + '<p style="padding: 2px 0px 0px 0px"></p></a></li>');
                        $("#uploadfilelist").listview("refresh");

                        i = i + 1;
                    }

                }
            }

            $("#fileToUpload").val("");

        } catch(err) {
            alert("Exception " + err);
        }
    }

	//removing selected file if needed, before uploading
    function removeImage(processingfileuniquekey) {

        try {

            $("#uploadfilelist li").each(function() {

                if ($(this).find("h3").text().indexOf(processingfileuniquekey) != -1) {

                    var containtext = $(this).find("h3").text();

                    $(this).remove();

                    for (var b = 0; b < filequeue.length; b++) {

                        var processarray = filequeue[b];
                        var processmap = processarray.file;

                        if (containtext.indexOf(processmap[1]) != -1) {

                            filequeue.splice(b, 1);

                            break;
                        }
                    }

                    $("#uploadfilelist").listview("refresh");

                }

            });

            if (filequeue.length == 0) {
                $('#sizereducechkbox').attr('checked', false);
                $("#sizereducechkbox").checkboxradio("refresh");
                $("#sizereducechkbox").fadeOut(100);
                $("#sizereducechkboxlbl").fadeOut(100);
            }

            $("#uploadfilelist").listview("refresh");

        } catch(err) {
            alert("Exception " + err);
        }
    }

	//uploading files
    function uploadFiles() {

        try {

            while (filequeue.length > 0) {

                var item = filequeue.pop();
                var processarray = item.file;
                var file = processarray[0];
                var key = processarray[1];

                if ($('#sizereducechkbox').is(':checked')) {
                    resizeAndUpload(file, key);
                }
                else {
                    upload(file, key);
                }
            }

        } catch(err) {
            alert("Exception " + err);
        }

    }

	//used to prevent caching of the ajax request(specially with Mobile Safari)
    function GUID() {
        var S4 = function () {
            return Math.floor(
                Math.random() * 0x10000 /* 65536 */
            ).toString(16);
        };

        return (
            S4() + S4() + "-" +
                S4() + "-" +
                    S4() + "-" +
                        S4() + "-" +
                            S4() + S4() + S4()
        );
    }

	//default upload file function
    function upload(file, key, item) {

        try {

            var uploadurl = '@Url.Action("UploadFiles", "FileUpload")';
            uploadurl += "?bustCache=" + GUID();

            var li = item.li;

            var xhr = new XMLHttpRequest(), upload = xhr.upload;

            upload.addEventListener("loadstart", function (ev) {

                var containtext = $(li).find("h3").text();
                var index = containtext.indexOf(" upload error");

                if (index != -1) {

                    var refreshtext = containtext.substring(0, index);

                    $(li).find('h3').text(refreshtext);
                    $("#uploadfilelist").listview("refresh");

                }
                else {

                    $("#uploadfilelist").listview("refresh");

                }

            }, false);

            upload.addEventListener("progress", function (ev) {

                if (ev.lengthComputable) {
                    var percentComplete = Math.round(ev.loaded * 100 / ev.total);
                    $(li).find("p").text("Uploading " + percentComplete + "%");
                    $(li).find("p").css("color", "#3DD13F");
                }

            }, false);
            upload.addEventListener("load", function (evt) {

                $(li).find("h3").css("color", "#3DD13F");

            }, false);
            upload.addEventListener("error", function (ev) {

                if (xhr.status != 500) {

                    filequeue.push(item);

                    var containtext = $(li).find("h3").text();
                    $(li).find("h3").text(containtext + " upload error");
                    $(li).find("h3").css("color", "#FF0000");
                    $(li).find("p").text("Uploading 0%");
                    $(li).find("p").css("color", "#FF0000");

                }

            }, false);

            xhr.open("POST", uploadurl);

            xhr.setRequestHeader("Content-type", "multipart/form-data");

            xhr.setRequestHeader("X-File-Name", (key + file.name));

            xhr.setRequestHeader("X-File-Size", file.size);
            xhr.setRequestHeader("X-File-Type", file.type);

            xhr.send(file);

            xhr.onreadystatechange = function () {

                var containtext;

                if (xhr.readyState != 4) {
                    return;
                }

                else if (xhr.readyState == 4) {

                    if (xhr.status == 500) {

                        filequeue.push(item);

                        containtext = $(li).find("h3").text();
                        $(li).find("h3").text(containtext + " upload error");
                        $(li).find("h3").css("color", "#FF0000");
                        $(li).find("p").text("Uploading 0%");
                        $(li).find("p").css("color", "#FF0000");

                    }
                    else if (xhr.status == 200) {

                        containtext = $(li).find("h3").text();
                        $(li).find("h3").text(containtext + " upload complete");
                        $(li).fadeOut(5000);
                    }

                }

            };

            if (filequeue.length == 0) {

                $('#sizereducechkbox').attr('checked', false);
                $("#sizereducechkbox").checkboxradio("refresh");
                $("#sizereducechkbox").fadeOut(100);
                $("#sizereducechkboxlbl").fadeOut(100);

                chromeCount = 0;

            }

        }

        catch (err) {
            alert("Exception " + err);
        }
    }

	//size reduced file upload
    function resizeAndUpload(file, key, item) {

        try {

            var uploadurl = '@Url.Action("UploadSizeReducedFiles", "FileUpload")';
            uploadurl += "?bustCache=" + GUID();

			//due to problem occurs while resizing of the image with ios-devices/safari browser
            var mpImg = new MegaPixImage(file);

            var li = item.li;

            var reader = new FileReader();
            reader.onloadend = function (evt) {

                if (evt.target.readyState == FileReader.DONE) {

                    var tempImg = new Image();
                    tempImg.src = reader.result;
                    tempImg.onload = function () {

                        var MAX_WIDTH = 800;
                        var MAX_HEIGHT = 600;

                        var tempW = tempImg.width;
                        var tempH = tempImg.height;

                        if (tempW > MAX_WIDTH) {
                            tempW = MAX_WIDTH;
                        }

                        if (tempH > MAX_HEIGHT) {
                            tempH = MAX_HEIGHT;
                        }

                        var canvas = document.createElement('canvas');
						//render canvas with the use of MegaPixImage library
                        mpImg.render(canvas, { maxWidth: tempW, maxHeight: tempH });

                        var xhr = new XMLHttpRequest(), upload = xhr.upload;

                        upload.addEventListener("loadstart", function (ev) {

                            var containtext = $(li).find("h3").text();
                            var index = containtext.indexOf(" upload error");

                            if (index != -1) {

                                var refreshtext = containtext.substring(0, index);

                                $(li).find('h3').text(refreshtext);
                                $("#uploadfilelist").listview("refresh");

                            }
                            else {

                                $("#uploadfilelist").listview("refresh");

                            }

                        }, false);

                        upload.addEventListener("progress", function (ev) {

                            if (ev.lengthComputable) {
                                var percentComplete = Math.round(ev.loaded * 100 / ev.total);
                                $(li).find("p").text("Uploading " + percentComplete + "%");
                                $(li).find("p").css("color", "#3DD13F");
                            }

                        }, false);
                        upload.addEventListener("load", function (ev) {

                            $(li).find("h3").css("color", "#3DD13F");

                        }, false);
                        upload.addEventListener("error", function (ev) {

                            if (xhr.status != 500) {

                                filequeue.push(item);

                                var containtext = $(li).find("h3").text();
                                $(li).find("h3").text(containtext + " upload error");
                                $(li).find("h3").css("color", "#FF0000");
                                $(li).find("p").text("Uploading 0%");
                                $(li).find("p").css("color", "#FF0000");

                            }

                        }, false);

                        xhr.open("POST", uploadurl);
                        xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
                        xhr.setRequestHeader("X-File-Name", (key + file.name));

                        xhr.setRequestHeader("X-File-Size", file.size);
                        xhr.setRequestHeader("X-File-Type", file.type);

                        var data = 'image=' + canvas.toDataURL("image/jpeg");
                        xhr.send(data);

                        xhr.onreadystatechange = function () {

                            var containtext;

                            if (xhr.readyState != 4) {
                                return;
                            }

                            else if (xhr.readyState == 4) {

                                if (xhr.status == 500) {

                                    filequeue.push(item);

                                    containtext = $(li).find("h3").text();
                                    $(li).find("h3").text(containtext + " upload error");
                                    $(li).find("h3").css("color", "#FF0000");
                                    $(li).find("p").text("Uploading 0%");
                                    $(li).find("p").css("color", "#FF0000");

                                }
                                else if (xhr.status == 200) {

                                    containtext = $(li).find("h3").text();
                                    $(li).find("h3").text(containtext + " upload complete");
                                    $(li).fadeOut(5000);
                                }

                            }

                        };

                        if (filequeue.length == 0) {

                            $('#sizereducechkbox').attr('checked', false);
                            $("#sizereducechkbox").checkboxradio("refresh");
                            $("#sizereducechkbox").fadeOut(100);
                            $("#sizereducechkboxlbl").fadeOut(100);

                            chromeCount = 0;

                        }

                    };

                };

            };
            reader.readAsDataURL(file);
        }

        catch (err) {
            alert("Exception " + err);
        }
    }

	//display error information
    function errorDisplay(error) {
        $("#perror").text(error).fadeOut(4000);
    }

 </script>

This method handles the file saving to the server-side folder which is Uploads. The two methods for saving the original file/size reduced file.
Also the status of the uploaded file will be displayed in the file uploading list.
Controller Actions- FileUpload


[AcceptVerbs(HttpVerbs.Post)]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult UploadSizeReducedFiles()
{
    string fileName = null;
    string uploadedFilePath = null;

    try
    {
        fileName = Request.Headers["X-File-Name"];

        string directoryPath = Server.MapPath("~/Uploads/");

        if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
        }

        var stream = new StreamReader(Request.InputStream);
        string image = stream.ReadToEnd();

        image = image.Substring("image=data:image/jpeg;base64,".Length);
        byte[] buffer = Convert.FromBase64String(image);

        uploadedFilePath = string.Format("{0}{1}", directoryPath, editedFileName);

        System.IO.File.WriteAllBytes(uploadedFilePath, buffer);

        return Json(fileName + " completed", JsonRequestBehavior.AllowGet);
    }
    catch (Exception e)
    {
        Response.StatusCode = 500;
        return Json(fileName + " fail", JsonRequestBehavior.AllowGet);
    }
}

[AcceptVerbs(HttpVerbs.Post)]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult UploadFiles()
{
    string fileName = null;
    string uploadedFilePath = null;

    try
    {
        var len = Request.InputStream.Length;

        fileName = Request.Headers["X-File-Name"];

        string directoryPath = Server.MapPath("~/Uploads/");

        if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
        }

        uploadedFilePath = string.Format("{0}{1}", directoryPath, fileName);

        Request.SaveAs(uploadedFilePath, false);

        return Json(fileName + " completed", JsonRequestBehavior.AllowGet);
    }
    catch (Exception e)
    {
        Response.StatusCode = 500;
        return Json(fileName + " fail", JsonRequestBehavior.AllowGet);
    }
}

Replace partial text string in SQL Text field

Even though this is very simple, I thought of blogging this.

I had a table called tbl_Item which had a Field called URL(nvarchar(200)) having several records like
http://192.168.0.20:8080/Items/T-shirt.jpg,
http://192.168.0.20:8080/Items/Jean.jpg.

I wanted to replace the part of the string which contains 192.168.0.20:8080 to 10.20.10.71. Here it goes.

UPDATE tbl_Item
SET Url = replace(cast(Url as NVARCHAR(200)),'192.168.0.20:8080','10.20.10.71')