European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET 4.5 Hosting - UK :: Zip File Manipulation in ASP.NET 4.5

clock December 11, 2014 08:16 by author Scott

One of the missing feature of .NET framework was a support for Zip file manipulation such as reading the zip archive, adding files, extracting files, etc. and we were using some third party libraries such as excellent the DotNetZip. In .NET 4.5, we have an extensive support for manipulating .zip files.

First thing that you should do is to add System.IO.Compression assembly as reference to your project. You may also want to reference System.IO.Compression.FileSystem assembly to access three extension methods (from the ZipFileExtensions class) for the ZipArchive class: CreateEntryFromFile,CreateEntryFromFile, and ExtractToDirectory. These extension methods enable you to compress and decompress the contents of the entry to a file.

Let’s cover the bits and pieces that we get from System.IO.Compression assembly at first. The below sample shows how to read a zip archive easily with ZipArchive class:

static void Main(string[] args) {

    const string zipFilePath = @"C:\apps\Sample Pictures.zip";

    using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
    using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read)) {

        foreach (var zipArchiveEntry in archive.Entries)
            Console.WriteLine(
                "FullName of the Zip Archive Entry: {0}", zipArchiveEntry.FullName
            );
    }
}

In this sample, we are opening the zip archive and iterate through the collection of entries. When we run the application, we should see the list of files inside the zip archive:

It’s also so easy to add a new file to the zip archive:

static void Main(string[] args) {

    const string zipFilePath = @"C:\apps\Sample Pictures.zip";

    using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
    using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Update)) {

        ZipArchiveEntry readMeEntry = archive.CreateEntry("ReadMe.txt");
        using (StreamWriter writer = new StreamWriter(readMeEntry.Open())) {
            writer.WriteLine("Lorem ipsum dolor sit amet...");
            writer.Write("Proin rutrum, massa sed molestie porta, urna...");
        }

        foreach (var zipArchiveEntry in archive.Entries)
            Console.WriteLine(
                "FullName of the Zip Archive Entry: {0}", zipArchiveEntry.FullName
            );
    }
}

In this sample, we are adding a file named ReadMe.txt at the root of archive and then we are writing some text into that file.

Extracting files is into a folder is so easy as well. You need reference the System.IO.Compression.FileSystem assembly along with System.IO.Compression assembly as mentioned before for this sample:

static void Main(string[] args) {

    const string zipFilePath = @"C:\apps\Sample Pictures.zip";
    const string dirToExtract = @"C:\apps\Sample Pictures\";

    using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
    using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Update))
        archive.ExtractToDirectory(dirToExtract);
}

There are some other handy APIs as well but it is so easy to discover them by yourself. 



HostForLIFE.eu Proudly Launches ASP.NET 5 Hosting

clock December 8, 2014 10:06 by author Peter

European leading web hosting provider, HostForLIFE.eu announces the launch of ASP.NET 5  support on the recently released Windows Server 2012 R2.

HostForLIFE.eu was established to cater to an under served market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu – a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the ASP.NET 5 hosting in our entire servers environment.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET 5 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

According to Microsoft officials, much of the functionality in the ASP.NET 5 release is a new flexible and cross-platform runtime, a new modular HTTP request pipeline, Cloud-ready environment configuration, Unified programming model that combines MVC, Web API, and Web Pages, Ability to see changes without re-building the project, etc.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting our ASP.NET 5 site on our environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET  based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European ASP.NET 5 hosting installation to all our new and existing customers. The customers can simply deploy our ASP.NET 5 website via our world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features ASP.NET 5 Hosting can be viewed here http://hostforlife.eu/European-ASPNET-5-Hosting

About Company
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.



ASP.NET 5 Hosting - HostForLIFE.eu :: Auto Resize Text Box in ASP.NET

clock December 5, 2014 06:53 by author Peter

In this article, we want to talk about How to to develop a simple Example of text box control with ASP.NET 5. Once we enter data during this text box control we want to the length (re-size height and width) of text box. Text box is an ASP.NET web control, use for obtaining input by user as similar to the login web site we see username and password Textbox exactly in which we enter username and password. Inside the Toolbox we obtain a textbox only drag and drop it on ASP.NET web site and then it is automatically create our html code. We think about a text box and attempt to Auto re-size it once we enter value in text box.

And this is the example code that I used:
JavaScript function for resize ASP.NET control
And here is the Text Box auto resize function.

