Problems in connecting to a WiFi network that has MAC Filtering enabled

Prerequisite: You should have given your device MAC address to the network admin.

You may have come across this issue while trying to connect your phone to a WiFi network that has MAC Filtering enabled.
Follow these steps to resolve it.

Tested on: Samsung Galaxy S10e

  1. Goto the troublesome network -> Manage network settings

2. Check what’s the value in MAC address type field. Most probably it should be set to Use randomized MAC(default). This could be a reason for not getting connected to the WiFi network.

3. Change it to Use device MAC

The problem should be resolved. 🙂

Custom Hyperlink Control for Windows(Windows 8.1, Windows Phone 8.1)

Ended up building a user control which behaves similarly in both Windows and Windows Phone environments. With this you’ll get the underline effect, stating of default color as well as the press color.
Designer code


<UserControl x:Class="MyApp.Architecture.Controls.CustomHyperlink" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:MyApp.Architecture.Controls" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Background="YellowGreen">
    <HyperlinkButton x:Name="innerHyperlinkCtrl" FontFamily="Segoe WP Light">
        <HyperlinkButton.Content>
            <TextBlock FontFamily="Segoe UI" x:Name="inlineText">
					<Underline>
						<Run x:Name="ulRHlink"/>
					</Underline>
            </TextBlock>
        </HyperlinkButton.Content>
    </HyperlinkButton>
</UserControl>

C# code


public sealed partial class CustomHyperlink : UserControl
{
	private HyperlinkButton innerCtrl;
	private TextWrapping textWrapping = TextWrapping.WrapWholeWords;

	#region Constructors

	public CustomHyperlink()
	{
		this.InitializeComponent();
		this.Loaded += CustomHyperlink_Loaded;
		this.InnerCtrl = innerHyperlinkCtrl;

		this.DefaultColor = "#000000";
		this.PressedColor = "#40ff00";
	}

	#endregion

	#region Getters, Setters

	public HyperlinkButton InnerCtrl
	{
		get { return this.innerCtrl; }
		private set { this.innerCtrl = value; }
	}

	#endregion

	#region Events

	void CustomHyperlink_Loaded(object sender, RoutedEventArgs e)
	{
		this.InnerCtrl.Style = (this.Style == null) ? GetDefaultStyle() : this.Style;
		this.inlineText.TextWrapping = this.textWrapping;

		this.InnerCtrl.VerticalAlignment = this.VerticalAlignment;
		this.InnerCtrl.HorizontalAlignment = this.HorizontalAlignment;
		this.InnerCtrl.FontSize = this.FontSize;
		this.InnerCtrl.FontWeight = this.FontWeight;
		this.InnerCtrl.Margin = this.Margin;
	}

	#endregion

	#region Dependency Properties

	public static readonly DependencyProperty LinkTextProperty = DependencyProperty.Register("LinkText", typeof(string), typeof(CustomHyperlink), new PropertyMetadata(null, new PropertyChangedCallback(OnContentChanged)));
	public string LinkText
	{
		get { return (string)GetValue(LinkTextProperty); }
		set { SetValue(LinkTextProperty, value); }
	}

	private static void OnContentChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
	{
		CustomHyperlink mhl = sender as CustomHyperlink;
		mhl.ulRHlink.Text = (e.NewValue != null) ? e.NewValue.ToString() : string.Empty;
	}

	public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register("TextWrapping", typeof(TextWrapping), typeof(CustomHyperlink), null);
	public TextWrapping TextWrapping
	{
		get { return (TextWrapping)GetValue(TextWrappingProperty); }
		set 
		{ 
			SetValue(TextWrappingProperty, value);
			this.inlineText.TextWrapping = value;
		}
	}

	public static readonly DependencyProperty DefaultColorProperty = DependencyProperty.Register("DefaultColor", typeof(string), typeof(CustomHyperlink), null);
	public string DefaultColor
	{
		get { return (string)GetValue(DefaultColorProperty); }
		set { SetValue(DefaultColorProperty, value); }
	}

	public static readonly DependencyProperty PressedColorColorProperty = DependencyProperty.Register("PressedColor", typeof(string), typeof(CustomHyperlink), null);
	public string PressedColor
	{
		get { return (string)GetValue(PressedColorColorProperty); }
		set { SetValue(PressedColorColorProperty, value); }
	}

