Thursday, 5 January 2017

How to post image in blob using Windows Azure.

First Set Connection String in Web Config File
============================
 <!--Blob Connnection-->
    <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=satyastorageaccount;AccountKey=SrVl+wKtyrty64564564646464545vPeFthtrhrt7vQXdxjr1Fp6e67tutut==" />
    <!--End BlobConnection-->
=================================

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Telerik.Web.UI.ImageEditor;


namespace testassss.Admin
{
    public partial class CompanyBranding : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public static Bitmap ResizeImage(Stream stream, int hght, int wdth)
        {
            int height = hght;//150;
            int width = wdth; //150;
            Bitmap scaledImage = new Bitmap(width, height);
            try
            {
                System.Drawing.Image originalImage = Bitmap.FromStream(stream);
                using (Graphics g = Graphics.FromImage(scaledImage))
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(originalImage, 0, 0, width, height);
                    return scaledImage;
                }
            }
            catch (Exception Exc)
            {
                Exc.ToString();
                return scaledImage;
            }
        }
        public static Bitmap ResizeImage1(Stream stream, int hghtw, int wdthw)
        {
            int height = hghtw;//150;
            int width = wdthw; //150;
            Bitmap scaledImage1 = new Bitmap(width, height);
            try
            {
                System.Drawing.Image originalImage = Bitmap.FromStream(stream);
                using (Graphics h = Graphics.FromImage(scaledImage1))
                {
                    h.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    h.DrawImage(originalImage, 0, 0, width, height);
                    return scaledImage1;
                }
            }
            catch (Exception Exc)
            {
                Exc.ToString();
                return scaledImage1;
            }
        }
        protected void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
        {
            try
            {
                Bitmap bitmapImage = ResizeImage(RadAsyncUpload1.UploadedFiles[0].InputStream, 120, 130);
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                bitmapImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                RadBinaryImage1.DataValue = stream.ToArray();
                ViewState["Signbin"] = stream.ToArray();
                Session["FileSize"] = e.File.ContentLength;
                Session["FileType"] = e.File.ContentType;
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('Error Message:')</script>" + ex.Message);
            }
        }
        protected void RadAsyncUpload2_FileUploaded(object sender, FileUploadedEventArgs e)
        {
            try
            {
             
                Bitmap bitmapImage = ResizeImage1(RadAsyncUpload2.UploadedFiles[0].InputStream, 120, 130);
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                bitmapImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);          
                RadBinaryImage2.DataValue = stream.ToArray();
                //RadBinaryImage3.DataValue = stream.ToArray();
                //RadBinaryImage4.DataValue = stream.ToArray();
                //RadBinaryImage5.DataValue = stream.ToArray();          
                //RadBinaryImage2.DataValue = stream.ToArray();
                ViewState["Signbin"] = stream.ToArray();
                Session["FileSize"] = e.File.ContentLength;
                Session["FileType"] = e.File.ContentType;
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('Error Message:')</script>" + ex.Message);
            }
        }
        public static CloudStorageAccount GetConnectionString()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
            return storageAccount;
        }
        public async Task<string> UploadImageAsync(UploadedFile imageToUpload)
        {
            string floder = RadTextBox2.Text;
            string imageFullPath = null;
            if (imageToUpload == null || imageToUpload.ContentLength == 0)
            {
                return null;
            }
            try
            {
                CloudStorageAccount cloudStorageAccount = GetConnectionString();
                CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
                CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(floder);
                CloudBlobDirectory folder = cloudBlobContainer.GetDirectoryReference(floder + "image");
                cloudBlobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(imageToUpload.FileName);
                CloudBlockBlob cloudBlockBlob = folder.GetBlockBlobReference(imageName);
                cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;
                CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
                cloudBlockBlob.UploadFromStream(imageToUpload.InputStream);
                imageFullPath = cloudBlockBlob.Uri.ToString();
                ViewState["Image"] = imageFullPath;
            }
            catch (Exception ex)
            {

            }
            return imageFullPath;
        }
        public async Task<string> UploadImageAsync1(UploadedFile imageToUpload)
        {
            string floder = RadTextBox2.Text;
            string imageFullPath = null;
            if (imageToUpload == null || imageToUpload.ContentLength == 0)
            {
                return null;
            }
            try
            {
                CloudStorageAccount cloudStorageAccount = GetConnectionString();
                CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
                CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(floder);
                CloudBlobDirectory folder = cloudBlobContainer.GetDirectoryReference(floder +"image");
                cloudBlobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(imageToUpload.FileName);
                CloudBlockBlob cloudBlockBlob = folder.GetBlockBlobReference(imageName);
                cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;
                CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
                cloudBlockBlob.UploadFromStream(imageToUpload.InputStream);
                imageFullPath = cloudBlockBlob.Uri.ToString();
               ViewState["Image1"] = imageFullPath;
            }
            catch (Exception ex)
            {

            }
            return imageFullPath;
        }
        protected void RadButton1_Click(object sender, EventArgs e)
        {
             try
             {
                 string floder = RadTextBox2.Text;          
             
                // Retrieve storage account from connection string.
                CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("swasherpstorageaccount", "ffwfweFQ2BviaUvQXdxjryrty4546rgrtzvw=="), true);
                // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                // Retrieve a reference to a container.
                CloudBlobContainer container = blobClient.GetContainerReference(floder);
                // Retrieve reference to a blob named "myblob".
                //CloudBlockBlob blockBlob = container.GetBlockBlobReference("swash");
                // Create the container if it doesn't already exist.
                container.CreateIfNotExists();
                var img = UploadImageAsync(RadAsyncUpload1.UploadedFiles[0]);
                var img1 = UploadImageAsync1(RadAsyncUpload2.UploadedFiles[0]);
                ErpDataAccess.GetInstance.InsertData(ViewState["Image"].ToString());
                // myph.InsertData(ViewState["Image"].ToString());
                ViewState["Image"] = null;              
            }
            catch (Exception Exc)
            {
            }          
        }
    }
}