function resizemultilineTextBox(txt) {
            txt.style.height = "1px";
            txt.style.height = (1 + txt.scrollHeight) + "px";
        }
Asp.net web page code with Textbox:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Autoresizetextboxcontrol.aspx.cs" Inherits="Autoresizetextboxcontrol" %>
<!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></title>
        <script>
        function resizemultilineTextBox(txt) {
            txt.style.height = "1px";
            txt.style.height = (1 + txt.scrollHeight) + "px";
        }
    </script>
    <style type="text/css">
        .style1
        {
            color: #990000;
            text-decoration: underline;
            font-family: Arial, Helvetica, sans-serif;
        }
    </style>
</head>
<body>
    <form id="form2" runat="server">
        <div align="center" style="height: 123px; background-color: #6699FF">
        <h1 class="style1">Auto Resize ASP.NET TextBox Control</h1>
            <table style="width: 494px">
                <tr>
                    <td>Enter Text Here: </td>
                    <td>                      
                        <asp:TextBox ID="txtDescription" runat="server"                            

onkeyup="resizemultilineTextBox(this)" TextMode="MultiLine" Width="212px">
</asp:TextBox>                      
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>



European ASP.NET 4.5 Hosting - France :: Using HTML 5 and ASP.NET to Upload Files

clock December 4, 2014 07:03 by author Scott

ASP.NET web applications that require uploading files from the client machine to the server use the file field to select files. The selected files are uploaded to the server using form submission techniques. In addition to the file field, HTML5 also allows you to select files using drag and drop. Using this feature you can drag files from Windows Explorer or Desktop and drop them on a predefined area of a web page. The files can then be uploaded to the server. This article illustrates how the HTML5 drag and drop feature can be used to upload files on the server.  

Traditionally you use the HTML file field to select files that are to be uploaded to the server. ASP.NET web forms wrap the file field into the FileUpload server control and ASP.NET MVC applications can use an <input> element with type attribute set to file. Another alternative offered by HTML5 is dragging one or more files from Windows Explorer or Desktop and drop them onto some predefined HTML element of a web page. You can then access the dropped files using the dataTransfer object available to drag and drop events.

To understand how files can be selected using the drag and drop features of HTML5, let's develop a new ASP.NET web forms application. The HTML markup of the default web form is shown below:

<form id="form1" runat="server">
<center>
 
<div id="box">Drag & Drop files from your machine on this box.</div>
 
<br />
 
<input id="upload" type="button" value="Upload Selected Files" />
</center>
</form>

As you can see, the <form> consists of a <div> element and a button. The <div> element is intended to drop the files dragged from the local machine. Merely dropping the files won't upload them to the server. Clicking on the button initiates the file upload operation.

To handle the file drop operation you need to wire certain event handlers to the box <div> element. The following jQuery code shows how that can be done:

var selectedFiles; 

