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

ASP.NET 5 Hosting - HostForLIFE.eu :: How to Use Entity Framework 7 To Persist Movie Data To a Database?

clock April 4, 2016 19:50 by author Anthony

Today I will explain about how to use entity framework 7 to presist movie data to a database. But before you start, you must add Entity Framework 7 NuGet packages to your project. Also make sure that your project.json file includes the following two dependencies (you’ll get Intellisense while entering the names of the packages and their versions).

"EntityFramework.SqlServer": "7.0.0-beta2",
"EntityFramework.Commands": "7.0.0-beta2",

 

After you complete this step, the Entity Framework packages should appear under References.

Creating the Model and DbContext

Next, we need to create our Movie model class. This class represents the entity that we want to store in the database. Add the following Movie.cs class to your Models folder:

namespace MovieAngularJSApp.Models
{
    public class Movie
    {
        public int Id { get; set; }
 
        public string Title { get; set; }
 
        public string Director { get; set; }
    }
}

We also need to create an Entity Framework DbContext class. We create this class when using Entity Framework 7 in exactly the same way as we created this class for previous versions of the Entity Framework.

using Microsoft.Data.Entity;
namespace MovieAngularJSApp.Models
{
    public class MoviesAppContext:DbContext
    {
 
        public DbSet<Movie> Movies { get; set; }
 
    }
}

Registering the Entity Framework Services
Now that we have our DbContext class, we need to register the DbContext with our application services. Modify your Startup.cs file so it contains the code for registering the Entity Framework in the code below:

using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Data.Entity;
using MovieAngularJSApp.Models;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
namespace MovieAngularJSApp
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            // Setup configuration sources.
            Configuration = new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();
        }
         public IConfiguration Configuration { get; set; }
         public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
 
            // Register Entity Framework
            services.AddEntityFramework(Configuration)
                .AddSqlServer()
                .AddDbContext<MoviesAppContext>();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
 
    }
}

The database connection string is loaded up from the Config.json file (notice the constructor in the Startup.cs file). Here is what the Config.json file looks like:

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=MoviesDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    },
    "EntityFramework": {
        "MoviesAppContext": {
            "ConnectionStringKey": "Data:DefaultConnection:ConnectionString"
        }
    }
}

Updating the MoviesController

Because we registered our MoviesAppContext class as a service, we can take advantage of the built-in ASP.NET 5 Dependency Injection framework to use the MoviesAppContext in our MoviesController. Notice that the MoviesAppContext class is added to the MoviesController using constructor dependency injection in the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;
namespace MovieAngularJSApp.API.Controllers
{
    [Route("api/[controller]")]
    public class MoviesController : Controller
    {
        private readonly MoviesAppContext _dbContext;
 
        public MoviesController(MoviesAppContext dbContext)
        {
            _dbContext = dbContext;
        }
 
        [HttpGet]
        public IEnumerable<Movie> Get()
        {
            return _dbContext.Movies;
        }
        [HttpGet("{id:int}")]
        public IActionResult Get(int id)
        {
            var movie = _dbContext.Movies.FirstOrDefault(m => m.Id == id);
            if (movie == null) {
                return new HttpNotFoundResult();
            } else {
                return new ObjectResult(movie);
            }
        }
        [HttpPost]
        public IActionResult Post([FromBody]Movie movie)
        {
            if (movie.Id == 0)
            {
                _dbContext.Movies.Add(movie);
                _dbContext.SaveChanges();
                return new ObjectResult(movie);
            }
            else
            {
                var original = _dbContext.Movies.FirstOrDefault(m => m.Id == movie.Id);
                original.Title = movie.Title;
                original.Director = movie.Director;
                _dbContext.SaveChanges();
                return new ObjectResult(original);
            }
        }
        [HttpDelete("{id:int}")]
        public IActionResult Delete(int id)
        {
            var movie = _dbContext.Movies.FirstOrDefault(m => m.Id == id);
            _dbContext.Movies.Remove(movie);
            _dbContext.SaveChanges();
            return new HttpStatusCodeResult(200);
        }
 
 
    }
}