When User has Registered at that time create a container and blob and 4 Subcontainer using Windows Azure.

First Set the Connection String in Web Config File.

the Process Is
===============
<!--Azure Storage Account and BlobContainer Connection String (Satya)-->
    <add key="StorageAccountName" value="satyastorageaccount" />
    <add key="StorageAccountKey" value="fffq7R20Q0Pjomd73xSVt44re44dGXTANbM+Mx3iRFfegxjr1Fp6eqhzX2Uzvw==" />
    <add key="blobcontainer" value="linkueblobcontainer" />
    <!--End Azure ConnectionString-->
===============================================

Next In C# ASP .NET CODE
===============================
 protected void Button1_Click(object sender, EventArgs e)

        {
 // this is Dynamically Sub Container name from frontend
 string floder = txtcreatecontanier.Text;
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("satyastorageaccount", "SrVl+wK6AxvPeFtT0JDxfs3xSVt44Q2BviaUvQfsdfs54434Fp6eqhzX2Uzvw=="), true);
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference(floder);
            //// set the container to be public
            //container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
            // Create the container if it doesn't already exist.
            container.CreateIfNotExists();
            // Retrieve reference to a blob named "myblob".
            int count = 3;
            for (int i = 0; i <= count; i++)
            {
               CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
              CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(floder);



              string obj = Server.MapPath("~/Images/accent.png");
                var filename = Path.GetFileName(obj);
                if (i == 0)
                {
                    CloudBlobDirectory Img = container.GetDirectoryReference(floder + "image");
                    string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(filename);
                    CloudBlockBlob cloudBlockBlob = Img.GetBlockBlobReference(imageName);
                    CloudBlobClient blobClient1 = storageAccount.CreateCloudBlobClient();
                    ErpDataAccess.GetInstance.InsertData(Img.ToString());
                    using (var fs = File.OpenRead(obj))
                    {
                        cloudBlockBlob.UploadFromStream(fs);
                    }
                }
                if (i == 1)
                {
                    CloudBlobDirectory Img = container.GetDirectoryReference(floder + "video");
                    string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(filename);
                    CloudBlockBlob cloudBlockBlob = Img.GetBlockBlobReference(imageName);
                    CloudBlobClient blobClient1 = storageAccount.CreateCloudBlobClient();
                    ErpDataAccess.GetInstance.InsertData(Img.ToString());
                    using (var fs = File.OpenRead(obj))
                    {
                        cloudBlockBlob.UploadFromStream(fs);
                    }
                }
                if (i == 2)
                {
                    CloudBlobDirectory Img = container.GetDirectoryReference(floder + "files");
                    string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(filename);
                    CloudBlockBlob cloudBlockBlob = Img.GetBlockBlobReference(imageName);
                    CloudBlobClient blobClient1 = storageAccount.CreateCloudBlobClient();
                    ErpDataAccess.GetInstance.InsertData(Img.ToString());
                    using (var fs = File.OpenRead(obj))
                    {
                        cloudBlockBlob.UploadFromStream(fs);
                    }
                }
                if (i == 3)
                {
                    CloudBlobDirectory Img = container.GetDirectoryReference(floder + "music");
                    string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(filename);
                    CloudBlockBlob cloudBlockBlob = Img.GetBlockBlobReference(imageName);
                    CloudBlobClient blobClient1 = storageAccount.CreateCloudBlobClient();
                    ErpDataAccess.GetInstance.InsertData(Img.ToString());
                    using (var fs = File.OpenRead(obj))
                    {
                        cloudBlockBlob.UploadFromStream(fs);
                    }
                }

            }
}