$(document).ready(function () {
  var box;
  box = document.getElementById("box");
  box.addEventListener("dragenter", OnDragEnter, false);
  box.addEventListener("dragover", OnDragOver, false);
  box.addEventListener("drop", OnDrop, false);
...
}

The code declares a global variable named selectedFiles for storing a list of selected files. The ready() function wires three event handler functions to the respective events of the box <div> element, viz. dragenter, dragover and drop using addEventListener() method. The first parameter of the addEventListener() method is the event name and the second parameter is the event handler function. The event handler functions are shown below:

function OnDragEnter(e) {
  e
.stopPropagation();
  e
.preventDefault();
} 

function OnDragOver(e) {
  e
.stopPropagation();
  e
.preventDefault();
} 

function OnDrop(e) {
  e
.stopPropagation();
  e
.preventDefault();
  selectedFiles
= e.dataTransfer.files;
  $
("#box").text(selectedFiles.length + " file(s) selected for uploading!");
}

The OnDragEnter() and OnDragOver() event handler functions are simple and they merely prevent the event bubbling of the respective events. The OnDrop() function is important since it handles the drop event. The list of files dragged and dropped on the <div> element is obtained using the files property of the dataTransfer object. The files object is of type FileList and each item of the FileList collection is of type File. These two objects are available as a part of the HTML5 File API. The OnDrop() function stores the selected files in the global variable - selectedFiles and displays a message in the <div> using the text() method that indicates the number of files selected. The following figure shows how the default web form looks after dragging and dropping files on the <div> element.

Default web form after dragging and dropping files to the <div> element

How to Send Files to the Servere?

To send the selected files from the client to the server you can use different techniques but in this example you will use jQuery $.ajax() method for uploading the files. The following code shows how $.ajax() method can be used for this purpose.

$("#upload").click(function () {
  var data = new FormData();
  for (var i = 0; i < selectedFiles.length; i++) {
    data.append(selectedFiles[i].name, selectedFiles[i]);
  }
  $.ajax({
    type: "POST",
    url: "FileHandler.ashx",
    contentType: false,
    processData: false,
    data: data,
    success: function (result) {
      alert(result);
    },
    error: function () {
      alert("There was error uploading files!");
    }
  });
});

The code shown above first creates a FormData object. The FormData object encapsulates form's data that you wish to send to the server. All the selected files are added to the FormData object using its append() method. The first parameter of the append() method is the name of the file being added and the second parameter is the File object itself. Once the FormData object is ready you make a POST request to a Generic ASP.NET Handler (FileHandler.ashx) using jQuery $.ajax() method. You will create the generic handler in the next section.

The type of the request is POST. The url is FileHandler.ashx. Notice that the processData option is set to false. By default when you use the $.ajax() method the data is sent in URL encoded format. To prevent this behavior processData is set to false. The data option  is set to the FormData object created earlier. The success function simply displays the message returned by the generic handler. The error handler function displays an error message in case there is any error while calling FileHandler.ashx.

Receive the Uploaded Files

The ASP.NET generic handler - FileHandler.ashx - receives the files sent by the $.ajax() method. The generic handler also saves them to a folder on the server. The following code shows how the handler accomplishes this task:

public void ProcessRequest(HttpContext context)
{
   
if (context.Request.Files.Count > 0)
   
{
       
HttpFileCollection files = context.Request.Files;
       
foreach (string key in files)
       
{
           
HttpPostedFile file = files[key];
           
string fileName = file.FileName;
            fileName
= context.Server.MapPath("~/uploads/" + fileName);
            file
.SaveAs(fileName);
       
}
   
}
    context
.Response.ContentType = "text/plain";
    context
.Response.Write("File(s) uploaded successfully!");
}

The ProcessRequest() method of the FileHandler.ashx is called when the files are sent to the server using the $.ajax() method. The uploaded files can be accessed using the Files collection of the Request object. Each item inside the Files collection is of type HttpPostedFile. A foreach loop iterates through all the files from the Files collection and saves the individual file using the SaveAs() method of HttpPostedFile class. Once all files are saved a success message is sent to the client.

Note that by default ASP.NET sets request length to 4096 bytes. If you wish to upload large files you may adjust the request length using web.config file as shown below:

<httpRuntime
  
maxRequestLength="20000"
  
requestValidationMode="4.5"
  
targetFramework="4.5"
  
encoderType="..." />

As you can see the maxRequestLength attribute of the <httpRuntime> section is set to 20000 bytes. You need to adjust this value as per your requirement.

That's it! You can now run the web form, drag and drop files on the <div> element and click on the "Upload Selected Files" button to upload them on the server. 



ASP.NET 5 Hosting - HostForLIFE.eu :: How to create “Remember Me” Login Page using checkbox with ASP.NET ?

clock December 1, 2014 06:12 by author Peter

In this tutorial, I will tell you How to create “Remember Me” Login Page using checkbox with ASP.NET 5 and C#. Whenever you tick Remember Me checkbox it will maintain username and password for web site user using Cookies.

When user click login button that could stores the username and password inside the cookie. First thing you need to do is confirm that the Remember Me checkbox is checked or not, if it's checked then store the username and password inside the cookie to the 1 month and if not checked then set the expiration day to 1 day in else condition to destroy the cookie.

And here is the code that I used:

protected void Page_Load(object sender, EventArgs e)  

      if (!Page.IsPostBack) 
      { 
           if (Request.Cookies["UserName"] != null) 
                txtUserName.Text = Request.Cookies["UserName"].Value; 
           if (Request.Cookies["Password"] != null) 
                txtPassword.Text = Request.Cookies["Password"].Value; 
           if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null) 
                chkRember.Checked = true;  
      }  
}  
protected void btnLogin_Click(object sender, EventArgs e) 
 { 
       string stringconnection = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; 
       MySqlConnection connection = new MySqlConnection(stringconnection); 
      try 
      {  
           int flag = 0; 
           if (chkRember.Checked == true) 
           { 
                Response.Cookies["UserName"].Value = txtUserName.Text; 
                Response.Cookies["Password"].Value = txtPassword.Text; 
                Response.Cookies["UserName"].Expires = DateTime.Now.AddMonths(1); 
                Response.Cookies["Password"].Expires = DateTime.Now.AddMonths(1); 
           } 
           else 
           { 
                Response.Cookies["UserName"].Expires = DateTime.Now.AddMonths(-1); 
                Response.Cookies["Password"].Expires = DateTime.Now.AddMonths(-1); 
           }  
           MySqlCommand com = new MySqlCommand("select * from tbl_user_details", connection); 
           connection.Open(); 
           if (connection.State == ConnectionState.Open) 
           { 
                MySqlDataReader objSqlDataReader;                
                objSqlDataReader = com.ExecuteReader();

                    while (objSqlDataReader.Read())                 
                     { 
                     if (objSqlDataReader[2].ToString().Equals(txtUserName.Text) && objSqlDataReader[5].ToString().Equals(txtPassword.Text)) 
                     { 
                          flag = 1; 
                          Session["UserName"] = txtUserName.Text; 
                          Session["UserType"] = objSqlDataReader[8].ToString(); 
                          Response.Redirect("ContactUs.aspx", false); 
                     } 
                     else 
                     { 
                          ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>"); 
                    } 
                } 
           } 
      } 
      catch (Exception ex) 
      { 
           lblMsg.Text = ex.ToString(); 
      } 
      finally  
      { 
           connection.Close(); 
      }
 }



