Thursday, 13 July 2017

Photo Upload In Blog

----Design-----------------------

<%@ Page Title="" Language="C#" MasterPageFile="~/Admin/Adminmasterpage.master" AutoEventWireup="true" CodeFile="GalleryEntry.aspx.cs" Inherits="Admin_GalleryEntry" %>

<asp:Content ID="Content1" ContentPlaceHolderID="CPHead" runat="Server">
    <script>
        function OnClientFileUploaded(sender, eventArgs) {
            uploadedFilesCount++;
        }
    </script>
    <telerik:RadScriptBlock runat="server" ID="radscriptblok1">
        <script type="text/javascript">
            function OnClientImageloaded(sender, args) {
                $find("<%= RadAjaxPanel2.ClientID %>").ajaxRequest();
                document.getElementById("<%=BtnSave.ClientID %>").disabled = true;
            }
        </script>
        <style>
            #ctl00_CPMain_RadWindowGallary_C {
                height: 340px !important;
            }
        </style>
    </telerik:RadScriptBlock>

    <style type="text/css">
        body {
            font-size: 13px !important;
        }

        .layoutTable {
            clear: both;
            width: 100%;
            border-spacing: 0px;
        }

            .layoutTable td {
                padding: 0;
            }

        .demo-container {
            max-width: 970px;
            margin-left: -10px;
        }

        .itemWrapper {
            float: left;
            margin-left: 62px;
            margin-bottom: 10px;
        }

        .itemTable {
            width: 200px;
            height: 160px;
            border-spacing: 0;
        }

            .itemTable td {
                padding: 0;
            }

        td.cellInfo {
            /*width: 66%;*/
        }

        table {
            border-collapse: separate !important;
        }

        .RadInput_Bootstrap, .RadInputMgr_Bootstrap {
            font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
            padding-left: 0px !important;
        }

        .t-col {
            padding-left: 0px !important;
        }

        .proceedtopay {
            border: 1px solid;
            /* border-radius: 5px; */
            color: white;
            /* font-size: 13px; */
            padding: 12px 8px 12px 8px;
            background: rgb(66, 130, 196);
        }

        .btn, .btn-default, .btn-default.focus, .btn-default:focus, .btn.focus, .btn:focus {
            background-color: #2ea444 !important;
            border-color: rgba(171, 186, 195, 0) !important;
        }

        .RadUpload .ruBrowse {
            height: 1.9em !important;
        }

        .RadUpload .ruUploadSuccess {
            display: none !important;
        }
        .RadWindow .rwIcon {
            width: 3em !important;
            height: 2em !important;
            top: 42% !important;
        }
        .RadWindow .rwTitleWrapper .rwTitle {
    padding: .5em 0 .5em 3em !important;
}
    </style>
    <script type="text/javascript">
        function CheckFirstChar(key, txt) {
            if (key == 32 && txt.value.length <= 0) {
                return false;
            }
            else if (txt.value.length > 0) {
                if (txt.value.charCodeAt(0) == 32) {
                    txt.value = txt.value.substring(1, txt.value.length);
                    return true;
                }
            }
            return true;
        }
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="CPMain" runat="Server">
    <telerik:RadNotification RenderMode="Lightweight" ID="ApplicantSummary" runat="server" Position="TopCenter" TitleIcon="~/img/logo-footer.png"
        AutoCloseDelay="9000" Width="380" Height="92" Title="Applicant Summary" LoadContentOn="EveryShow">
    </telerik:RadNotification>
    <telerik:RadWindowManager RenderMode="Lightweight" ID="radManger" runat="server"></telerik:RadWindowManager>
    <div class="row" style="margin-bottom: 40px; margin-top: 10px;">
        <div class="col-sm-12 no-padding contact-us-custom-padding" style="margin-left:20px">
            <button type="button" class="btn btn-dm " runat="server" id="btnAddGalary" value="Add New Galary" onserverclick="btnAddGalary_ServerClick">
                + Add New Gallery
            </button>
            <asp:Label ID="lblImageId" runat="server" Visible="false"></asp:Label>
            <div class="clearfix" style="margin-bottom: 2%"></div>
            <div style="overflow-y: auto; height: 500px">
                <asp:Panel ID="ListViewPanel1" runat="server">
                    <telerik:RadListView Skin="Vista" ID="ListViewImage" RenderMode="Lightweight"
                        runat="server" ItemPlaceholderID="MainContent" OnItemCommand="ListViewImage_ItemCommand" OnPageIndexChanged="ListViewImage_PageIndexChanged" OnPageSizeChanged="ListViewImage_PageSizeChanged" DataKeyNames="GallaryImages_ID" PageSize="4">

                        <LayoutTemplate>
                            <fieldset id="FieldSet1" class="productsFieldset" style="border: 1px #5f5f5f">

                                <table class="layoutTable">
                                    <tr>
                                        <td>
                                            <asp:Panel ID="MainContent" runat="server">
                                            </asp:Panel>
                                        </td>
                                    </tr>
                                    <%-- <tr>
                                    <td>
                                        <telerik:RadDataPager RenderMode="Lightweight" ID="RadDataPager1" runat="server" PagedControlID="kk"
                                            PageSize="2" Style="margin-top: 10px; width: 100%">
                                            <Fields>
                                                <telerik:RadDataPagerButtonField FieldType="FirstPrev"></telerik:RadDataPagerButtonField>
                                                <telerik:RadDataPagerButtonField FieldType="Numeric"></telerik:RadDataPagerButtonField>
                                                <telerik:RadDataPagerButtonField FieldType="NextLast"></telerik:RadDataPagerButtonField>

                                            </Fields>
                                        </telerik:RadDataPager>
                                    </td>
                                </tr>--%>
                                </table>
                            </fieldset>
                        </LayoutTemplate>

                        <ItemTemplate>
                            <div class="itemWrapper">
                                <table class="itemTable" style="border: 1px solid #ddd; padding-left: 20px; padding-top: 6px; padding-bottom: 15px">
                                    <tr style="float: right">
                                        <td class="cellInfo">
                                            <asp:ImageButton ID="Button1" runat="server" CommandName="btnEdit" ImageUrl="~/assets/edit.png" ToolTip="Edit"></asp:ImageButton>&nbsp;
                                            <asp:ImageButton ID="Button2" runat="server" CommandName="btnDelete" ImageUrl="~/assets/delete.png" ToolTip="Delete" OnClientClick="return confirm('Are you sure to delete this record?');"></asp:ImageButton>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="cellInfo">
                                            <telerik:RadBinaryImage ID="RadBinaryImage3" Height="120px" Width="90%" runat="server" AlternateText="No Image" CssClass="binaryImage" ToolTip='<%#Eval("GallaryImages_Name", "Photo of {0}") %>'
                                                ResizeMode="Fit" ImageUrl='<%#Eval("GallaryImages_URL")%>'></telerik:RadBinaryImage>
                                        </td>
                                    </tr>
                                    <tr style="height: 10px"></tr>
                                    <tr>
                                        <td class="cellInfo">
                                            <asp:Label ID="lblImageName" runat="server" ForeColor="#3F51B5" Font-Bold="true" Font-Size="12px" Text='<%# Eval("GallaryImages_Name") %>'></asp:Label>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </ItemTemplate>
                    </telerik:RadListView>
                </asp:Panel>
            </div>
        </div>
    </div>
    <telerik:RadWindow runat="server" ID="RadWindowGallary" Modal="true" Width="650px" Height="380px" CssClass="borderLessDialog" Title="Gallery Information" Animation="None" AutoSize="false" Behaviors="Close,Move" DestroyOnClose="true" Skin="WebBlue" VisibleStatusbar="false" IconUrl="~/images/slider3_ly2_BJD.png">
        <ContentTemplate>
            <div class="clearfix" style="margin-bottom: 2%"></div>
            <div class="col-md-12">
                <div class="form-group">
                    <div class="col-md-3">
                        <telerik:RadLabel ID="lblName" runat="server">Name </telerik:RadLabel>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator21" ForeColor="red" SetFocusOnError="true" ControlToValidate="txtImgname" ErrorMessage="*" Display="Dynamic" runat="server" ValidationGroup="ValidGallary">  </asp:RequiredFieldValidator>
                    </div>
                    <div class="col-md-8">
                        <telerik:RadTextBox ID="txtImgname" runat="server" class="form-control" MaxLength="30" placeholder="Name of Image " Width="100%" onkeyup="CheckFirstChar(event.keyCode, this);" onkeydown="return CheckFirstChar(event.keyCode, this);"></telerik:RadTextBox>
                    </div>
                </div>
            </div>
            <div class="clearfix" style="margin-bottom: 1%"></div>
            <div class="col-md-12">
                <div class="form-group">
                    <div class="col-md-3">
                        <telerik:RadLabel ID="RadTitle" runat="server">Description </telerik:RadLabel>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ForeColor="red" SetFocusOnError="true" ControlToValidate="txtImgDesc" ErrorMessage="*" Display="Dynamic" runat="server" ValidationGroup="ValidGallary">  </asp:RequiredFieldValidator>
                    </div>
                    <div class="col-md-8">
                        <telerik:RadTextBox ID="txtImgDesc" runat="server" class="form-control" MaxLength="2000" placeholder="Description of Image" Width="100%" TextMode="MultiLine" Height="60px" onkeyup="CheckFirstChar(event.keyCode, this);" onkeydown="return CheckFirstChar(event.keyCode, this);"></telerik:RadTextBox>
                    </div>
                </div>
            </div>
            <div class="clearfix" style="margin-bottom: 1%"></div>

            <div class="col-md-12">
                <div class="form-group">
                    <div class="col-md-3"></div>
                    <div class="col-md-8">

                        <telerik:RadAjaxPanel ID="RadAjaxPanel2" runat="server">
                            <telerik:RadBinaryImage ID="RadBinaryImage1" runat="server" Height="116px" Width="120px" AlternateText="Upload Image" Style="text-align: center; color: darkgrey; line-height: 8;" />
                        </telerik:RadAjaxPanel>
                    </div>
                </div>
            </div>

            <div class="clearfix" style="margin-bottom: 1%"></div>

            <div class="col-md-12">
                <div class="form-group">
                    <div class="col-md-3">
                        <telerik:RadLabel ID="Radupload" runat="server">Upload Image </telerik:RadLabel>
                    </div>
                    <div class="col-md-8">
                        <telerik:RadAsyncUpload RenderMode="Lightweight" runat="server" MaxFileInputsCount="1" ID="RadAsyncUpload2"
                            HideFileInput="true" OnFileUploaded="RadAsyncUpload2_FileUploaded" OnClientFileUploaded="OnClientImageloaded"
                            AllowedFileExtensions=".jpeg,.jpg,.png" MultipleFileSelection="Disabled" />
                    </div>
                </div>
                <div class="clearfix" style="margin-bottom: 1%"></div>
                <div class="form-group">
                    <%--<div class="col-md-12" align="center" style="margin-left:-22px">--%>
                    <div class="col-md-3"></div>
                    <div class="col-md-8">
                        <telerik:RadLabel ID="lblErrorMessage" runat="server" Visible="false"></telerik:RadLabel>
                    </div>
                </div>
            </div>
            <div class="clearfix" style="margin-bottom: 3%"></div>
            <telerik:LayoutRow>
                <Columns>
                    <telerik:LayoutColumn Span="12" SpanMd="12" SpanSm="12" SpanXs="12">
                        <div class="col-md-9" align="center">
                            <telerik:RadButton ID="BtnSave" runat="server" ValidationGroup="ValidGallary" Text="Save" OnClick="BtnSave_Click"></telerik:RadButton>
                            <telerik:RadButton ID="BtnCancel" runat="server" Text="Cancel" OnClick="BtnCancel_Click"></telerik:RadButton>
                        </div>
                    </telerik:LayoutColumn>
                </Columns>
            </telerik:LayoutRow>
        </ContentTemplate>
    </telerik:RadWindow>
