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

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.



Classic ASP Hosting Germany - HostForLIFE.eu :: How to Use AspJpeg in Classic ASP Hosting?

clock November 7, 2014 07:11 by author Peter

AspJpeg may be a server part which will facilitate your Classic ASP or ASP.NET applications with all their image-management desires. With AspJpeg, you'll be able to produce high-quality thumbnails, logo-stamp pictures, extract metadata information from pictures, crop, enhance, rotate, convert, more a lot of. Now, I am going to show you how to Create a thumbnail image sample with ASPJpeg in Classic ASP:
<%
' Create instance of AspJpeg
Set Jpeg = Server.CreateObject("Persits.Jpeg")

' Open source image
Jpeg.Open "c:\yourabsolutepath\yourimage.jpg"

' New width
L = 100

' Resize, preserve aspect ratio
Jpeg.Width = L
Jpeg.Height = Jpeg.OriginalHeight * L / Jpeg.OriginalWidth

' create thumbnail and save it to disk
Jpeg.Save "c:\yourabsolutepath\yourthumbnail.jpg"

%>

And now, we are goint to Resize with ASPJpeg. The following script will open a JPEG image on the drive, resizes it and saves the resultant thumbnail back to disk.
<%
' Create an instance of AspJpeg
Set Jpeg = Server.CreateObject("Persits.Jpeg")

' Compute path to source image
Path = Server.MapPath("images") & "\test.jpg"

' Open source image
Jpeg.Open Path

' Decrease image size by 50%
Jpeg.Width = Jpeg.OriginalWidth / 2
Jpeg.Height = Jpeg.OriginalHeight / 2

' Optional: apply sharpening
Jpeg.Sharpen 1, 150

' Create thumbnail and save it to disk
Jpeg.Save Server.MapPath("images") & "\test_small.jpg"
%>

Send your Thumbnail Directly to Browser
AspJpeg can send your thumbnail directly to the client browser rather than save it to disk. An image resizing script can be invoked via the SRC attribute of an <IMG> tag as below:
<IMG SRC="resize.asp?path=c:\dir\myimage.jpg&width=100">


Code for resize.asp as following:
<%
' IMPORTANT: This script must not contain any HTML tags
' Create an instance of AspJpeg object
Set jpeg = Server.CreateObject("Persits.Jpeg")

jpeg.Open( Request("path") )

' Set new width
jpeg.Width = Request("width")

' Set new height, preserve original width/height ratio
jpeg.Height = _
  jpeg.OriginalHeight * jpeg.Width / jpeg.OriginalWidth

' Send thumbnail data to client browser
jpeg.SendBinary
%>


Best and Cheap Classic ASP Hosting With AspEncrypt Recommendation

HostforLIFE.eu was founded in 2008. It has been topping the list of almost all the web hosting review sites so far. Still have websites running on ASP 3.0 or Classic ASP? Don’t worry; we still support legacy technology like Classic ASP Hosting. You can also mix and match Classic ASP and ASP.NET code in one single web site. We will make sure that Classic ASP runs smoothly on our servers and that your website is safer, faster and better supported than anywhere else! Our best and cheap Classic ASP hosting plan is starting at $5.00/mo. HostforLIFE.eu is now providing free domain and double SQL server space for new clients to enjoy the company’s outstanding web hosting service.



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.



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