UK ASP.NET 4.5.2 Hosting - HostForLIFE.eu :: How to Use NServiceBus with ASP.NET SignalR ?

clock November 24, 2014 06:35 by author Peter

In this tutorial, I will tell you how to use NServiceBus with ASP.NET SignalR. In detail right listed below what I'm planning to do is periodically publish an event utilizing NServiceBus. I will be able to use a ASP.NET MVC application as my front end and there I will be able to use a an additional NServiceBus client and that is liable for capturing event broadcasted from the NServiceBus publisher. Then working with ASP.NET SignalR, I will certainly be updating the UI with others captured events content.

First, Add a new ASP. NET MVC application to the solution.

Currently I'm running NServiceBus. Host and Microsoft ASP. NET SignalR nuget packages on ASP. NET MVC project using Package Manager Console. NServiceBus. Host can add the EndpointConfig. cs towards the project and I'm keeping as it's. Currently I'm making a folder named “SignalR” within my project and I'm heading to add a brand new category there named “EventMessageHandler”.
public class EventMessageHandler : IHandleMessages<MyMessage>
{
    public void Handle(MyMessage message)
    { 
    }
}

When the NServiceBus has revealed an event of kind “MyMessage”, “Handle” method in “EventMessageHandler” class can tackle it. For the moment, lets maintain the “Handle” method empty and let’s add a OWIN Startup class towards the project by right clicking upon the App_Start folder and selecting a OWIN Startup class template.

Next step, I am modifying the created OWIN Startup class with these code:
using Owin;
using Microsoft.Owin;
using NServiceBus; 
[assembly: OwinStartup(typeof(NServiceBusSignalRSample.Startup))]
namespace NServiceBusSignalRSample
{
    public class Startup
    {
        public static IBus Bus { get; private set; } 
        public static void Configuration(IAppBuilder app)
        {
            Bus = Configure
                    .With()
                    .DefaultBuilder()
                    .DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("NServiceBusSignalRSample.Messages"))
                    .PurgeOnStartup(false)
                    .UnicastBus()
                    .LoadMessageHandlers()
                    .CreateBus()
                    .Start(); 
            app.MapSignalR();
        }
    }
}


Right listed below I've configured my NServiceBus host and I'm mapping SignalR hubs towards the app builder pipeline. Next action is to make a SignalR hub. For the I'm adding the listed class towards the previously produced “SignalR” folder.

public class MyHub : Hub{
    public void Send(string name, string message)
    {
        Clients.All.addNewMessageToPage(name, message);
    }
}

Currently right listed below I'm deriving “MyHub” class from “Hub” and I ve got a method there named “Send” that takes 2 parameters. Within the method, I'm calling the consumer aspect “addNewMessageToPage” that still I haven’t wrote.