</asp:Content>



===========================================================

---Coding--------------------------

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_GalleryEntry : System.Web.UI.Page
{
    BlobService bs = new BlobService();
    HttpClient client = new HttpClient();
    public List<ImageGallaryClass> LstImageGallaryClass = new List<ImageGallaryClass>();

    protected void Page_Load(object sender, EventArgs e)
    {
        #region .......API Base address.......
        var appsurl = ConfigurationManager.AppSettings["APIPath"].ToString();
        client.BaseAddress = new Uri(appsurl);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        #endregion
        if (!Page.IsPostBack)
        {
            LoadImageView();
        }
    }

    #region GetImageList
    private List<ImageGallaryClass> GetImageList()
    {
        HttpResponseMessage hrm = client.GetAsync("Gallery").Result;
        if (hrm.IsSuccessStatusCode)
        {
            LstImageGallaryClass = hrm.Content.ReadAsAsync<List<ImageGallaryClass>>().Result;
            return LstImageGallaryClass.Where(a => a.IsActive == true).ToList();
        }
        else
        {
            return null;
        }
    }
    #endregion

    private void LoadImageView()
    {
        try
        {
            HttpResponseMessage GalleryInformation = client.GetAsync("Gallery").Result;
            if (GalleryInformation.IsSuccessStatusCode)
            {
                LstImageGallaryClass = GalleryInformation.Content.ReadAsAsync<List<ImageGallaryClass>>().Result;
                var Imageload = (from a in LstImageGallaryClass
                                 where a.IsActive == true && a.IsDelete == false
                                 select new
                                 {
                                     a.GallaryImages_ID,
                                     a.GallaryImages_Name,
                                     a.GallaryImages_URL
                                 }).ToList();
                if (Imageload.ToList().Count > 0)
                {
                    ListViewImage.DataSource = null;
                    ListViewImage.DataSource = Imageload.ToList();
                    ListViewImage.DataBind();
                }
                else
                {
                    ListViewImage.DataSource = String.Empty;
                    ListViewImage.DataBind();
                }
            }
        }
        catch (Exception ex)
        {

        }
    }
    public async Task<string> SaveCompanyPhoto(UploadedFile LeadImage)
    {
        BlobService bs = new BlobService();
        string fg = "";
        if (Session["LdImage"] != null)
        {
            fg = Session["LdImage"].ToString();
        }
        if (LeadImage != null)
        {
            var imageUrl = await bs.UploadImageAsync(LeadImage);
            Session["LdImage"] = imageUrl;
            fg = imageUrl;
        }
        return fg;
    }
    public void OpenGallarypopup()
    {
        #region--Contact Popup--
        string script = "function f(){$find(\"" + RadWindowGallary.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "key", script, true);
        lblErrorMessage.Visible = false;
        txtImgname.Focus();
        #endregion
    }
    public void CloseGallarypopup()
    {
        #region--Contact Popup--
        string script = "function f(){Close('" + RadWindowGallary.ClientID + "'); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
        lblErrorMessage.Visible = false;
        #endregion
    }
    protected void btnAddGalary_ServerClick(object sender, EventArgs e)
    {
        BtnSave.Text = "Save";
        txtImgname.Text = string.Empty;
        txtImgDesc.Text = string.Empty;
        RadBinaryImage1.DataValue = null;
        RadBinaryImage1.ImageUrl = "";
        OpenGallarypopup();
    }
    public async Task<string> SaveCompanythumbPhoto(UploadedFile LeadImage)
    {
        BlobService bs = new BlobService();
        string fg = "";
        if (Session["tempimage"] != null)
        {
            fg = Session["tempimage"].ToString();

        }
        if (LeadImage != null)
        {
            string target = Server.MapPath("~/UploadedImages");
            if (!Directory.Exists(target))
            {
                Directory.CreateDirectory(target);
            }
            using (Bitmap originalImage = new Bitmap(LeadImage.InputStream))
            {
                int width = 265;
                int height = 265;
                Bitmap thumbnail = new Bitmap(width, height);
                using (Graphics g = Graphics.FromImage((System.Drawing.Image)thumbnail))
                    g.DrawImage(originalImage, 0, 0, width, height);
                string thumbnailFileName = Path.Combine(target,
                    string.Format("{0}_bthumb{1}", LeadImage.GetNameWithoutExtension(), LeadImage.GetExtension()));
                thumbnail.Save(thumbnailFileName);

                var IMAGEURL = await bs.UploadImageAsync1(thumbnailFileName, LeadImage.GetExtension(), LeadImage.ContentType);
                fg = IMAGEURL;
                if ((System.IO.File.Exists(thumbnailFileName)))
                {
                    System.IO.File.Delete(thumbnailFileName);
                }
                Session["tempimage"] = fg;
            }
        }
        return fg;

    }
    protected void RadAsyncUpload2_FileUploaded(object sender, Telerik.Web.UI.FileUploadedEventArgs e)
    {
        BtnSave.Enabled = true;
        if (IsFileValid())
        {
            ViewState["APIimage"] = SaveCompanyPhoto(RadAsyncUpload2.UploadedFiles[0]).Result;
            string path = SaveCompanythumbPhoto(RadAsyncUpload2.UploadedFiles[0]).Result;
            RadBinaryImage1.ImageUrl = path;
            OpenGallarypopup();
        }
    }

    public bool IsFileValid()
    {
        Bitmap bitmp = new Bitmap(RadAsyncUpload2.UploadedFiles[0].InputStream);
        if (bitmp.Width == 900 && bitmp.Height == 845)
        {
            OpenGallarypopup();
            return true;
        }
        else
        {
            OpenGallarypopup();
            lblErrorMessage.Visible = true;
            lblErrorMessage.Text = "Image is not in proper dimension(900 X 845)";
            lblErrorMessage.ForeColor = System.Drawing.Color.Red;
            return false;
        }
    }

    protected void BtnSave_Click(object sender, EventArgs e)
    {
        if (BtnSave.Text == "Save")
        {
            if (RadBinaryImage1.ImageUrl != "")
            {
                ImageGallaryClass postImgInfo = new ImageGallaryClass();
                postImgInfo.GallaryImages_Name = txtImgname.Text;
                postImgInfo.GallaryImages_Description = txtImgDesc.Text;
                postImgInfo.GallaryImages_URL = ViewState["APIimage"] == null ? string.Empty : ViewState["APIimage"].ToString();
                postImgInfo.InsertedOn = DateTime.Now;
                postImgInfo.IsActive = true;
                postImgInfo.IsDelete = false;
                HttpResponseMessage Imgcontent = client.PostAsJsonAsync("Gallery", postImgInfo).Result;
                if (Imgcontent.IsSuccessStatusCode)
                {
                    txtImgname.Text = string.Empty;
                    txtImgDesc.Text = string.Empty;
                    RadBinaryImage1.DataValue = null;
                    RadBinaryImage1.ImageUrl = "";
                    ApplicantSummary.Text = "Data Save successfully!";
                    ApplicantSummary.Show();
                    LoadImageView();
                    //CloseGallarypopup();
                    //Response.Redirect(Request.RawUrl);
                }
            }
            else
            {
                OpenGallarypopup();
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "Please Upload Image !";
                lblErrorMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
        else
        {
            ImageGallaryClass postImgInfo = GetImageList().Where(a => a.GallaryImages_ID == Convert.ToInt32(lblImageId.Text)).FirstOrDefault();
            postImgInfo.GallaryImages_Name = txtImgname.Text;
            postImgInfo.GallaryImages_Description = txtImgDesc.Text;
            postImgInfo.GallaryImages_URL = RadBinaryImage1.ImageUrl;// ViewState["APIimage"] == null ? string.Empty : ViewState["APIimage"].ToString();
            //postImg.InsertedBy = loginId;
            postImgInfo.InsertedOn = DateTime.Now;
            postImgInfo.IsActive = true;
            postImgInfo.IsDelete = false;
            HttpResponseMessage Imgcontent = client.PutAsJsonAsync("Gallery/" + lblImageId.Text, postImgInfo).Result;
            if (Imgcontent.IsSuccessStatusCode)
            {
                txtImgname.Text = string.Empty;
                txtImgDesc.Text = string.Empty;
                RadBinaryImage1.DataValue = null;
                RadBinaryImage1.ImageUrl = "";
                BtnSave.Text = "Save";
                ApplicantSummary.Text = "Data Update successfully!";
                ApplicantSummary.Show();
                LoadImageView();
                //CloseGallarypopup();
                // Response.Redirect(Request.RawUrl);
            }
        }

    }

    protected void BtnCancel_Click(object sender, EventArgs e)
    {
        CloseGallarypopup();
        Response.Redirect(Request.RawUrl);
    }

    protected void FetchData()
    {
        try
        {
            var image = GetImageList().Where(a => a.GallaryImages_ID == Convert.ToInt32(lblImageId.Text)).FirstOrDefault();

            txtImgname.Text = image.GallaryImages_Name;
            txtImgDesc.Text = image.GallaryImages_Description;
            RadBinaryImage1.ImageUrl = image.GallaryImages_URL;
        }
        catch (Exception)
        {

        }
    }

    protected void ListViewImage_ItemCommand(object sender, RadListViewCommandEventArgs e)
    {
        RadListViewDataItem item = e.ListViewItem as RadListViewDataItem;
        lblImageId.Text = item.GetDataKeyValue("GallaryImages_ID").ToString();
        ImageButton btn = (ImageButton)item.FindControl("Button2");

        if (e.CommandName == "btnEdit")
        {
            OpenGallarypopup();
            //BtnSave.Enabled = true;
            FetchData();
            BtnSave.Text = "Update";
        }
        else if (e.CommandName == "btnDelete")
        {
            if (btn.CausesValidation == true)    //ok was pressed.
            {
                var address = GetImageList().Where(a => a.GallaryImages_ID == Convert.ToInt32(lblImageId.Text)).FirstOrDefault();

                HttpResponseMessage content = client.DeleteAsync("Gallery/" + lblImageId.Text).Result;
                if (content.IsSuccessStatusCode)
                {
                    txtImgname.Text = string.Empty;
                    txtImgDesc.Text = string.Empty;
                    RadBinaryImage1.DataValue = null;
                    RadBinaryImage1.ImageUrl = "";
                    LoadImageView();
                    ApplicantSummary.Text = "Data Deleted successfully!";
                    ApplicantSummary.Show();
                }
            }
        }
    }
    protected void ListViewImage_PageIndexChanged(object sender, RadListViewPageChangedEventArgs e)
    {
        ListViewImage.CurrentPageIndex = e.NewPageIndex;
        LoadImageView();
    }
    protected void ListViewImage_PageSizeChanged(object sender, RadListViewPageSizeChangedEventArgs e)
    {
        LoadImageView();
    }
}

No comments:

Post a Comment