Window Azure ,Test HTTPS for your custom domain in Window Azure. And Navigate to custom domain using Kudu debug console for your app.

================
for example we want to set https:// ( SLS  Certificate) to my Custom domain from azure then the process is.
=============
If you still want to allow HTTP access to your app, skip this step. App Service does not enforce HTTPS, so visitors can still access your app using HTTP. If you want to enforce HTTPS for your app, you can define a rewrite rule in the web.config file for your app. Every App Service app has this file, regardless of the language framework of your app.




Follow these steps:
  1. Navigate to the Kudu debug console for your app. Its address is https://<appname>.scm.azurewebsites.net/DebugConsole.
  2.  for Example- https://satyabrata.scm.azurewebsites.net/DebugConsole
  3. After that we login using azure uid and password. Next-
  4. In the debug console, CD to D:\home\site\wwwroot.
  5. Open web.config by clicking the pencil button.

  1. If you deploy your app with Visual Studio or Git, App Service automatically generates the appropriate web.config for your .NET, PHP, Node.js, or Python app in the application root. If web.config doesn't exist, run touch web.config in the web-based command prompt to create it. Or, you can create it in your local project and redeploy your code.
  2. If you had to create a web.config, copy the following code into it and save it. If you opened an existing web.config, then you just need to copy the entire <rule> tag into your web.config'sconfiguration/system.webServer/rewrite/rules element.
    Copy
     <?xml version="1.0" encoding="UTF-8"?>
     <configuration>
       <system.webServer>
         <rewrite>
           <rules>
             <!-- BEGIN rule TAG FOR HTTPS REDIRECT -->
             <rule name="Force HTTPS" enabled="true">
               <match url="(.*)" ignoreCase="false" />
               <conditions>
                 <add input="{HTTPS}" pattern="off" />
               </conditions>
               <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
             </rule>
             <!-- END rule TAG FOR HTTPS REDIRECT -->
           </rules>
         </rewrite>
       </system.webServer>
     </configuration>
    
    This rule returns an HTTP 301 (permanent redire

Insert Update Delete with Popup Window using Ado .net

Designing File
------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CRUD.aspx.cs" Inherits="CRUD.CRUD" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>GridView Add, Edit, Delete AJAX Way</title>
    <link href="CSS/CSS.css" rel="stylesheet" type="text/css" />
    <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="scripts/jquery.blockUI.js" type="text/javascript"></script>
    <script type="text/javascript">
        function BlockUI(elementID) {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_beginRequest(function () {
                $("#" + elementID).block({
                    message: '<table align = "center"><tr><td>' +
             '<img src="images/loadingAnim.gif"/></td></tr></table>',
                    css: {},
                    overlayCSS: {
                        backgroundColor: '#000000', opacity: 0.6
                    }
                });
            });
            prm.add_endRequest(function () {
                $("#" + elementID).unblock();
            });
        }
        $(document).ready(function () {

            BlockUI("<%=pnlAddEdit.ClientID %>");
            $.blockUI.defaults.css = {};
        });
            function Hidepopup() {
                $find("popup").hide();
                return false;
            }
    </script>
    <script type="text/javascript">
        function isNumber(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                return false;
            }
            return true;
        }
    </script>