Just before starting off using the client aspect code, let’s modify the “Handle” method in “EventMessageHandler” class now to call my hubs’ send method.
public class EventMessageHandler : IHandleMessages<MyMessage>
{
    public void Handle(MyMessage message)
    {
        IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
        hubContext.Clients.All.addNewMessageToPage(message.Message, "Peter");
    }
}

Next,  I'm ready along with the back end code. Final thing to become done is to make a view in client side, initiate the hub connection and build a method named “addNewMessageToPage”. For the first I'm modifying the “HomeController” and adding a brand new Action there named “SignalR”.
public ActionResult SignalR()
{
    return View();
}

Then I'm correct clicking upon the Motion and making a new view along with a similar name “SignalR”. I'm modifying the “SignalR” view as follows.
@{
    ViewBag.Title = "SignalR";
}
<h2>SignalR</h2> 
<div class="container">
    <ul id="output"></ul>
</div> 
@section scripts {
    <script src="~/Scripts/jquery.signalR-2.1.1.min.js"></script>
    <script src="~/signalr/hubs"></script>
     <script>       
       $(function () {
            $.connection.hub.logging = true;
            $.connection.hub.start();
            var chat = $.connection.myHub; 
            chat.client.addNewMessageToPage = function (message, name) {
$('#output').append('<li>' + message + ' ' + name + '</li>');          
 };
        });
    </script>
}

Now I'm ready. One last factor to become done is to line multiple startup projects.

Finally, I'm running the Apps. Hope this post works for you!



ASP.NET 4.5.2 Hosting Germany - HostForLIFE.eu :: Learn How to Add or Update Record with GridView control in ASP.NET

clock November 21, 2014 05:08 by author Peter

A Gridview is really a control for displaying and manipulating data from completely different data sources. It shows data from a sort of data sources inside a tabular format. Rather than boundfiled, I like to make use of TemplateField coz of the simplicity. In this article I am going to implement how to Add, Update, Delete selected record from GirdView control in ASP.NET 4.5.2

This the code for Add new record from footer and Update the selected row.

Default.aspx:
<asp:gridview allowpaging="True" autogeneratecolumns="False" cellpadding="4" forecolor="#333333" gridlines="None" id="gvstatus" onpageindexchanging="gvstatus_PageIndexChanging" onrowcancelingedit="gvstatus_RowCancelingEdit" onrowcommand="gvstatus_RowCommand" onrowediting="gvstatus_RowEditing" onrowupdating="gvstatus_RowUpdating" onselectedindexchanged="gvstatus_SelectedIndexChanged" runat="server" showfooter="True" width="600px">
            <columns>
 <asp:templatefield headerstyle-horizontalalign="Left" headertext="SrNo ">
            <itemtemplate>
                    &lt;%# Container.DataItemIndex + 1 %&gt;
                </itemtemplate>
 </asp:templatefield>

 <asp:templatefield headertext="ID" visible="false">
      <itemtemplate>
      <asp:label columnname_id="" id="lblid" runat="server" text="&lt;%# Bind(">"&gt; </asp:label>
     </itemtemplate>
</asp:templatefield>
<asp:templatefield headertext="EmpName">
      <itemtemplate>
        <asp:label columnname_empname="" id="lblEmpName" runat="server" text="&lt;%# Bind(">"&gt;</asp:label>
       </itemtemplate>
       <edititemtemplate>
           <asp:textbox id="txtEmpName" runat="server" text="&lt;%# Bind(&quot;columnname_EmpName&quot;) %&gt;"></asp:textbox>
        </edititemtemplate>
        <footertemplate>
              <asp:textbox id="txtfEmpName" runat="server"></asp:textbox>
        </footertemplate>
</asp:templatefield>
 <asp:templatefield headertext="empSalary">
        <itemtemplate>
           <asp:label id="lblempSalary" runat="server" text="&lt;%# Bind(&quot;columnname_EmpSalary&quot;) %&gt;"></asp:label>
        </itemtemplate>
        <edititemtemplate>
             <asp:textbox id="txtempSalary" runat="server" text="&lt;%# Bind(&quot;columnname_EmpSalary&quot;) %&gt;"></asp:textbox>
         </edititemtemplate>
         <footertemplate>
            <asp:textbox id="txtfempSalary" runat="server"></asp:textbox>
         </footertemplate>