	public static readonly DependencyProperty NavigateUriProperty = DependencyProperty.Register("NavigateUri", typeof(Uri), typeof(CustomHyperlink), null);
	public Uri NavigateUri
	{
		get { return (Uri)GetValue(NavigateUriProperty); }
		set 
		{ 
			SetValue(NavigateUriProperty, value); 
			this.InnerCtrl.NavigateUri = value; 
		}
	}

	#endregion

	#region Default Style

	private Style GetDefaultStyle()
	{
		StringBuilder styleBuilder = new StringBuilder();
		styleBuilder.Append("<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" 
                      xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" x:Key=\"CustomHyperlinkButtonStyle\" TargetType=\"HyperlinkButton\">");           
			styleBuilder.Append("<Setter Property=\"Template\">");
				styleBuilder.Append("<Setter.Value>");
					styleBuilder.Append("<ControlTemplate TargetType=\"HyperlinkButton\">");
						styleBuilder.Append("<Grid>");
						styleBuilder.Append("<VisualStateManager.VisualStateGroups>");
							styleBuilder.Append("<VisualStateGroup x:Name=\"CommonStates\">");
								styleBuilder.Append("<VisualState x:Name=\"Normal\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBNormal\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"" + DefaultColor + "\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
								styleBuilder.Append("<VisualState x:Name=\"Pressed\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBPressed\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"" + PressedColor + "\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
								styleBuilder.Append("<VisualState x:Name=\"Disabled\">");
									styleBuilder.Append("<Storyboard x:Name=\"HyperLinkSBDisabled\">");
										styleBuilder.Append("<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=\"Foreground\" Storyboard.TargetName=\"ContentPresenter\">");
											styleBuilder.Append("<DiscreteObjectKeyFrame KeyTime=\"0\" Value=\"{ThemeResource HyperlinkDisabledThemeBrush}\"/>");
										styleBuilder.Append("</ObjectAnimationUsingKeyFrames>");
									styleBuilder.Append("</Storyboard>");
								styleBuilder.Append("</VisualState>");
							styleBuilder.Append("</VisualStateGroup>");
						styleBuilder.Append("</VisualStateManager.VisualStateGroups>");
						styleBuilder.Append("<ContentPresenter x:Name=\"ContentPresenter\" AutomationProperties.AccessibilityView=\"Raw\" ContentTemplate=\"{TemplateBinding ContentTemplate}\" ContentTransitions=\"{TemplateBinding ContentTransitions}\" Content=\"{TemplateBinding Content}\" HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\">");
						styleBuilder.Append("</ContentPresenter>");
						styleBuilder.Append("</Grid>");
					styleBuilder.Append("</ControlTemplate>");
				styleBuilder.Append("</Setter.Value>");
			styleBuilder.Append("</Setter>");
		styleBuilder.Append("</Style>");

		return (Style)XamlReader.Load(styleBuilder.ToString());
	}

	#endregion
}

Typical Usage (XAML)


<custctrl:CustomHyperlink x:Name="GoogleLink" HorizontalAlignment="Stretch" VerticalAlignment="Center" FontSize="14" Margin="0,20,0,0" NavigateUri="www.google.com" LinkText="Link to Google"/>

Typical Usage(C# class)


CustomHyperlink customHyperlink = new CustomHyperlink();
customHyperlink.Name = standardControlName;
customHyperlink.DefaultColor = "#000000";
customHyperlink.PressedColor = "#40ff00";
customHyperlink.HorizontalAlignment = HorizontalAlignment.Left;
customHyperlink.VerticalAlignment = VerticalAlignment.Center;
customHyperlink.LinkText = "Hello There";

Happy coding…. 🙂

Forcing newly entered characters to be in UPPERCASE in a TextBox

For Windows Store Apps(Windows 8.1 & Windows Phone 8.1)


///
<summary>
/// Identify whether the pressed key is a Letter(Ex: a, B..)
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
	int keyValue = (int)e.Key;
	if (keyValue >= 0x41 && keyValue <= 0x5A)
		isLetter = true;
}

///
<summary>
/// Identify whether a text PASTE is happened.
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_Paste(object sender, TextControlPasteEventArgs e)
{
	var textBox = sender as TextBox;
	startingLocation = textBox.SelectionStart;
	pasteOccurred = true;
}

///
<summary>
/// Change the newly entered character's case to upper case / a set of characters (Ex: text Paste)
/// </summary>

/// <param name="sender"></param>
/// <param name="e"></param>
static void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
	var textBox = sender as TextBox;
	var newText = textBox.Text;
	int currentPosition = textBox.SelectionStart;

	#region text paste

	if (pasteOccurred)
	{
		string newCharacters = newText.Substring(startingLocation, (currentPosition-startingLocation));
		newText = newText.Remove(startingLocation, newCharacters.Length).Insert(startingLocation, newCharacters.ToUpper());
		textBox.Text = newText;
		textBox.SelectionStart = currentPosition;

		pasteOccurred = false;
		startingLocation = -1;

		return;
	}

	#endregion

	if (!isLetter) return;

	currentPosition = textBox.SelectionStart - 1;
	if (currentPosition < 0) return; 	if (Char.IsLower(newText, currentPosition)) 	{ 		string newCharacter = newText.Substring(currentPosition, 1); 		newText = newText.Remove(currentPosition, 1).Insert(currentPosition, newCharacter.ToUpper()); 		textBox.Text = newText; 		textBox.SelectionStart = currentPosition + 1; 	} 	isLetter = false; } 

For Android(TextWatcher implementation)