</head>
<body style="margin: 0; padding: 0">
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:HiddenField ID="HdnId" runat="server" />
                <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" />
                <asp:LinkButton ID="lnkFake" runat="server"></asp:LinkButton>
                <div id="Show" runat="server">
                    <asp:GridView ID="GridView1" runat="server" Width="1253px"
                        AutoGenerateColumns="False" AlternatingRowStyle-BackColor="#C2D69B"
                        HeaderStyle-BackColor="green" AllowPaging="True"
                        OnPageIndexChanging="OnPaging" CellPadding="4" ForeColor="#333333" GridLines="None">
                        <Columns>
                            <asp:BoundField DataField="firstname" HeaderText="First Name" HtmlEncode="true" />
                            <asp:BoundField DataField="lastname" HeaderText="Last Name" HtmlEncode="true" />
                            <asp:BoundField DataField="contact" HeaderText="Contact No" HtmlEncode="true" />
                            <asp:TemplateField ItemStyle-Width="30px">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" OnClick="Edit"></asp:LinkButton>
                                    <asp:LinkButton ID="LnkDelete" runat="server" Text="Delete" OnClick="LnkDelete_Click"></asp:LinkButton>
                                    <asp:Label ID="LblId" runat="server" Text='<%# Eval("employeeid") %>' Visible="false" />
                                </ItemTemplate>
                                <ItemStyle Width="30px" />
                            </asp:TemplateField>
                        </Columns>
                        <AlternatingRowStyle BackColor="White" />
                        <EditRowStyle BackColor="#2461BF" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#EFF3FB" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
                    </asp:GridView>
                </div>
                <div id="Hide" runat="server" style="margin-left:200px">
                    <asp:Label ID="Lbnljasj" runat="server" Text=".....No records found....." />
                </div>
                <asp:Panel ID="pnlAddEdit" runat="server" CssClass="modalPopup" Style="display: none">
                    <asp:Label Font-Bold="true" ID="Label4" runat="server" Text="Employee Details"></asp:Label>
                    <br />
                    <table align="center">
                        <tr>
                            <td>
                                <asp:Label ID="Label1" runat="server" Text="First Name"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="TxtFirstName" MaxLength="20" runat="server"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="ReQ1" runat="server" ControlToValidate="TxtFirstName" ErrorMessage="*" Display="Dynamic" ValidationGroup="Employee" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Label ID="Label2" runat="server" Text="Last Name"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="TxtLastName" runat="server" MaxLength="15"></asp:TextBox>
                                 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TxtLastName" ErrorMessage="*" Display="Dynamic" ValidationGroup="Employee" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Label ID="Label3" runat="server" Text="Contact no"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="TxtContactNo" runat="server" MaxLength="10" onkeypress="return isNumber(event)"></asp:TextBox>
                                 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TxtContactNo" ErrorMessage="*" Display="Dynamic" ValidationGroup="Employee" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" ValidationGroup="Employee"/>
                            </td>
                            <td>
                                <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick="return Hidepopup()" />
                            </td>
                        </tr>
                    </table>
                </asp:Panel>
                <cc1:ModalPopupExtender ID="popup" runat="server" DropShadow="false"
                    PopupControlID="pnlAddEdit" TargetControlID="lnkFake"
                    BackgroundCssClass="modalBackground">
                </cc1:ModalPopupExtender>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="GridView1" />
                <asp:AsyncPostBackTrigger ControlID="btnSave" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>