</asp:templatefield>
 <asp:templatefield itemstyle-width="190px" showheader="False">
         <itemtemplate>
             <asp:button causesvalidation="False" commandname="Edit" id="btnedit" runat="server" text="Edit"></asp:button>
          </itemtemplate>
          <edititemtemplate>
               <asp:button causesvalidation="True" commandname="Update" id="btnupdate" runat="server" text="Update"></asp:button>
                        &nbsp;<asp:button causesvalidation="False" commandname="Cancel" id="btncancel" runat="server" text="Cancel"></asp:button>
         </edititemtemplate>
        <footertemplate>
            <asp:button commandname="Add" id="btnadd" runat="server" text="Add">
        </asp:button></footertemplate>
 </asp:templatefield>
            </columns>
            <pagerstyle backcolor="#A86E07" forecolor="White" horizontalalign="Center">
            <selectedrowstyle backcolor="#E2DED6" font-bold="True" forecolor="#333333">
          <headerstyle backcolor="#A86E07" font-bold="True" forecolor="White">
        <editrowstyle backcolor="#d9d9d9">
    <alternatingrowstyle backcolor="White" forecolor="#A86E07">
 </alternatingrowstyle></editrowstyle></headerstyle></selectedrowstyle>
</pagerstyle>
</asp:gridview>

CodeBehind:
protected void Page_Load(object sender, EventArgs e)
    {
       if (!Page.IsPostBack)
       {
         gvBind(); //Bind gridview
       }
     }
public void gvBind()
{   
SqlDataAdapter dap = new SqlDataAdapter("select id, empName,empSalary from myTable", conn);    DataSet ds = new DataSet();
     dap.Fill(ds);
     gvstatus.DataSource = ds.Tables[0];
     gvstatus.DataBind();
}
Update the select row from girdview
protected void gvstatus_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        lblmsg.Text = "";
        try
        {
            GridViewRow row = (GridViewRow)gvstatus.Rows[e.RowIndex];
            Label lblid = (Label)gvstatus.Rows[e.RowIndex].FindControl("lblid");
            TextBox txtname = (TextBox)gvstatus.Rows[e.RowIndex].FindControl("txtEmpName");
            TextBox txtSalary = (TextBox)gvstatus.Rows[e.RowIndex].FindControl("txtempSalary");
            string empName = txtname.Text;
            string empSalary = txtSalary.Text;
            string lblID=lblid.Text;
            int result = UpdateQuery(empName, empSalary,lblID);
            if (result > 0)
            {
                lblmsg.Text = "Record is updated successfully.";
            }
            gvstatus.EditIndex = -1;
            gvBind();
        }
        catch (Exception ae)
        {
            Response.Write(ae.Message);
        }
    }

And this is the Code that I used to add new record into database form GirdView footer
  protected void gvstatus_RowCommand(object sender, GridViewCommandEventArgs e)   
{       
        if (e.CommandName == "Add")
        {
            string empName = ((TextBox)gvstatus.FooterRow.FindControl("txtfempName")).Text;
            string empSalry = ((TextBox)gvstatus.FooterRow.FindControl("txtfempSalary")).Text;
            int result = InsertNewRecord(empName, empSalry);
            if (result > 0)
            {
                lblmsg.Text = "Record is added successfully.";
            }
            gvstatus.EditIndex = -1;
            gvBind();
        }
    }
protected void gvstatus_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
 gvstatus.EditIndex = -1;
 gvBind();
}
 protected void gvstatus_RowEditing(object sender, GridViewEditEventArgs e)
{
 lblmsg.Text = "";
 gvstatus.EditIndex = e.NewEditIndex;
 gvBind();
}
public void UpdateQuery(string empName, string empSalary, string lblID)
{
 SqlCommand cmd = new SqlCommand("update myTable set empName='" + empName + "',empSalary='" + empSalary + "' where  id='" + lblID + "'", conn);
 conn.Open();
 int temp = cmd.ExecuteNonQuery();
 conn.Close();
 return temp;
}
public void InsertNewRecord(string empName, string empSalary)
{
 SqlCommand cmd = new SqlCommand("your insert query ", conn);
 conn.Open();
 int temp = cmd.ExecuteNonQuery();
 conn.Close();
 return temp;
}



ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: How to Create PDF from DataTable in ASP.NET 4.5.2 ?

clock November 17, 2014 05:58 by author Peter

