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

Free ASP.NET 5 Hosting - HostForLIFE.eu :: Create MD5 encryptions in ASP.NET using C#

clock May 29, 2015 07:48 by author Peter

In the world of network encryption is one of the very important idea to secure your users' information from outside hackers. usually once user input any password related field  its getting encrypted and so put that encrypted password into database. And within the case of retrieving there are 2 process are there.  You will encrypt the imputing password and match it with the field in database otherwise you can decrypt the keep password and match it with the input. I thing first one is much better and less time consuming.

So, how to encrypt your inputted password field. The most common encryption technique is MD5. Here in this example I'll show you ways to encrypt a string into an encrypted password using MD5 in ASP.NET using C#. Create a new project and add a new WebForm to start your encrypted application. in the ASPX page add a new TextBox. Create a TextChange event and on the AutoPostBack property of the TextBox.

Write the following code, in the ASPX page:
<form id="form1" runat="server">
    <div>
        <asp:textbox autopostback="True" id="TextBox1" ontextchanged="TextBox1_TextChanged" runat="server"></asp:textbox>
        Encrypted password :
        <asp:label id="Label1" runat="server" text=""></asp:label>
    </div>
</form>

Write the following code In the C# page:
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;
using System;
namespace md5
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            Byte[] ePass;
            UTF8Encoding encoder = new UTF8Encoding();
            ePass = md5Hasher.ComputeHash(encoder.GetBytes(TextBox1.Text));
            Label1.Text = Convert.ToBase64String(ePass);
        }
    }
}

In the Label1 you'll see the encrypted password. simply place the ePass into the database to store as an encrypted password. Your encryption is over. I hope it works for you!

Free ASP.NET 5 Hosting
Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET 5 Hosting - HostForLIFE.eu :: How to Make an Instant Search of Grid View in ASP.NET using C# ?

clock May 25, 2015 07:48 by author Peter

Today I'll show you the way to make a search in GridView  in ASP.NET using C#. You'll do it normally getting a ASP command button and run a query to get the value in a GridView. It'll refresh the page every time. You'll stop this by adding an UpdatePanel but the time taking will be more or less same. however here I'll use quickseacrch.js to search within a GridView. To do this produce a new project and add a new web form in your Visual Studio. In the aspx file write the following code to proceed.

<form id="form1" runat="server">
<asp:gridview autogeneratecolumns="False" headerstyle-backcolor="#3AC0F2" headerstyle-forecolor="White" id="GridView1" ondatabound="OnDataBound" runat="server">
        <columns>            
            <asp:templatefield headertext="Name">
                <itemtemplate>
                    <asp:label id="Label1" runat="server" text="<%# Eval("Name") %>"></asp:label>
                </itemtemplate>
            </asp:templatefield>            
        </columns>  
    </asp:gridview>    
    <script type="text/javascript">
        $(function () {
            $('.search_textbox').each(function (i) {
                $(this).quicksearch("[id*=GridView1] tr:not(:has(th))", {
                    'testQuery': function (query, txt, row) {
                        return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;                   
}
                });
            });
        });
    </script>
    </form>


Now, in the head section add a script tag to do this js function:
<script type="text/javascript">
 $(function () {
  $('.search_textbox').each(function (i) {
   $(this).quicksearch("[id*=GridView1] tr:not(:has(th))", {
    'testQuery': function (query, txt, row) {
     return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
    }
   });
  });
 });
</script>


In the CS page write the following code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[1] {new DataColumn("Name", typeof(string))});
            dt.Rows.Add("Peter");
            dt.Rows.Add("Scott");
            dt.Rows.Add("Rebecca");
            dt.Rows.Add("Suzan");
            dt.Rows.Add("Tom");
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
     protected void OnDataBound(object sender, EventArgs e)
    {
        GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
        for (int i = 0; i < GridView1.Columns.Count; i++)
        {
            TableHeaderCell cell = new TableHeaderCell();
            TextBox txtSearch = new TextBox();
            txtSearch.Attributes["placeholder"] = GridView1.Columns[i].HeaderText;
            txtSearch.CssClass = "search_textbox";
            cell.Controls.Add(txtSearch);
            row.Controls.Add(cell);
        }
        GridView1.HeaderRow.Parent.Controls.AddAt(1, row);
    }