 final EditText editText = (EditText) view; //new region force -> uppercase implementation
final TextWatcher textWatcher = new TextWatcher() {
	boolean shouldContinue = true;

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		//To avoid executing of text change listener -> onTextChanged when the time of data binding..
		shouldContinue = editText.hasFocus() ? true : false;
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if(!shouldContinue)return;

		int curCursorLoc = editText.getSelectionEnd();
		if(curCursorLoc < 1) return;

		CharSequence charSet = s.subSequence(start, (start + count));
		if(charSet != null) {
			String upperStr = charSet.toString().toUpperCase();
			StringBuilder stringBuilder = new StringBuilder(s);
			stringBuilder.replace(start, (start + count), upperStr);
			editText.setText(stringBuilder.toString());
			editText.setSelection(curCursorLoc);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
	}
};

editText.addTextChangedListener(textWatcher);
//endregion

For iOS (iPhone or iPad)


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    BOOL shouldChange;
    NSRange lowercaseCharRange;
	lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];

	if (lowercaseCharRange.location != NSNotFound) {
		textField.text = [textField.text stringByReplacingCharactersInRange:range
																 withString:[string uppercaseString]];
		UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument inDirection:UITextLayoutDirectionRight offset:(range.location + 1)];
		UITextRange *newCursorRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
		[textField setSelectedTextRange:newCursorRange];
		shouldChange = NO;
	}
	else
		shouldChange = YES;

    return shouldChange;
}

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);
    }
}

Microsoft JScript runtime error: ‘$’ is undefined in MVC4 Mobile Web Application

