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 - 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.



ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: Filetype Validation When Upload a File on ASP.NET

clock October 20, 2014 06:29 by author Peter

ASP.NET 4.5.2’s file upload facility offers a quick, easy method for allowing users to upload content to your server. In many cases however the upload type must be restricted. For example, perhaps you are allowing users to upload a profile image. You certainly don’t want them to be capable of uploading an executable (.exe) file.

The simple solution is to attach a RegularExpressionValidator to the file upload control.  Below is an example of a RegularExpressionValidator restricting the accepted filetypes of a FileUpload control to .gif, .jpg, .jpeg or .png
<asp:FileUpload ID="uplImage" runat="server" />
<asp:RegularExpressionValidator ID="revImage" ControlToValidate="uplImage" ValidationExpression="^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$" Text=" ! Invalid image type" runat="server" />


Here is the regular expression.
^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$
   
Unfortunately we cannot merely ignore case in the expression. The RegularExpressionValidator doesn't have an option to ignore case and the ASP.NET Regex Engine’s ignore case construct isn't supported on the client side Javascript Regex Engine. However, the expression on top of can match all variations of upper/lowercase characters like .gif,  .Gif and .GIF

Don’t forget to see in your postback handler that the page is valid! If you are doing forget and therefore the regular expression match fails, your code can still execute.
protected void btnUpload_Click(object sender, EventArgs e)
{
       if (IsValid)
        {
                // Process your data
        }
}



ASP.NET 4.5.2 Hosting UK - HostForLIFE.eu :: Get rid of Undesirable Properties and Events from UserControl

clock October 17, 2014 06:49 by author Peter

Have you ever created a UserControl and needed to get rid of all those properties that don't seem to be applicable on ASP.NET  4.5.2 Hosting UK? And what concerning the events? looking and predominate the properties with the BrowsableAttribute set to false is awkward, particularly since a number of these properties area unit virtual, whereas others are not (need to be declared as 'new'). this method removes the unwanted properties and events by merely adding their names to an inventory.

I am presently writing an impact that performs image transitions, and am designing a separate article for that. when overloading variety of properties from the base class, and adding the [Browsable(false)] attribute to them, I started thinking there should be the way to try and do this the base the code itself. I used this method to get rid of unwanted properties and events from that control, and that i felt that the technique used merited its own article.

The VS designer and editor uses the TypeDescriptor of your object to get an inventory of its members (methods, properties and events) that ar offered. By implementing the ICustomTypeDescriptor on your class, you get to settle on that of those are literally available to the host of the object. This makes it potential to filter any of the member you do not wish employed by the consumer of the control.

public partial class ucImageShow : UserControl , ICustomTypeDescriptor {
    ...    
}
}

Most of the implentation uses the static ways of the TypeDescriptor object to come all the data from the framework. For the required ways, we have a tendency to simply acquire that info, and separate out no matter we do not need. Below is my implementation for the image transitioning control.

public AttributeCollection GetAttributes() {
    return TypeDescriptor.GetAttributes(this, true);

}

public string GetClassName() {

    return TypeDescriptor.GetClassName(this, true);

}

public string GetComponentName() {

    return TypeDescriptor.GetComponentName(this, true);

}

public TypeConverter GetConverter() {

    return TypeDescriptor.GetConverter(this, true);

}

public EventDescriptor GetDefaultEvent() {

    return TypeDescriptor.GetDefaultEvent(this, true);

}

public PropertyDescriptor GetDefaultProperty() {

    return TypeDescriptor.GetDefaultProperty(this, true);

}

public object GetEditor(Type editorBaseType) {

    return TypeDescriptor.GetEditor(this, editorBaseType, true);

}

public EventDescriptorCollection GetEvents(Attribute[] attributes) {
    EventDescriptorCollection orig = TypeDescriptor.GetEvents(this, attributes, true);

    return FilterEvents(orig);

}

public EventDescriptorCollection GetEvents() {

    EventDescriptorCollection orig = TypeDescriptor.GetEvents(this, true);

    return FilterEvents(orig);

}

public PropertyDescriptorCollection GetProperties(Attribute[] attributes) {
    PropertyDescriptorCollection orig = TypeDescriptor.GetProperties(this, attributes, true);

    return FilterProperties(orig);

}

public PropertyDescriptorCollection GetProperties() {
    PropertyDescriptorCollection orig = TypeDescriptor.GetProperties(this, true);

    return FilterProperties(orig);

}

public object GetPropertyOwner(PropertyDescriptor pd) {

    return this;
}

Filtering the events and properties is solely a making a replacement collection, and adding all members of the present collection that don't meet the filter criteria. This new collection then replaces the first collection for the come back of the ICustomTypeDescriptor method.

private string[] _excludeBrowsableProperties = {
    "AutoScroll",

    "AutoScrollOffset",

   "AutoScrollMargin",

    "AutoScrollMinSize",

    "AutoSize",

    "AutoSizeMode",

    "AutoValidate",

    "CausesValidation",

    "ImeMode",

  "RightToLeft",

    "TabIndex",
   
"TabStop"

};

private string[] _excludeBrowsableEvents = {
    "AutoSizeChanged",
  
"AutoValidateChanged",
  
"BindingContextChanged",

   "CausesValidationChanged",

    "ChangeUICues",

    "ImeModeChanged",

    "RightToLeftChanged",

    "Scroll",

    "TabIndexChanged",

    "TabStopChanged",

    "Validated",

    "Validating"

};

private PropertyDescriptorCollection FilterProperties(PropertyDescriptorCollection originalCollection) {

    // Create an enumerator containing only the properties that are not in the provided list of property names

    // and fill an array with those selected properties

    IEnumerable<PropertyDescriptor> selectedProperties = originalCollection.OfType<PropertyDescriptor>().Where(p => !_excludeBrowsableProperties.Contains(p.Name));

    PropertyDescriptor[] descriptors = selectedProperties.ToArray();

    // Return a PropertyDescriptorCollection containing only the filtered descriptors

    PropertyDescriptorCollection newCollection = new PropertyDescriptorCollection(descriptors);

    return newCollection;

}

private EventDescriptorCollection FilterEvents(EventDescriptorCollection origEvents) {

    // Create an enumerator containing only the events that are not in the provided list of event names

    // and fill an array with those selected events

    IEnumerable<EventDescriptor> selectedEvents = origEvents.OfType<EventDescriptor>().Where(e => !_excludeBrowsableEvents.Contains(e.Name));

    EventDescriptor[] descriptors = selectedEvents.ToArray();

    // Return an EventDescriptorCollection containing only the filtered descriptors

    EventDescriptorCollection newCollection = new EventDescriptorCollection(descriptors);

    return newCollection;

}

As you can see on the example above, filters the properties and events supported their name. However, it might not take a lot of effort to filter them on the other criteria, for example the existance and/or worth of an attribute, or the property kind. This technique not solely removes access to the properties from the VS designer, however additionally from the editor and compiler. this implies that it'll not turn out any designer generated code for these properties.

The draw back of this is often that if the control is placed on a form, then a property is excluded that the designer has already generated code for, then the complete form can become invalid. to repair that, you would like to go into the form.designer.cs module and take away any references to the offending property. I discovered this the laborious method by excluding the TabIndex property.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in