=============================================
C# Code
==========================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CRUD
{
    public partial class CRUD : System.Web.UI.Page
    {
        string strConnString = ConfigurationManager.ConnectionStrings["DemoConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            string strQuery = "select employeeid,firstname,lastname,contact" +
                               " from Employee";
            SqlCommand cmd = new SqlCommand(strQuery);
            DataTable dt1 = GetData(cmd);
            if (dt1.Rows.Count > 0)
            {
                Show.Visible = true;
                Hide.Visible = false;
                GridView1.DataSource = GetData(cmd);
                GridView1.DataBind();
            }
            else
            {
                Show.Visible = false;
                Hide.Visible = true;
            }
        }

        private DataTable GetData(SqlCommand cmd)
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    con.Open();
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                    return dt;
                }
            }
        }

        protected void OnPaging(object sender, GridViewPageEventArgs e)
        {
            this.BindData();
            GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataBind();
        }

        protected void Edit(object sender, EventArgs e)
        {
            using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
            {
                TxtFirstName.Text = row.Cells[0].Text;
                TxtLastName.Text = row.Cells[1].Text;
                TxtContactNo.Text = row.Cells[2].Text;
                Label id=(Label)row.FindControl("LblId");
                HdnId.Value = id.Text;
                popup.Show();
            }
        }

        protected void Add(object sender, EventArgs e)
        {
            TxtFirstName.Text = string.Empty;
            TxtLastName.Text = string.Empty;
            TxtContactNo.Text = string.Empty;
            HdnId.Value = "";
            popup.Show();
        }

        protected void Save(object sender, EventArgs e)
        {
            if (HdnId.Value == "")
            {
                string query = "INSERT INTO Employee (firstname, lastname, contact) VALUES ('" + TxtFirstName.Text + "', '" + TxtLastName.Text + "', " + TxtContactNo.Text + " )";
                SqlConnection con = new SqlConnection(strConnString);
                con.Open();
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.ExecuteNonQuery();
            }
            else
            {
                string ty = "UPDATE Employee SET firstname='" + TxtFirstName.Text + "',lastname='" + TxtLastName.Text + "',contact=" + TxtContactNo.Text + " WHERE employeeid=" + HdnId.Value + "";
                SqlConnection con = new SqlConnection(strConnString);
                con.Open();
                SqlCommand cmd = new SqlCommand(ty, con);
                cmd.ExecuteNonQuery();
                HdnId.Value = "";
            }
            BindData();
        }
        protected void LnkDelete_Click(object sender, EventArgs e)
        {
            using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
            {
                Label id = (Label)row.FindControl("LblId");
                string ty = "DELETE FROM Employee WHERE employeeid=" + id.Text + "";
                SqlConnection con = new SqlConnection(strConnString);
                con.Open();
                SqlCommand cmd = new SqlCommand(ty, con);
                cmd.ExecuteNonQuery();
            }
            BindData();
        }
    }
}

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


===========================================
Table Design
=======================================



vjj



Wednesday, 4 January 2017

Create a Web Api Service and call it in to Asp.net Project.