Finally, run the code. Hope it works!

Free ASP.NET 5 Hosting
Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET 5 Hosting - HostForLIFE.eu :: How to get all file names in a folder using C#/VB.NET in ASP.NET?

clock May 22, 2015 07:59 by author Peter

Today, I am going to tell you about ASP.NET How to get all file names in a folder using C#/VB.NET. Fisrt, create the new ASP.NET project and then write the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class GetAllFileNames : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = string.Empty;
        str = str + "<ul>";
        DirectoryInfo d = new DirectoryInfo(@"D:\TextFiles");//Assuming Test is your Folder
        FileInfo[] Files = d.GetFiles("*.*"); //Getting Text files
        foreach (FileInfo file in Files)
        {
            str = str+"<li>"  + file.Name;       
        }
        str = str + "</li></ul>";
        Response.Write(str);
    }
}

VB:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.IO
Partial Public Class GetAllFileNames
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        Dim str As String = String.Empty
        str = str & "<ul>"
        Dim d As New DirectoryInfo("D:\TextFiles")
        'Assuming Test is your Folder
        Dim Files As FileInfo() = d.GetFiles("*.*")
        'Getting Text files
        For Each file As FileInfo In Files
            str = str & "<li>" & file.Name
        Next
        str = str & "</li></ul>"
        Response.Write(str)
    End Sub
End Class

And here is the output from the above code:

 

Free ASP.NET 5 Hosting
Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET 5 Hosting - HostForLIFE.eu :: How to Display Images that Dynamically generated in ASP.NET

clock May 19, 2015 06:35 by author Rebecca

Sometimes you need to display an image that is not saved in a file. These could be dynamically generated or loaded from a file but were modified. To display them in an Image control you need to create another page that saves the image in its output stream.


As an example to demonstrate how to do this, I created a project with two aspx pages. The first page, default.aspx, is the one the user views and it contains the Image control that will display the dynamically generated image. The second one contains the code to generate the image, named imagegen.aspx. Delete all the HTML code in imagegen.aspx and leave the Page directive only. So the contents of imagegen.aspx should look like this:

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

The code below is in imagegen.aspx’s Page Load event. It creates an image with a white background and writes the current date and time on it. The Bitmap object’s Save method allows you to save the image to a file or a stream. And saving the image to Response.OutputStream sends it to the outgoing HTTP body. To get the image displayed in default.aspx just set the ImageURL property of the Image control to “imagegen.aspx”. Now everytime default.aspx is loaded a new image is generated with the loading date and time displayed in it.
  
protected void Page_Load(object sender, EventArgs e)
{
    Bitmap image = new Bitmap(200, 200);
    Graphics graphics = Graphics.FromImage(image);
    Font font = new Font("Arial", 12);
 
    graphics.FillRectangle(Brushes.White, 0, 0, 200, 200);
    graphics.DrawString(DateTime.Now.ToString(), font, Brushes.DarkBlue, 5, 5);
 
    image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
   
    graphics.Dispose(); 
    image.Dispose();
 
    Response.Flush();
}

Free ASP.NET 5 Hosting
Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET 5 Hosting - HostForLIFE.eu :: How to Move DataGrid Row Up/Down with Sorting?

clock May 18, 2015 07:11 by author Peter

In this short article, let me show you how to create two buttons "one for UP" and "one for DOWN" in the datagrid then you can easily move row up and down by using the following code.

