0

I'm currently working on a mobile application (mobile website really) that allows people to take photos from an inspection and then upload from their mobile phone storing the server path in a database field via LINQ and the photo to a directory on the server that is dictated by a querystring.

One of the requirements from the client is that they now wish to have the image resized on the client side and then saved to the server which makes alot of sense as the mobile coverage (3G/4G) mightn't be as good as the city.

Upload.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<script type="text/javascript">
    function AppendMacro() {
        var selMacro = document.getElementById('<%= selPhotoMacro.ClientID%>');
        var txtbox = document.getElementById('<%= txtDescription.ClientID%>')
        txtbox.value += selMacro.value + '\n\n';
    }
 </script>
<div align="center">
<asp:Repeater ID="rInspection" runat="server">
    <ItemTemplate><h1 style="margin: 0px;">Additional Photos</h1><strong><%# DataBinder.Eval(Container.DataItem, "InspectionTitle")%></strong><br /><a href="/inspection.aspx?id=<% Response.Write(Request.QueryString["id"]); %>"><%# DataBinder.Eval(Container.DataItem, "InspectionAddress")%></a><br /><br /><div style="font-size: 11px;">Additional Photos appear at the back of the Inspection Report.</div><br /></ItemTemplate>
</asp:Repeater>
</div>

<p><div class="photo"><asp:Image ID="imgPhotoUpload" runat="server" ImageUrl="Images/photo.gif" Width="63" Height="56" BorderStyle="Solid" BorderColor="Black" BorderWidth="1px" /></div><div style="float: left;"><p><strong>Additional Photo</strong><br /><asp:FileUpload ID="PhotoUpload" runat="server" /></div><br clear="left" />
    </p>

<asp:Panel ID="Panel1" runat="server" Visible="false" HorizontalAlign="Center">
    <asp:Image ID="Image1" runat="server" BorderStyle="Solid" BorderColor="Black" BorderWidth="1px" Width="300" Height="200" />
    <p>
    <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="SaveImage" Font-Size="Large"  />
    <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick = "Cancel" Font-Size="Large"  />
    </p>
</asp:Panel>

<asp:DropDownList ID="selPhotoMacro" runat="server" OnInit="BindMacros" onchange="AppendMacro()" Width="300px">
</asp:DropDownList>
<asp:TextBox ID="txtDescription" runat="server" TextMode="MultiLine" Columns="40" Rows="10"></asp:TextBox>



<div align="center">
    <asp:Button ID="btnUpload" runat="server" Text="Upload Photo" OnClick="Upload" Font-Size="Large" />
</div>

Upload.aspx.cs

using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppWalkthrough.Data;
using Xrm;

namespace WebAppWalkthrough
{
public partial class photos : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["Image"] = null;

            //var InspectionQuery = Request.QueryString["id"];
            var xrm = new XrmServiceContext("Xrm");
            var InspectionTitle = from i in xrm.new_inspectionsSet
                                  where i.Id == Guid.Parse(Request.QueryString["id"])
                                  select new { InspectionTitle = i.new_name, Id = i.new_inspectionsId.Value, InspectionAddress = i.new_HiddenAddress };

            rInspection.DataSource = InspectionTitle;
            rInspection.DataBind();
        }



    }

    protected void BindMacros(object sender, EventArgs e)
    {
        var xrm = new XrmServiceContext("Xrm");
        //ALL Macros (except the * Please Select)
        var Macros = from c in xrm.new_macroSet
                     where c.new_InspectionType.Equals(Request.QueryString["type"]) && !c.new_name.Contains("PLEASE SELECT")
                     orderby c.new_name ascending
                     select new
                     {
                         MacroTitle = c.new_name + "-" + c.new_Description,
                         MacroDescription = c.new_Description
                     };

        selPhotoMacro.DataSource = Macros;
        selPhotoMacro.DataTextField = "MacroTitle";
        selPhotoMacro.DataValueField = "MacroDescription";
        selPhotoMacro.DataBind();
    }

    protected void Upload(object sender, EventArgs e)
    {
        Session["Image"] = PhotoUpload.PostedFile;
        Stream fs = PhotoUpload.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        byte[] bytes = br.ReadBytes((Int32)fs.Length);
        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);

        Image1.ImageUrl = "data:image/png;base64," + base64String;
        Panel1.Visible = true;

        //hide upload
        btnUpload.Visible = false;
    }

    protected void Cancel(object sender, EventArgs e)
    {
        Response.Redirect(Request.Url.AbsoluteUri);
    }

    protected void SaveImage(object sender, EventArgs e)
    {
        var CRMService = CRMHelper.GetCRMService();

        //instantiate the object
        new_additionalphoto p = new new_additionalphoto();

        string path = Server.MapPath("~/Assets/") + Request.QueryString["id"];

        //CREATE FOLDER FOR PHOTOS
        try
        {
            if (Directory.Exists(path))
            {
                //Response.Write("Path exists!");

            }
            //create directory
            DirectoryInfo di = Directory.CreateDirectory(path);

        }
        catch (Exception DirError)
        {
            Response.Write(DirError.ToString());

        }

        string ImageURL = "http://website/" + Request.QueryString["id"] + "/";

        HttpPostedFile postedFile = (HttpPostedFile)Session["Image"];


        //if (PhotoUpload.HasFile && PhotoUpload.PostedFile != null)
        //{
            //string theImage = PhotoUpload.FileName;
            string theImage = postedFile.FileName;

            if (System.IO.Path.GetExtension(theImage) == ".gif" || (System.IO.Path.GetExtension(theImage) == ".jpg") || (System.IO.Path.GetExtension(theImage) == ".jpeg"))
            {
                PhotoUpload.SaveAs((path + "/") + theImage);
                p.new_name = ImageURL + theImage;
            }
            else
            {
                Response.Write(System.IO.Path.GetExtension(theImage));
            }
        //}

        p.new_Photo = new EntityReference("new_additionalphoto", new Guid(Request.QueryString["id"]));
        p.new_Description = txtDescription.Text;

        var Id = CRMService.Create(p);
        Response.Redirect(Request.Url.AbsoluteUri);

        //labMessage.Text = "Photo Attached";

    }
}

}

The code above is saving the record to the DB, and also saving to the server (however, I've noticed that on the server it's not quite right as it's showing as 0Kb).

I haven't added the code to resize the image from High Resolution to say 72dpi as I can't quite workout how to achieve this.

I'm slowly getting comfortable with C# and would greatly appreciate anyones assistance on how to re-size the image before saving to the server with the file name stored via the LINQ code.

Chris
  • 67
  • 1
  • 2
  • 10

0 Answers0