First Create a Web Api project. Net Add a Controller. in this Controller. you Write. Add a Layer which name is Data Access Layer. Next add a Web Application with a Page which name is Default.aspx.


 public class TestController : ApiController
    {
        MyModelEntities db = new MyModelEntities();
        // GET: api/Test
        Class1 cl = new Class1();
        public HttpResponseMessage Get()
        {
            var v = (from c in cl.getdata() select
                         new demo{
                         Id=c.Id.ToString(),
                         Contact_Id = c.Contact_Id.ToString(),
                         Contact_Name=c.Contact_Name
                         }).ToList();

            return new HttpResponseMessage()
            {
                Content = new StringContent(JArray.FromObject(v).ToString(), Encoding.UTF8, "application/Json")
            };
        }
        public class demo
        {
            public string Id { get; set; }
            public string Contact_Id { get; set; }
            public string Contact_Name { get; set; }

            public string City { get; set; }
        }
        // GET: api/Test/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Test
        public HttpResponseMessage Post([FromBody]string name)
        {
            DataAccessLayer.tbl_Contact tcc = new DataAccessLayer.tbl_Contact();
            tcc.Contact_Name = name;
            cl.insertData(tcc);
            //return obj;
            var v = (from c in cl.getdata()
                     select
                         new demo
                         {
                             Id = c.Id.ToString(),
                             Contact_Id = c.Contact_Id.ToString(),
                             Contact_Name = c.Contact_Name
                         }).ToList();
            return new HttpResponseMessage()
            {
                Content = new StringContent(JArray.FromObject(v).ToString(), Encoding.UTF8, "application/Json")
            };
        }

        // PUT: api/Test/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Test/5
        public HttpResponseMessage Delete(int id)
        {

            DataAccessLayer.tbl_Contact tcc = new DataAccessLayer.tbl_Contact();
            tcc.Id = id;
            cl.DeleteData(tcc);
            //return obj;
            var v = (from c in cl.getdata()
                     select
                         new demo
                         {
                             Id = c.Id.ToString(),
                             Contact_Id = c.Contact_Id.ToString(),
                             Contact_Name = c.Contact_Name
                         }).ToList();
            return new HttpResponseMessage()
            {
                Content = new StringContent(JArray.FromObject(v).ToString(), Encoding.UTF8, "application/Json")
            };
        }



     
    }
=====================================================
 In DataAccess Layer
====================================================
 public partial class Class1
    {
        InductionNewEntities db = new InductionNewEntities();
        public  IEnumerable<tbl_Contact> getdata()
        {
            var v = from c in db.tbl_Contact select c;

            string data = "";
            return v.ToList();
        }


        public tbl_Contact insertData(tbl_Contact obj)
        {
            using (var ve = new InductionNewEntities())
            {
                tbl_Contact tc = new tbl_Contact();
                tc.Contact_Name = obj.Contact_Name;
                ve.tbl_Contact.Add(tc);
                ve.SaveChanges();
                return obj;
            }
        }
        public tbl_Contact DeleteData(tbl_Contact obj)
        {
            using (var ve = new InductionNewEntities())
            {
                tbl_Contact tc = db.tbl_Contact.Where(t=> t.Id==obj.Id).First();

                db.tbl_Contact.Remove(tc);
                db.SaveChanges();
                return obj;
            }
        }
    }
================================================

In Asp.net Project
==============================================
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button id="btn_post" runat="server" Text="Post" OnClick="btn_post_Click"/>
    <asp:Button id="btn_get" runat="server" Text="Get" OnClick="btn_get_Click"/>
        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
        <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Id">
                    <ItemTemplate>
                        <asp:Label ID="lbl_id" runat="server" Text='<%# Eval("Id") %>' ></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lbl_ContactName" runat="server" Text='<%# Eval("Contact_Name") %>' ></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="ContactId">
                    <ItemTemplate>
                        <asp:Label ID="lbl_ContactId" runat="server" Text='<%# Eval("Contact_Id") %>' ></asp:Label>
                    </ItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:Button Text="Delete" runat="server" CommandArgument='<%# Eval("Id") %>' ID="btn_del" OnClick="btn_del_Click"  />
                    </ItemTemplate>

                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