With this article, i'm explaining you learn how to create PDF File from datatable with ASP.NET 4.5.2. I'm passing a DataTable during this function and code to convert this in pdf file. I'm working with iTextSharp you'll be able to download it from internet. It totally free. you will need to make an easy ASP.NET page and have data from database. Then pass it to ExportToPDF method. We are able to established PDF page margins, alter page orientation (portrait, landscape), custaomize headers and footers add page numbers and a lot of. Carry out a few R & D along with iTextSharp.

And here is the code that I use to create PDF file from DataTable:
public void ExportToPdf(DataTable myDataTable) 
   {     
     Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10); 
     try 
     { 
       PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream); 
       pdfDoc.Open(); 
       Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11)); 
       Paragraph p = new Paragraph(); 
       p.Alignment = Element.ALIGN_CENTER; 
       p.Add(c); 
       pdfDoc.Add(p); 
       string clientLogo = System.Web.HttpContext.Current.Session["CompanyName"].ToString(); 
       clientLogo = clientLogo.Replace(" ", ""); 
       string clogo = clientLogo + ".jpg"; 
       string imageFilePath = System.Web.HttpContext.Current.Server.MapPath("../ClientLogo/" + clogo + ""); 
       iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath); 
       //Resize image depend upon your need  
       jpg.ScaleToFit(80f, 60f); 
       //Give space before image  
       jpg.SpacingBefore = 0f; 
       //Give some space after the image  
       jpg.SpacingAfter = 1f; 
       jpg.Alignment = Element.HEADER; 
       pdfDoc.Add(jpg); 
       Font font8 = FontFactory.GetFont("ARIAL", 7); 
       DataTable dt = myDataTable; 
       if (dt != null) 
       { 
         //Craete instance of the pdf table and set the number of column in that table 
         PdfPTable PdfTable = new PdfPTable(dt.Columns.Count); 
         PdfPCell PdfPCell = null; 
         for (int rows = 0; rows < dt.Rows.Count; rows++) 
         { 
           for (int column = 0; column < dt.Columns.Count; column++)  
           { 
             PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8))); 
             PdfTable.AddCell(PdfPCell); 
           } 
         } 
         //PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table           
         pdfDoc.Add(PdfTable); // add pdf table to the document  
       } 
       pdfDoc.Close(); 
       Response.ContentType = "application/pdf"; 
       Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf"); 
       System.Web.HttpContext.Current.Response.Write(pdfDoc); 
       Response.Flush(); 
       Response.End(); 
       //HttpContext.Current.ApplicationInstance.CompleteRequest(); 
     } 
     catch (DocumentException de) 
     { 
       System.Web.HttpContext.Current.Response.Write(de.Message); 
     } 
     catch (IOException ioEx) 
     { 
       System.Web.HttpContext.Current.Response.Write(ioEx.Message); 
     } 
     catch (Exception ex) 
     { 
       System.Web.HttpContext.Current.Response.Write(ex.Message); 
     } 
   } 



ASP.NET 4.5.2 Hosting with Paris (France) Server - HostForLIFE.eu :: How to Resize Image With Maintain The Ratio in ASP.NET 4.5.2 ?

clock November 14, 2014 04:54 by author Peter

Now, I am going to tell you how to Re-size Image along with maintain the ration employing ASP.NET 4.5.2 and C# code. Sometimes we must store totally different size images to get a certain images as applied to e-commerce web page. for that we both re-size the image and save multiple images collectively small, medium along with a full size image. Other then When we've got issue relating to space having very fine performance server then we are able to use dynamically re-sizing of image merely save only huge image then when want to utilize re-size it in run time when you need.

For achieving this process I generate a code that response the re-size image. I utilize it for jpg and png images not for gif. Call the page in which code for image merging :
Image1.ImageUrl = "dynamicimage.aspx";