Add code in Default.aspx page:
<asp:DataGrid ID="dgrdAdmin" runat="server" OnItemCommand="dgrdAdmin_ItemCommand"     AllowSorting="true">
     <Columns>
        <asp:BoundColumn DataField="id" Visible="false"></asp:BoundColumn>
           <asp:TemplateColumn>
              <ItemTemplate>
                 <asp:ImageButton ID="imgbtnUP" runat="server" CommandName="Up" />
                  <asp:ImageButton ID="imgbtnDown" runat="server" CommandName="Down" />
             </ItemTemplate>
          </asp:TemplateColumn>
      </Columns>
  </asp:DataGrid>

Now, write the following code:
 private int GetMaxSortOrder()
   {
      int max = 0;
      DataTable dt = new DataTable();
      SqlConnection conn = new SqlConnection("Your_Connection_String");
      SqlCommand cmd = new SqlCommand("SELECT MAX(SORTORDER) FROM Your_Admin_Table");
      conn.Open();
      SqlDataAdapter sqad = new SqlDataAdapter(cmd);
      sqad.Fill(dt);
      if (dt.Rows.Count > 0)
      {
          if (dt.Rows[0][0].ToString() != "")
          max = Convert.ToInt32(dt.Rows[0][0]);
      }
    return max;
    }