I came across this problem while I was developing a mobile web application in MVC4. I think most of you all have faced this issue and found a solution as well. But I thought it was worth to share this, becuase this did the trick for me.
In my MVC4 web application , I had my _Layout.cshtml page like this.


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <meta name="viewport" content="width=device-width" />
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        @Styles.Render("~/Content/mobileCss", "~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div data-role="page" data-theme="b">
            <div data-role="header">
                @if (IsSectionDefined("Header")) {
                    @RenderSection("Header")
                } else {
                    <h1>@ViewBag.Title</h1>
                    @Html.Partial("_LoginPartial")
                }
            </div>
            <div data-role="content">
                @RenderBody()
            </div>
        </div>

        @Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")
        @RenderSection("scripts", required: false)
    </body>
</html>

But in-order to resolve the error, I had to modify the page like below.


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title</title>
        <meta name="viewport" content="width=device-width" />
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        @Styles.Render("~/Content/mobileCss", "~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        <strong>@Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")</strong>

    </head>
    <body>
        <div data-role="page" data-theme="b">
            <div data-role="header">
                @if (IsSectionDefined("Header")) {
                    @RenderSection("Header")
                } else {
                    <h1>@ViewBag.Title</h1>
                    @Html.Partial("_LoginPartial")
                }
            </div>
            <div data-role="content">
                @RenderBody()
            </div>
        </div>

        @RenderSection("scripts", required: false)
    </body>
</html>

Note that I changed the place of JQuery script line from body -> head section.
source : http://forums.asp.net/t/1835597.aspx/1

Windows Phone 7 Photo Upload

Recently I have developed a native Windows Phone 7 program to upload images to remote server.

Here are the Screen shots.

010203

Implementation details.

MainPage.xaml


<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

 <ListBox Height="517" Margin="0,6,0,0" Name="listimge" VerticalAlignment="Top" Width="450">
 <ListBox.ItemTemplate>
 <DataTemplate>
 <StackPanel Orientation="Horizontal">
 <CheckBox Name="chk" /><Image Source="{Binding ImageFile}" Width="100" Height="100"/>

 </StackPanel>
 </DataTemplate>
 </ListBox.ItemTemplate>
 </ListBox>
 <Button Content="Upload" Height="72" HorizontalAlignment="Left" Margin="150,529,0,0" Name="uploadButton"
 VerticalAlignment="Top" Width="160" Click="UploadClick" />

</Grid>

MainPage.xaml.cs

The below method is used to load image files from the Picture Gallery to the ListBox.


private MediaLibrary MyMediaLibrary { get; set; }

private void LoadImageGallery()
{
            MyMediaLibrary = new MediaLibrary();
            PictureCollection pictures = MyMediaLibrary.Pictures;
            foreach (Picture picture in pictures)
            {
                var image = new BitmapImage();
                image.SetSource(picture.GetImage());
                var mediaImage = new MediaImage {ImageFile = image};
                listimge.Items.Add(mediaImage);
            }
}

This method is used to upload the selected images(iterating through the ListBox to find the selected index) to the remote server.

private void UploadClick(object sender, RoutedEventArgs e)
{
            for (int i = 0; i < listimge.Items.Count; i++)
            {
                if (listimge.ItemContainerGenerator != null)
                {
                    var item = listimge.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                    var tagregCheckBox = FindCheckBox<CheckBox>(item);
                    if (tagregCheckBox.IsChecked == true)
                    {
                        UploadImage(i);
                        tagregCheckBox.IsChecked = false;
                    }
                }
            }
}

Helper function which is used to identify the checked Checkboxses in the ListBox.

private T FindCheckBox<T>(DependencyObject parentElement) where T : DependencyObject
{
            int count = VisualTreeHelper.GetChildrenCount(parentElement);
            if (count == 0)
                return null;

            for (int i = 0; i < count; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parentElement, i);

                if (child != null && child is T)
                {
                    return (T) child;
                }
                var result = FindCheckBox<T>(child);
                if (result != null)
                    return result;
            }
            return null;
}

This method is used to find the image from image gallery, get the stream of the identified image and send it to the remote server.

private void UploadImage(int selectedIndex)
{
            const int BLOCK_SIZE = 4096;

            var uri = new Uri("http://10.20.10.71/MVCFile/File", UriKind.Absolute);

            var webClient = new WebClient();
            webClient.AllowReadStreamBuffering = true;
            webClient.AllowWriteStreamBuffering = true;

            Stream selectedImageStream = MyMediaLibrary.Pictures[selectedIndex].GetImage();

            webClient.OpenWriteCompleted += (s, args) =>
                                                {
                                                    using (var binaryReader = new BinaryReader(selectedImageStream ))
                                                    {
                                                        using (var binaryWriter = new BinaryWriter(args.Result))
                                                        {
                                                            long count = 0;
                                                            long fileSize = selectedImageStream .Length;
                                                            var bytes = new byte[BLOCK_SIZE];
                                                            do
                                                            {
                                                                bytes = binaryReader.ReadBytes(BLOCK_SIZE);
                                                                count += bytes.Length;
                                                                binaryWriter.Write(bytes);
                                                            } while (count < fileSize);
                                                        }
                                                    }
                                                };

            webClient.WriteStreamClosed += (s, args) => { MessageBox.Show("Send Complete"); };

            webClient.OpenWriteAsync(uri, "POST");
}

Finally add the ‘LoadImageGallery’ method to the constructor of MainPage.

// Constructor
public MainPage()
{
            InitializeComponent();
            LoadImageGallery();
}

Controller – File Upload

public class FileController : Controller
{
       public ActionResult Index()
      {
            string filename = Server.MapPath(String.Format("{0}.jpg", "YourFileName"));

            try
            {
                using (var fs = new FileStream(filename, FileMode.Create))
                {
                    using (var bw = new BinaryWriter(fs))
                    {
                        using (var br = new BinaryReader(Request.InputStream))
                        {
                            long bCount = 0;
                            long fileSize = br.BaseStream.Length;
                            const int BLOCK_SIZE = 4096;
                            byte[] bytes = new byte[BLOCK_SIZE];
                            do
                            {
                                bytes = br.ReadBytes(BLOCK_SIZE);
                                bCount += bytes.Length;
                                bw.Write(bytes);
                            } while (bCount < fileSize);
                        }
                    }
                }

                return Json(new { Result = "Upload Complete" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "Upload Error", Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
      }
}