And this is the Code for image generation and merging (dynamicimage.aspx or dynamicimage.aspx.cs) using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
protected void Page_Load(object sender, EventArgs e)
{
  string testimage = Server.MapPath(@"images/hemant_image.jpg");
  getimage(testimage, 400, 400); 
  // can set imageurl, max-width and max-height using query string...
}
public void getimage(string ThumbnailPath, int maxwidth, int maxheight)
{
    System.Drawing.Image image = System.Drawing.Image.FromFile(ThumbnailPath);
    Size ThumbNailSize = setimagesize(maxwidth, maxheight, image.Width, image.Height);
    System.Drawing.Image ImgThnail = new Bitmap(ThumbNailSize.Width, ThumbNailSize.Height);
    System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(ImgThnail);  
    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphics.CompositingQuality = CompositingQuality.HighQuality;
    graphics.DrawImage(image, 0, 0, ThumbNailSize.Width, ThumbNailSize.Height);
    ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
    string sExt = System.IO.Path.GetExtension(ThumbnailPath);
    if (sExt.ToString() == ".png")  
  {
        Response.ContentType = "image/png";
        ImgThnail.Save(Response.OutputStream, image.RawFormat);
    }
    else
    {
        Response.ContentType = "image/jpeg";
        ImgThnail.Save(Response.OutputStream, info[1], encoderParameters);
    }
    image.Dispose();
}
// below code is my old one for calculating height and width with maintain image ratio.
public Size setimagesize(int maxwidth, int maxheight, int OriginalWidth, int OriginalHeight)
{
    Size NewSize = new Size();
    int sNewWidth = OriginalWidth;
    int sNewHeight = OriginalHeight;
    int tempheight = 0;
    int tempwidht = 0;
    if (OriginalWidth >= OriginalHeight)
    {
        if (OriginalWidth >= maxwidth)
        {
            sNewWidth = maxwidth;
            sNewHeight = OriginalHeight * maxwidth / OriginalWidth;
        }
        if (sNewHeight > maxheight)
        {
            tempheight = sNewHeight;
            sNewHeight = maxheight;
            sNewWidth = sNewWidth * maxheight / tempheight;
        }
    }
    else
    {
        if (OriginalHeight >= maxheight)
        {
            sNewHeight = maxheight;
            sNewWidth = OriginalWidth * maxheight / OriginalHeight;
        }
        if (sNewWidth > maxwidth)
        {
            tempwidht = sNewWidth;
            sNewWidth = maxwidth;
            sNewHeight = sNewHeight * maxwidth / tempwidht;
        }
    }
    NewSize = new Size(sNewWidth, sNewHeight);
    return NewSize;
}



HostForLIFE.eu Windows Hosting Proudly Launches New Data Center in Paris (France)

clock November 10, 2014 10:47 by author Peter

HostForLIFE.eu, a leading Windows web hosting provider with innovative technology solutions and a dedicated professional services team proudly announces New Data Center in Paris (France) for all costumers. HostForLIFE’s new data center in Paris will address strong demand from customers for excellent data center services in Europe, as data consumption and hosting services experience continued growth in the global IT markets.

The new facility will provide customers and our end users with HostForLIFE.eu services that meet in-country data residency requirements. It will also complement the existing HostForLIFE.eu. The Paris (France) data center will offer the full range of HostForLIFE.eu web hosting infrastructure services, including bare metal servers, virtual servers, storage and networking.

HostForLIFE.eu expansion into Paris gives us a stronger European market presence as well as added proximity and access to HostForLIFE.eu growing customer base in region. HostForLIFE.eu has been a leader in the dedicated Windows & ASP.NET Hosting industry for a number of years now and we are looking forward to bringing our level of service and reliability to the Windows market at an affordable price.

The new data center will allow customers to replicate or integrate data between Paris data centers with high transfer speeds and unmetered bandwidth (at no charge) between facilities. Paris itself, is a major center of business with a third of the world’s largest companies headquartered there, but it also boasts a large community of emerging technology startups, incubators, and entrepreneurs.

Our network is built from best-in-class networking infrastructure, hardware, and software with exceptional bandwidth and connectivity for the highest speed and reliability. Every upstream network port is multiple 10G and every rack is terminated with two 10G connections to the public Internet and two 10G connections to our private network. Every location is hardened against physical intrusion, and server room access is limited to certified employees.

All of HostForLIFE.eu controls (inside and outside the data center) are vetted by third-party auditors, and we provide detailed reports for our customers own security certifications. The most sensitive financial, healthcare, and government workloads require the unparalleled protection HostForLIFE.eu provides.

Paris data centres meet the highest levels of building security, including constant security by trained security staff 24x7, electronic access management, proximity access control systems and CCTV. HostForLIFE.eu is monitored 24/7 by 441 cameras onsite. All customers are offered a 24/7 support function and access to our IT equipment at any time 24/7 by 365 days a year.

For more information about new data center in Paris, please visit http://hostforlife.eu/Paris-Hosting-Data-Center

About HostForLIFE.eu
HostForLIFE.eu is an European Windows Hosting Provider which focuses on the Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in