Performing Database Migrations

After we complete all of the steps above, our application still won’t work. If we run the Movies app then we will get an error message about not being able to open the MoviesDatabase.

The Entity Framework 7 does not support database initializers. Instead, you are encouraged to use Database Migrations.There are two ways to use Migrations with ASP.NET 5: from a Command Prompt or from the NuGet Package Manager Console. I used the Command Prompt approach and I executed the following two commands from the same directory that contains my project.json file:

k ef migration add initial
k ef migration apply

KPrompt

After you execute the two ef commands above, a new database named MoviesDatabase will be created. You can see the new database by opening up the Visual Studio SQL Server Object Explorer:

SQLExplorer

Executing the ef commands above will also add a new Migrations folder to your project.

Migrations

You now should be able to run the Movies app successfully.

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How to Create a Database With Data Source Control in ASP.NET

clock March 29, 2016 21:10 by author Anthony

In this post we are going to talk about techniques for displaying data contained in the SQL Server database with ASP.NET. There are at least three ways commonly used to perform the data binding to server conrol in ASP.NET 4.5

Here are three ways:

  • Data Source Control (Declarative)
  • Code by Hand
  • Model Binding

but in this time I will explain how to create a database with the Data Source Control in ASP.NET 4.5


Web Config

Before going into the main discussion helps me informed beforehand that the connection string that is used to communicate with the database in ASP.NET contained in the configuration file "web.config". Here are the contents

file: Web.config


<?xml version="1.0"?>
<configuration>

<connectionStrings>
<add name="learn_webConnectionString" connectionString="Data Source=SOFT-ENGINEER;Initial Catalog=learning_web;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>


Database Design

The database used in this post only use one of the table is very simple with the name "Category"

Data Source Control

Data Source Control in ASP.NET 4.5 used as a link between the database with controls for displaying data. Using this approach means that we do is get the data in a declarative rather than programmatic. To be more explicit, the following is a sample code

file: default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TryingWebForm.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Data Source Control</title>

</head>
<body>

<form id="form1" runat="server">

<div>

<p>The Declarative Way</p>

<asp:SqlDataSource ID="sdsCategory" runat="server" ConnectionString="<%$ ConnectionStrings:trying_webConnectionString %>"

SelectCommand="SELECT [id], [name_category] FROM [Category]"/>

<asp:GridView ID="gvCategoryDeclarative" runat="server" DataSourceID="sdsCategory" />

</div>

</form>

</body>

</html>

As seen in the above code, control "SqlDataSource" requires a connection string and a query command to be executed. In magic this control will connect to the database and execute commands query and the result was thrown into "GridView" by filling property "DataSourceID" with the Id of control SqlDataSource concerned. The image below is the result

 

HostForLIFE.eu ASP.NET 4.5 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



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. 



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



ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: How to Display Local Current Time use JavaScript in ASP.NET

clock November 3, 2014 10:38 by author Peter

In this tutorial, I’ll explain How to Display Local Current Time using JavaScript in ASP.NET 4.5.2 without page refresh in your website. We can show a clock which is able to be showing the local time of the client’s laptop by using JavaScript.

Show/Display local computer Time use JavaScript
Following is the JavaScript function to indicate current time on webpage like clock:

<script type="text/javascript">
function DisplayCurrentTime() {
var dt = new Date();
var refresh = 1000; //Refresh rate 1000 milli sec means 1 sec
var cDate = (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
document.getElementById('cTime').innerHTML = cDate + " – " + dt.toLocaleTimeString();
window.setTimeout('DisplayCurrentTime()', refresh);
}
</script>

Here is the complete code for your .aspx site:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Webblogsforyou.com | Show/Display Local Computer's Current time in webpage using
JavaScript </title>
<script type="text/javascript">
function DisplayCurrentTime() {
var dt = new Date();
var refresh = 1000; //Refresh rate 1000 milli sec means 1 sec
var cDate = (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
document.getElementById('cTime').innerHTML = cDate + " – " + dt.toLocaleTimeString();
window.setTimeout('DisplayCurrentTime()', refresh);
}
</script>
</head>
<body onload="DisplayCurrentTime();">
<form id="form1" runat="server">
<h4>
Show/Display Local Computer's Current time in webpage using JavaScript</h4>
<div>
<asp:Label ID="cTime" runat="server" ClientIDMode="Static" BackColor="#ffff00"
Font-Bold="true" />
</div>
</form>
</body>
</html>

As you'll be able to see from on top of sample code, I called DisplayCurrentTime() method on onload event of body tag that loads this local system time, set the interval for each one seconds and refresh current time without page refresh to show on the webpage.



ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: Disabling the Tooltip Property in ASP.NET

clock October 27, 2014 09:33 by author Peter

A tooltip is a little pop-up window that seems when a user pauses the mouse pointer over a part, like over a Button. In this tutorial, I will show you how to disable the Tooltip in ASP.NET 4.5.2. Take a glance at the code below:

JavaScript
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function DisableToolTip() {
            // Get the object
            var obj = document.getElementById('LnkBtn');
            // set the tool tip as empty
            obj.title = "";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:LinkButton runat="server" Text="Simple Link Button" ToolTip="Simple Button with Tool Tip" ID="LnkBtn" ClientIDMode="Static" ></asp:LinkButton>
   <a href="#" id="lnkDisable" onclick="DisableToolTip();">Disable Tool Tip</a>
    </form>
</body>
</html>

JQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">    
<title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#lnkDisable").click(function () { $('#LnkBtn').attr({'title':''}); });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:LinkButton runat="server" Text="Simple Link Button" ToolTip="Simple Button with Tool Tip" ID="LnkBtn" ClientIDMode="Static" ></asp:LinkButton>
    <a href="#" id="lnkDisable">Disable Tool Tip</a>
    </form>
</body>
</html>



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How to use jQuery Ajax in ASP.NET

clock October 24, 2014 06:42 by author Peter

Today, I want to show you How to use jQuery Ajax in ASP.NET 4.5. jQuery permits you to call server-side ASP.NET methods from the client side with none PostBack. truly it's an Ajax call to the server however it permits us to decision call or function defined server-side. The code snippet below describes the syntax of the call.

$.ajax({
        type: "POST",
        url: "CS.aspx/MethodName",
        data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        }
    }); 
HTML Markup
<div>
    Your Name :
    <asp:textbox id="txtUserName" runat="server"></asp:textbox>
    <input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
</div>

As you can see in the preceding I have added a TextBox when the user enters his name and a TML button that calls a JavaScript method to get the Current Time.
Methods  used on Client Side
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function ShowCurrentTime() {
        $.ajax({
            type: "POST",
            url: "CS.aspx/GetCurrentTime",
            data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }
    function OnSuccess(response) {
        alert(response.d);
    }
</script>

That ShowCurrentTime method above makes an AJAX call to the server. That method will executes the GetCurrentTime and accepts the username then returns a string value.
This is the Server-Side Methods
C#
  [System.Web.Services.WebMethod]
    public static string GetCurrentTime(string name)
    {
        return "Hello " + name + Environment.NewLine + "The Current Time is: "
       + DateTime.Now.ToString();   
  }

VB.Net
<System.Web.Services.WebMethod()> _
ublic Shared Function GetCurrentTime(ByVal name As String) As String
   Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _           
DateTime.Now.ToString()
End Function


The preceding method merely returns a acknowledgment message to the user along side the current server time. a vital factor to notice is that the method is declared as static (C#) or Shared (VB.Net) and also it's declared as a web method since unless you are doing this you will not be ready to decision the methods.



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