===============================================
C# Code in Web Page
===============================================
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using DataAccessLayer;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {

         
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            { 
            
            }
        }
        public  List<demo> demoList = new List<demo>();
        public  class demo
        {
            public string Id { get; set; }
            public string Contact_Id { get; set; }
            public string Contact_Name { get; set; }
        }
        
        protected void btn_post_Click(object sender, EventArgs e)   
         {
             HttpClient client = new HttpClient();
             client.BaseAddress = new Uri("http://localhost:49504/");

             // Add an Accept header for JSON format.
             client.DefaultRequestHeaders.Accept.Add(
                 new MediaTypeWithQualityHeaderValue("application/json"));

             var user = new demo();

             user.Contact_Name = txt_name.Text;

             var response = client.PostAsJsonAsync("api/Test", txt_name.Text).Result;

             if (response.IsSuccessStatusCode)
             {
                 Response.Write("User Added");

                 getdata();
             }
             else
             {
                 Response.Write("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
             }
        }
        public void getdata()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:49504/");

            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.GetAsync("api/Test").Result;

            if (response.IsSuccessStatusCode)
            {
                var users = response.Content.ReadAsAsync<IEnumerable<demo>>().Result;

                //usergrid.ItemsSource = users;
                GridView1.DataSource = users.ToList();
                GridView1.DataBind();
            }
            else
            {
                //MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
                Response.Write("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
            }
        }
        protected void btn_get_Click(object sender, EventArgs e)
        {
            getdata();
        }

        protected void btn_del_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            int id = Convert.ToInt32(btn.CommandArgument);

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:49504/");

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var user = new demo();

            user.Contact_Name = txt_name.Text;

            var url = "api/Test/" + id;

            HttpResponseMessage response = client.DeleteAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                Response.Write("User Deleted ");
                getdata();
            }
            else
            {
                Response.Write("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
            }
        }


    }
}

Sunday, 18 December 2016

How to set Transaction and Roll Back using Entity Framework in C# Code.

In Page Design
========================================
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestReansaction.aspx.cs" Inherits="WebApplication1.TestReansaction" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

        <asp:Button ID="button2" runat="server" Text="btn test 2" OnClick="button2_Click" />
   
    </div>
     
    </form>
</body>
</html>
=================================
In C# Code
====================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class TestReansaction : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
  protected void Button1_Click(object sender, EventArgs e)
        {
            using (CompanyEntities context = new CompanyEntities())
            {
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        EmployeeMaster employee = new EmployeeMaster();
                        employee.Code = "A0001";
                        employee.Name = "Jignesh Trivedi";
                        employee.DepartmentId =2;
                        context.EmployeeMasters.Add(employee);
                        context.SaveChanges();

                        DepartmentMaster dept = new DepartmentMaster();
                        dept.Code = "DEP000112765776767767676";
                        dept.Name = "Department 1";
                        context.DepartmentMasters.Add(dept);
                        context.SaveChanges();

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                    }
                }
            }  
        }
}

Create Schema Using C# Asp .Net Dynamically.

In WebConfig First Set The Connection String.
======================================

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <connectionStrings>
    <add name="InterviewConnectionString" connectionString="Data Source=SATYABRATA;Initial Catalog=Interview;Persist Security Info=True;User ID=satya;Password=satya@215;MultipleActiveResultSets=True;Application Name=EntityFramework"
          providerName="System.Data.SqlClient" />

  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>


</configuration>
======================================

Design Page in Source FIle
======================================
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Schema.aspx.cs" Inherits="CreateaSchema.Schema" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TxtSchema" runat="server" placeholder="Put Schema Name"></asp:TextBox>
            <br />
            <br />
            <asp:Button ID="BtnCreate" runat="server" Text="CreateSchematable" OnClick="BtnCreate_Click" />
            <asp:Button ID="BtnDelete" runat="server" Text="DeleteSchematable" OnClick="BtnDelete_Click" />
        </div>
    </form>
</body>

</html>
=======================================