protected void dgrdAdmin_ItemCommand(object sender, DataGridCommandEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
     {
       if (e.CommandName.Equals("Up"))
       {
          int SortOrder = 0;
          SqlConnection conn = new SqlConnection("Your_Connection_String");
           if (e.Item.Cells[10].Text != "")
            {
              SortOrder = Convert.ToInt32(e.Item.Cells[10].Text);
              if (SortOrder == 0)
                {
                  DataTable dt = new DataTable();
                  SqlCommand cmd = new SqlCommand("SELECT id FROM Your_ADMIN_Table");
                  conn.Open();
                  SqlDataAdapter sqad = new SqlDataAdapter(cmd);
                  sqad.Fill(dt);
                  if (dt.Rows.Count > 0)
                  {
                    int count = 0;
                    foreach (DataRow dr in dt.Rows)
                    {                   
                    count++;
                     SqlCommand cmdUp = new SqlCommand("UPDATE Your_ADMIN_Table SET
                                        SortOrder='" + count + "' WHERE id='" + dr["id"].ToString() + "'");
                     cmdUp.ExecuteNonQuery();
                    }
                  }
                   // bind your grid
                   return;
               }
            }
           if (SortOrder == GetMaxSortOrder() || SortOrder > GetMaxSortOrder())
           return;
           SqlCommand cmd2 = new SqlCommand("UPDATE Your_ADMIN_Table SET
              SortOrder='" + SortOrder + "' WHERE SortOrder='" + (SortOrder + 1) + "'");
           cmd2.ExecuteNonQuery();
           SqlCommand cmd3 = new SqlCommand("UPDATE Your_ADMIN_Table SET
           SortOrder='" + (SortOrder + 1) + "' WHERE id='" + e.Item.Cells[1].Text + "' AND                                           
           SortOrder='" + SortOrder + "'");
           cmd3.ExecuteNonQuery();
           dgrdAdmin.DataSource = // Bind data in datagrid
           dgrdAdmin.DataBind();
         }
        if (e.CommandName.Equals("Down"))
        {
          SqlConnection conn = new SqlConnection("Your_Connection_String");
          int SortOrder = 0;
          if (e.Item.Cells[10].Text != "")
           {
             SortOrder = Convert.ToInt32(e.Item.Cells[10].Text);
             if (SortOrder == 0)
             {
               DataTable dt = new DataTable();
               SqlCommand cmd = new SqlCommand("SELECT id FROM Your_ADMIN_Table");
               conn.Open();
               SqlDataAdapter sqad = new SqlDataAdapter(cmd);
               if (dt.Rows.Count > 0)
               {
                 int count = 0;
                 foreach (DataRow dr in dt.Rows)
                 {
                   count++;
                   SqlCommand cmdDown = new SqlCommand("UPDATE Your_ADMIN_Table SET
                   SortOrder='" + count + "' WHERE id='" + dr["id"].ToString() + "'");
                   cmdDown.ExecuteNonQuery();
                 }
               }
              // bind your grid
                 return;
           }
       }
       if (SortOrder == 0)
        return;
       SqlCommand cmd1 = new SqlCommand("UPDATE Your_ADMIN_Table SET SortOrder=" + SortOrder + "' WHERE SortOrder='" + (SortOrder - 1) + "'");
       cmd1.ExecuteNonQuery();
       SqlCommand cmd2 = new SqlCommand("UPDATE Your_ADMIN_Table SET SortOrder='" + (SortOrder - 1) + "' WHERE id='" + e.Item.Cells[1].Text + "'
       AND SortOrder='" + SortOrder + "'");
       cmd2.ExecuteNonQuery();
       dgrdAdmin.DataSource = // Bind data in datagrid
       dgrdAdmin.DataBind();
       }
    }
}

Now you can easily move your datagrid row up and down with sorting.

Free ASP.NET 5 Hosting

Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET 5 Hosting - HostForLIFE.eu :: How to Reduce ASP.NET Page Size

clock May 12, 2015 07:01 by author Rebecca

Although users today have faster Internet connection, light web pages and fast load are still popular. If your ASP.NET page is heavy, it will take some time to load and you risk that user will close browser window or go to some faster web site. Also, fast page load is respected by Google and other search engines. Pages that load fast are ranked higher in search results and because of that get more visits. With reduced page size, bandwidth costs area also reduced. So, if small page size is so important, let's take a look on how is possible to reduce size of page without removing useful content.

1. Optimize Images for Web

Let start with basic things. If you are placed image from digital camera and just set width and height of IMG tag to smaller values that action will not resize an image (although will appear smaller on page). So, use Photoshop, Paint Shop Pro or Resize image automatically with .Net code. Photoshop has feature named "Save For Web & Devices..." which helps to optimize images, especially if you are not professional graphic designer.

Another important issue with images on web page is using of backgrund image in page layout. Try to avoid large image in background, use few smaller images or if possible one small image with background-repeat parameter. Example code that repeat small background image inside a TABLE could look like this:

<table style="background-image:url('Sunflowers.jpg');background-repeat:repeat;"  width="500" height="500">
<tr>
 <td>here is a table content</td>
</tr>
</table>

Notice that using a lot of small images will increase number of http requests to server that can increase time to load. The solution is using of CSS sprites. Place all background images on one image, then use CSS background-image and background-position property to display only wanted image part.

2. Disable, Minimize or Move ViewState

ViewState can grow large if you have many controls on page, especially if data controls like GridView used. The best option is to turn off ViewState or at least not use it for every control. To disable ViewState use EnableViewState="false" in Page directive, with code like this:

<%@ Page EnableViewState="false" Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

If you must use ViewState for some controls, then turn it off for other controls. Every control has a property named EnableViewState. Set this property to false for every control that not require ViewState. On this way ViewState hidden field will be smaller and page will load faster.

Another option is to move ViewState from page to Session object. This approach will reduce page size, but ViewState will take space in memory on server. If you have a lot of concurrent visitors this could be performance problem. Take care that visitor can look at the two or more pages at the same time, so ViewState of every page must be stored to separated Session object. You can try this method with code like this:

[ C# ]
protected override object LoadPageStateFromPersistenceMedium()
{
   // Returns page's ViewState from Session object
   return Session["ViewState-" + Request.Url.AbsolutePath];
}
 

protected override void SavePageStateToPersistenceMedium(object state)
{
   // Saves page's ViewState to Session object
   Session["ViewState-" + Request.Url.AbsolutePath] = state;
   // Removes content of ViewState on page
   RegisterHiddenField("__VIEWSTATE", "");
}

[ VB.NET ]

Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
 ' Returns page's ViewState from Session object
 Return Session("ViewState-" & Request.Url.AbsolutePath)
End Function
 
Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal state As Object)
 ' Saves page's ViewState to Session object
 Session("ViewState-" & Request.Url.AbsolutePath) = state
 ' Removes content of ViewState on page
 RegisterHiddenField("__VIEWSTATE", "")
End Sub

If web site has performance problems because of extensive use of Session object, notice that with LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium functions you can load and save ViewState from any other source, like file system, database etc. Strategy like this will for sure reduce page size, but in the same time add additional processing to load and save ViewState from other medium so it should be used only when we can't disable ViewState or reduce it enough.

3. Remove Inline Styles to external .css File

If inline styles are moved from HTML to external .css file, pages will have smaller size. CSS file is loaded only first time when user visits web site. After that, it is stored in browser's cache and used to format every next page. Not only pages will load faster but you'll also have less maintenance work if styles are changed.

To link CSS file to HTML page use code like this in HEAD section:

<head runat="server">
<title>Page with external CSS file</title>
<link rel="stylesheet" type="text/css" href="Styles.css" />
</head>

4. Remove any inline JavaScript to external .js File

Like CSS styling, you can move any inline JavaScript to external .js file. On this way, JavaScript will be loaded only first time, and then cached by web browser for future use. To relate .js file to web page, add one more line in HEAD section:

<head runat="server">
<title>Page with external CSS and JS files</title>
<link rel="stylesheet" type="text/css" href="Styles.css" />
<script language="JavaScript" src="scripts/common.js"></script>
</head>

5. Use Light Page Layout

A lot of nested tables will probably make your page unnecessary large. Try use DIV tags instead of tables where possible and define DIVs appearance with CSS. On this way, HTML code will be smaller. Although many designers recommend using of DIV tags only and without any table used for layout, I am not DIV purist. On my opinion, tables are still good for columns even yooyut use table for that part. I created twelve hybrid CSS/Table/DIV Page Layouts Examples. This page layout examples use both TABLE and DIVs to get light but still robust page layout.

6. Use HTTP Compression

HTTP compression can be used to reduce number of bytes sent from server to client. If web browser supports this feature, IIS will send data compressed using GZIP.

Free ASP.NET 5 Hosting
Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET 5 Hosting - HostForLIFE.eu :: How to Open URL in New Window with Custom Height Width Example using AngularJS and ASP.NET?

clock May 11, 2015 08:12 by author Peter

In this tutorial, I will show you How to Open URL in New Window with Custom Height Width Example using AngularJS and ASP.NET 5. I using “$window.open” we will new popup browser window with custom size in AngularJS. Now, I will be able to explain how to open new browser window with custom height and width on button click using AngularJS.

Write the following code:
// Open New Child / Browser Window
$scope.openChildWindow = function () {
var left = screen.width / 2 - 200, top = screen.height / 2 – 250
$window.open('http://www.hostforlife.eu', '', "top=" + top + ",left=" + left + ",width=400,height=500")
}

This is the complete code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title> How to Open URL in New Window with Custom Height Width Example using AngularJS and ASP.NET?</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('sampleapp', [])
myApp.controller("expressionController", function ($scope,$window) {
// Open New Child / Browser Window
$scope.openChildWindow = function () {
var left = screen.width / 2 - 200, top = screen.height / 2 – 250
$window.open('http://www.hostforlife.eu', '', "top=" + top + ",left=" + left +
,width=400,height=500")
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div data-ng-app="sampleapp" data-ng-controller="expressionController">
<input type="button" value="Open Popup Window" ng-click="openChildWindow()"/> <br /><br />
</div>
</form>
</body>
</html>

 

Free ASP.NET 5 Hosting

Try our Free ASP.NET 5 Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET 5 Hosting - HostForLIFE.eu :: Create a Responsive Page Using BootStrap in ASP.NET

clock May 8, 2015 07:57 by author Peter

In this article, let me show you how to create a responsive page using BootStrap in ASP.NET. First of all, you must download BootStrap from bootstrap.com. Next step, Open your Visual Studio, add your downloaded file into your project then create the index.aspx page and call your necessary files with in the head tag from that downloaded folder.

Then, write the  following code:

<head runat="server">     
    <title></title>     
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
    <script src="js/bootstrap.min.js"></script>   
    <link href="css/bootstrap.min.css" rel="stylesheet" />   
</head>  

Consider <div class="row"></div> as a new line. Whatever you want to design in a row you should design with in a <div class="row">Your design</div>. And then <div class="col-lg-12"></div>
<div class="row"> 
    <div class="col-lg-12"> 
        Your Design

       Create a Responsive Page Using BootStrap in ASP.NET
    </div> 
</div>  

Full Code Sample
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="Responsive_Website.index" %> 
    <!DOCTYPE html> 
    <html 
        xmlns="http://www.w3.org/1999/xhtml"> 
        <head runat="server"> 
            <title></title> 
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
            <script src="js/bootstrap.min.js"></script> 
            <link href="css/bootstrap.min.css" rel="stylesheet" /> 
        </head> 
        <body> 
            <form id="form1" runat="server"> 
                <div class="container"> 
                    <div class="row"> 
                        <div class="col-lg-3"></div> 
                        <div class="col-lg-6"> 
                            <form class="form-signin"> 
                                <h2 class="form-signin-heading">Please sign in</h2> 
                                <label for="inputEmail" class="sr-only">Email address</label> 
                                <input type="email" id="inputEmail" class="form-control" placeholder="Email
ddress" required autofocus> 
                                    <label for="inputPassword" class="sr-only">Password</label> 
                                    <input type="password" id="inputPassword" class="form-control"
laceholder="Password" required> 
                                        <div class="checkbox"> 
                                            <label> 
                                                <input type="checkbox" value="remember-me">   
                                                    Remember me  
                                            </label> 
                                        </div> 
                                    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> 
                            </form> 
                        </div> 
                        <div class="col-lg-3"></div> 
                    </div> 
                </div> 
            </form> 
        </body> 
    </html>  

And here is the output from the above code:

Output (on small screens)

Free ASP.NET Hosting

Try our Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET Hosting - HostForLIFE.eu :: How to Schedule Task in ASP.NET

clock May 5, 2015 05:59 by author Rebecca

Mostly, ASP.NET doesn't provide some straightforward way to schedule tasks. Also, only what HTTP protocol can do is to return some output as a response after receives web request. Fortunately, there are numerous solutions to solve this problem. In this tutorial, I will show three ways to simulate scheduled tasks using pure ASP.NET methods (using of timer, cache expiration and threads).

In this tutorial, We're gonna use C# for running the script

Scheduled Tasks using Timer

Very simple solution to perform scheduled tasks is by using timer. Again, we'll use Global.asax and Application_Start procedure. In Application_Start we'll create a Timer and use Elapsed event to execute task in regular time intervals. To make it so, write this code in Global.asax file:

<%@ Application Language="C#" %>
  
   <script runat="server">
  
   // Code that runs on application startup
   void Application_Start(object sender, EventArgs e)
   {
   // Dynamically create new timer
   System.Timers.Timer timScheduledTask = new System.Timers.Timer();
  
   // Timer interval is set in miliseconds,
   // In this case, we'll run a task every minute
   timScheduledTask.Interval = 60 * 1000;
  
   timScheduledTask.Enabled = true;
  
   // Add handler for Elapsed event
   timScheduledTask.Elapsed +=
   new System.Timers.ElapsedEventHandler(timScheduledTask_Elapsed);
   }
  
   void timScheduledTask_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
   {
   // Execute some task
   FirstTask();
   }
  
   void FirstTask()
   {
   // Here is the code we need to execute periodically
  
   }
   </script>

Scheduled Tasks using Cache Expiration as a Trigger

ASP.NET Cache expiration is one more method you can use to create scheduled tasks. In this method, it is not important what you put in the cache. In this example, I added short string "1", but could be anything. Useful for scheduled tasks is the fact that cache expires after specified time interval and then executes selected function (scheduled task).

Here is example of Global.asax file that uses cache expiration to schedule tasks in ASP.NET application. First, Application_Start method calls ScheduleTask procedure that uses cache expiration to schedule when task will be executed. In this example, cache willl expire after one hour. Then, after cache expired, SetTimer() is called. SetTimer function calls DoTask() method which represents code of scheduled task, and also calls again ScheduleTask() function to plan next task execution.

<%@ Application Language="C#" %>
  
   <script runat="server">
   void Application_Start(object sender, EventArgs e)
   {
   // Schedule task for the first time
   ScheduleTask();
   }
  
   static void ScheduleTask()
   {
   HttpRuntime.Cache.Add(
   // String that represents the name of the cache item,
   // could be any string
   "ScheduledTask",
   // Something to store in the cache
   "1",
   // No cache dependencies
   null,
   // Will not use absolute cache expiration
   Cache.NoAbsoluteExpiration,
   // Cache will expire after one hour
   // You can change this time interval according
   // to your requriements
   TimeSpan.FromHours(1),
   // Cache will not be removed before expired
   CacheItemPriority.NotRemovable,
   // SetTimer function will be called when cache expire
   new CacheItemRemovedCallback(SetTimer));
   }
  
   // This function si called when cache is expired
   static void SetTimer(string key, Object value, CacheItemRemovedReason reason)
   {
   // Call the task function
   DoTask();
   // Schedule new execution time
   ScheduleTask();
   }
  
   static void DoTask()
   {
   // Task code which is executed periodically
   // In this example, code will be executed every hour
   }
   </script>

Scheduled Tasks using Threading

Solution that uses threads is very simple. We'll use Application_Start procedure in Global.asax to initially start task. Then, in separate thread we'll call task again in regular time intervals. Code in Global.asax could look like this:

%@ Application Language="C#" %>
<%-- We need this namespace to work with threads --%>
<%@ Import Namespace="System.Threading" %>
  
   <script runat="server">
  
  
   void Application_Start(object sender, EventArgs e)
   {
   // On application start, create an start separate thread
   ThreadStart tsTask = new ThreadStart(TaskLoop);
   Thread MyTask = new Thread(tsTask);
   MyTask.Start();
  
   }
  
   static void TaskLoop()
   {
   // In this example, task will repeat in infinite loop
   // You can additional parameter if you want to have an option
   // to stop the task from some page
   while (true)
   {
   // Execute scheduled task
   ScheduledTask();
  
   // Wait for certain time interval
   System.Threading.Thread.Sleep(TimeSpan.FromHours(12));
   }
   }
  
   static void ScheduledTask()
   {
   // Task code which is executed periodically
  
   }
   </script>

Free ASP.NET Hosting
Try our Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET Hosting - HostForLIFE.eu :: Using the MathCap for ASP.NET 5

clock May 4, 2015 08:41 by author Peter

In this post, I will tell you about using the MathCap for ASP.NET 5. MathCap is a plugin for ASP.NET application and its a 100% effective and simple to use. The more you see on a profound look. Here i imparted is the base form of Mathcap 1.0.0. More highlight are going ahead a newer versions. And now you must add mathcapp dll reference.

Remove the namespace on the webpage using MathCapcha;
Now write the following code
var bitmapImage = new Capcha();
var properties = new MathCapchaProperties();

Now, it is time to customise the properties.

Now get the response and point to image control, using below code:
var imgur = bitmapImage.CreateThumbnail(properties);
img.Src = imgur.bmpImageSource;
Response.Write(imgur.answer);

And here is the output:

Free ASP.NET Hosting
Try our Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.

 



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 2012 Hosting, ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, ASP.NET MVC 5 Hosting and SQL 2014 Hosting.


Tag cloud

Sign in