In C# Code Write This
=========================================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CreateaSchema
    public partial class Schema : System.Web.UI.Page
    {
        DataTable schemaTable;
        SqlCommand cmd1;
        SqlDataReader dtp;
        List<string> tables;
        DataTable dt;
        string schemaname;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }
        protected void BtnCreate_Click(object sender, EventArgs e)
        {
            if (TxtSchema.Text != "")
            {
                #region Get Connection String
                var connectionString = ConfigurationManager.ConnectionStrings["InterviewConnectionString"].ConnectionString;
                var csb = new SqlConnectionStringBuilder(connectionString);
                string DataSource = csb.DataSource;
                #endregion
                #region Get All Tables
                SqlConnection objConn = new SqlConnection(connectionString);
                objConn.Open();
                tables = new List<string>();
                DataTable dt = objConn.GetSchema("Tables");
                foreach (DataRow row in dt.Rows)
                {
                    string tablename = (string)row[2];
                    tables.Add(tablename);
                }
                #endregion
                #region Create Schema
                foreach (DataRow row in dt.Rows)
                {
                    string schemaname = (string)row[1];
                    if (schemaname == TxtSchema.Text)
                    {
                        Response.Write("<script>alert('Schema Already exist !');</script>");
                        return;
                    }
                }
                string schema = TxtSchema.Text;
                string schema1 = "CREATE SCHEMA " + schema;
                SqlCommand cmd = new SqlCommand(schema1, objConn);
                cmd.ExecuteNonQuery();
                #endregion
                #region Create Schema table
                foreach (var item in tables)
                {
                    string ty = "SELECT * FROM " + item;
                    cmd1 = new SqlCommand(ty, objConn);
                    dtp = cmd1.ExecuteReader(CommandBehavior.KeyInfo);
                    schemaTable = dtp.GetSchemaTable();
                    string tyr = CreateTABLE(item, schemaTable, schema);
                    SqlCommand cmd3 = new SqlCommand(tyr, objConn);
                    cmd3.ExecuteNonQuery();
                }
                #endregion
                TxtSchema.Text = "";
            }
        }
        public static string CreateTABLE(string tableName, DataTable table, string schema)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["InterviewConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(connectionString);
            string sqlsc;
            sqlsc = "CREATE TABLE " + schema + "." + tableName + "(";
            for (int i = 0; i < table.Rows.Count; i++)
            {
                sqlsc += "\n [" + table.Rows[i]["ColumnName"] + "] ";
                string columnType = table.Rows[i]["DataType"].ToString();
                switch (columnType)
                {
                    case "System.Int32":
                        sqlsc += " int ";
                        break;
                    case "System.Int64":
                        sqlsc += " bigint ";
                        break;
                    case "System.Int16":
                        sqlsc += " smallint";
                        break;
                    case "System.Byte":
                        sqlsc += " tinyint";
                        break;
                    case "System.Decimal":
                        sqlsc += " decimal ";
                        break;
                    case "System.DateTime":
                        sqlsc += " datetime ";
                        break;
                    case "System.String":
                    default:
                        sqlsc += string.Format(" nvarchar({0}) ", table.Columns[i].MaxLength == -1 ? "max" : table.Columns[i].MaxLength.ToString());
                        break;
                }
                if (table.Columns[i].AutoIncrement)
                    sqlsc += " IDENTITY(" + table.Columns[i].AutoIncrementSeed.ToString() + "," + table.Columns[i].AutoIncrementStep.ToString() + ") ";
                if (!table.Columns[i].AllowDBNull)
                    sqlsc += " NOT NULL ";
                sqlsc += ",";
            }
            return sqlsc.Substring(0, sqlsc.Length - 1) + "\n)";
        }
        protected void BtnDelete_Click(object sender, EventArgs e)
        {
            if (TxtSchema.Text != "")
            {
                #region Get Connection String
                var connectionString = ConfigurationManager.ConnectionStrings["InterviewConnectionString"].ConnectionString;
                var csb = new SqlConnectionStringBuilder(connectionString);
                string DataSource = csb.DataSource;
                #endregion
                #region Get And Delete Schema
                SqlConnection objConn = new SqlConnection(connectionString);
                objConn.Open();
                tables = new List<string>();
                dt = objConn.GetSchema("Tables");
                foreach (DataRow row in dt.Rows)
                {
                    string tablename = (string)row[2];
                    tables.Add(tablename);
                }
                foreach (DataRow row in dt.Rows)
                {
                    schemaname = (string)row[1];
                    if (schemaname == TxtSchema.Text)
                    {
                        string Item = (string)row[2];
                        string query = "DROP TABLE " + schemaname + "." + Item;
                        SqlCommand cmd3 = new SqlCommand(query, objConn);
                        cmd3.ExecuteNonQuery();
                    }
                }
                string tyu = "DROP SCHEMA " + TxtSchema.Text;
                SqlCommand cmd4 = new SqlCommand(tyu, objConn);
                cmd4.ExecuteNonQuery();
                #endregion
                TxtSchema.Text = "";
            }
        }
    }
}
==========================================