European ASP.NET 4.5 Hosting BLOG

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

ASP.NET Hosting UK - HostForLIFE.eu :: How to Use HTML5 to Detect Online Status of ASP.NET Website

clock June 18, 2015 05:54 by author Rebecca

Html 5 being the fore runner in the Web technology today has offered a lot of benefit and enhancements that will make life of a developer easier than even before. One of such enhancement belongs to the support of offline data storage inside browser cache.  The offline data storage enhances the UI Experience of the end user by providing rich api to read local storage. HTML 5 supports the features that was never present before and you needed to rely on those events only using 3rd party plugins. Say for instance, you have a requirement to continue using your web application even though there is no availability of Internet. In this tutorial, I will show you how easily you can detect whether the site is running in online or offline mode.

Step 1

First, let us add a code:

var addEvent = (function () {
  if (document.addEventListener) {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.addEventListener(type, fn, false);
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  } else {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  }
})();

You should already  know there are browser compatibility issues as most of the browser still lacks standardization. The document.addEventListener works in most of the browsers except IE. So to handle this, you have to bypass the availability the eventhandler.

Step 2

Now to invoke the event we call:

addEvent(window, 'online', online);
addEvent(window, 'offline', online);
online({ type: 'ready' });

So basically, here you trap the online and offline events of the Window object using either using attachEvent or addEventListener to show the online or offline status. Lets take a look on the event handler:

function online(event) {
document.getElementById('status').innerHTML = navigator.onLine ? 'online' : 'offline';
}

So in the code you can easily detect using the network status of the browser using navigat0r.onLine, such that when it returns true, that means client is online or else otherwise.

Here are the steps to sumarize:

  1. Add event listener to window.online / offline events
  2. Use navigator.onLine to detect whether the application is in online state.
  3. Do adjust your logic according to that.

The code works in most of the modern browsers. Happy coding :)

HostForLIFE.eu ASP.NET 5 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET Hosting France - HostForLIFE.eu :: How to Create Charts in ASP.NET

clock June 11, 2015 05:56 by author Rebecca

Graphs and charts are important tools for the analysis of data. In this tutorial, you will look at how to represent data in terms of a bar chart and pie chart. To make this possible, we need the latest rendition of Microsoft's Graphics Device Interface (GDI+).

Scenarios to draw bar and pie charts

In this bar and pie chart example, it will represent the data of a fictitious country having 4 towns; namely: Town A, Town B, Town C and Town D. Their population will be modeled in terms of graphs and charts. The figures are given below:

Town    Population
  A       1,000,000
  B        600,000
  C       2,500,000
  D        800,000

Then, the bar chart should be outputted like this:

And the pie chart should be outputted like below:

Useful classes

Below are some of the useful classes that will be used to achieve what you want:

The Bitmap class

In windows application, you would have output graphical contents to one of the windows. Whereas in ASP.NET, there are no window. Fortunately, there is a class that can act as the drawing surface and that is the Bitmap class.

As any drawing surface has a width and a height, so does the Bitmap object. So, when we will create a Bitmap object, we will pass in a width and a height as parameters in the constructors. Moreover, we have to specify “Pixel Format Argument” which means whether the pixel format should be 24-bits RGB color, 32-bits RGB color, GDI-colors etc. In short the following code will do the work.

Dim Image As New Bitmap(500, 300, PixelFormat.Format32bppRgb)

The Graphics Class

Once you have created the Bitmap object, you need to obtain a Graphics object that references that Bitmap object. The following code will do the job.

' Get the graphics context for the bitmap.
Dim g As Graphics = Graphics.FromImage(Image)

The x vs. y coordinates system is illustrated in the figure below:

The Drawer

Now that you have a surface to draw, as you may have guessed, you will need a pen or brush to draw. To create a pen, a few properties of the pen should be specified; like the color of the pen and the width of the pen..

' Create a pen for drawing
Dim redPen As New Pen(Color.Red, 10)
 
' Create a blue brush
Dim blueBrush As New SolidBrush(Color.Blue)

Useful methods for drawing

Now that we have a set of drawing tools at our disposal, the graphics class also has a set of interesting methods to simplify our work for drawing objects like: circles, rectangles, text and the list goes on.

For this tutorial, you will be using the following self explanatory methods:

  • Clear ( ): Cleans the graphics object (Pretty much like cleaning the whiteboard)
  • DrawString ( ): For outputting text
  • FillPie ( ): Draw a pie slice (useful for pie chart)
  • FillRectangle ( ): Draws a rectangle (useful for bar charts)
  • DrawLine ( ): Draws a line 

The above methods may be overloaded, so we used the names only. It is left to you as an option to explore how the overloaded methods.

How to Code the Chart Generator functions

Step 1

First of all create 2 buttons and label them Barchart and Piechart as shown in the figure below:

Step 2

Next, we shall declare some variables for the Bitmap object, Graphics object, population values, town names and the color representing each town. The code is as follows:

'   Variables declaration
Private myImage As Bitmap
Private g As Graphics
Private p() As Integer = {1000000, 600000, 2500000, 80000}
Private towns() As String = {"A", "B", "C", "D"}

Private myBrushes(4) As Brush

Next, in our Page_Load event, we will call a function that will create objects from the Bitmap and Graphics classes. We should also create the brushes that will be used for drawing the charts. The code snippet below does the job:

' Create an in-memory bitmap where you will draw the image.
' The Bitmap is 300 pixels wide and 200 pixels high.
myImage = New Bitmap(500, 300, PixelFormat.Format32bppRgb)
 
' Get the graphics context for the bitmap.
g = Graphics.FromImage(myImage)
 
'   Create the brushes for drawing
myBrushes(0) = New SolidBrush(Color.Red)
myBrushes(1) = New SolidBrush(Color.Blue)
myBrushes(2) = New SolidBrush(Color.Yellow)

myBrushes(3) = New SolidBrush(Color.Green)

Step 3

The bar charts have to be placed in a manner that we could draw the axes and label them as well. So, we declare an interval variable that will space the bar charts.

'   Variables declaration
Dim i As Integer
Dim xInterval As Integer = 100
Dim width As Integer = 90
Dim height As Integer
Dim blackBrush As New SolidBrush(Color.Black)
 
For i = 0 To p.Length - 1
    height = (p(i) \ 10000) '   divide by 10000 to adjust barchart to height of Bitmap
 
    '   Draws the bar chart using specific colours
    g.FillRectangle(myBrushes(i), xInterval * i + 50, 280 - height, width, height)
 
    '   label the barcharts
    g.DrawString(towns(i), New Font("Verdana", 12, FontStyle.Bold), Brushes.Black, xInterval * i + 50 + (width / 3), 280 - height - 25)
 
    '   Draw the scale
    g.DrawString(height, New Font("Verdana", 8, FontStyle.Bold), Brushes.Black, 0, 280 - height)
 
    '   Draw the axes
    g.DrawLine(Pens.Brown, 40, 10, 40, 290)         '   y-axis
    g.DrawLine(Pens.Brown, 20, 280, 490, 280)       '   x-axis
Next

The above code has only to be linked with the Click event of the “Barchart” button that was placed ok the page before. We have to keep track of the total angle so far and add the current angle produced by population[i] and use the FillPie method to draw the piechart.

Step 4

Next, to draw the pie chart, we make use of the following code:

'   Variables declaration
Dim i As Integer
Dim total As Integer
Dim percentage As Double
Dim angleSoFar As Double = 0.0
 
'   Caculates the total
For i = 0 To p.Length - 1
    total += p(i)
Next
 
'   Draws the pie chart
For i = 0 To p.Length - 1
    percentage = p(i) / total * 360
 
    g.FillPie(myBrushes(i), 25, 25, 250, 250, CInt(angleSoFar), CInt(percentage))
 
    angleSoFar += percentage
 
    '   Draws the lengend
    g.FillRectangle(myBrushes(i), 350, 25 + (i * 50), 25, 25)
 
    '   Label the towns
    g.DrawString("Town " & towns(i), New Font("Verdana", 8, FontStyle.Bold), Brushes.Brown, 390, 25 + (i * 50) + 10)
Next

The above code has to be linked with the Piechart Button's Click event.

Step 5

Now that we have the methods required to draw the charts, we should now output them on the browser. The piece of code below simply outputs the chart:

' Render the image to the HTML output stream.
myImage.Save(Response.OutputStream, _
System.Drawing.Imaging.ImageFormat.Jpeg)

Remember that myImage is the Bitmap object that we created earlier. Now, you can play around with the set of methods to produce other drawings or to improve the classes. You can also explore the rich set of methods and classes that the .NET framework provides you for producing drawings.

HostForLIFE.eu ASP.NET 5 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET Hosting Russia - HostForLIFE.eu :: Insert, Update, Delete & Retrieve Operations with ASP.NET

clock June 8, 2015 07:30 by author Peter

In this short article, I will write a simple code to Insert, update, delete, and Retrieve operations. Open the new project and then write the following code:

       using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Linq; 
    using System.Text; 
    using System.Windows.Forms;        
    using System.Data.SqlClient;             //namespace for using sqlserver components                    
    namespace InsertApp 
    { 
        public partial class Form1 : Form 
        { 
                          public Form1() 
            { 
                InitializeComponent(); 
            } 
                  private void Form1_Load(object sender, EventArgs e) 
            { 
                Getgrid(); 
            }                  
  public void Getgrid() 
            { 
                SqlConnection con = new SqlConnection("Data Source=SQLEXPRESS; Initial Catalog=SQLDATABASE; Integrated Security=SSPI "); 
                con.Open(); 
                SqlDataAdapter da = new SqlDataAdapter("select * from employee", con); 
                DataSet ds = new DataSet(); 
                da.Fill(ds); 
                dataGridView1.DataSource = ds.Tables[0]; 
           }        
            // Method for Insert the values 
            private void btnInsert_Click(object sender, EventArgs e)  
            { 
                SqlConnection con=new SqlConnection("Data Source=SQLEXPRESS; Initial Catalog=SQLDATABASE; Integrated Security=SSPI "); 
                con.Open();        
                    SqlCommand cmd = new SqlCommand("Insert into employee values('" + txtId.Text + "','" + txtName.Text + "','" + txtDesigid.Text + "','" + txtEmploc.Text + "')", con); 
                    int check = cmd.ExecuteNonQuery(); 
                    if (check > 0) 
                    { 
                        MessageBox.Show("Inserted"); 
                    } 
                    else 
                    { 
                        MessageBox.Show("Not- Inserted"); 
                    }                      
                    cmd.Dispose(); 
                    con.Close(); 
                    Getgrid();                    
            }        
            // Method for Update the values 
           private void btnUpdate_Click(object sender, EventArgs e) 
            { 
                SqlConnection con = new SqlConnection("Data Source=SQLEXPRESS; Initial Catalog=SQLDATABASE; Integrated Security=SSPI "); 
                con.Open();                    
                    SqlCommand cmd = new SqlCommand("update employee set emp_id='" + txtId.Text + "', emp_name='" + txtName.Text + "',desig_id='" + txtDesigid.Text + "',emp_location='" + txtEmploc.Text + "' where emp_id='"+txtId.Text+"'", con); 
                    cmd.ExecuteNonQuery(); 
                    MessageBox.Show("updated"); 
                    cmd.Dispose(); 
                    con.Close(); 
                    Getgrid(); 
            }        
            // Method for Delete the values 
            private void btnDelete_Click(object sender, EventArgs e) 
            { 
                SqlConnection con = new SqlConnection("Data Source=SQLEXPRESS; Initial Catalog=SQLDATABASE; Integrated Security=SSPI "); 
                con.Open();       
                SqlCommand cmd = new SqlCommand("delete from employee where emp_id='" + txtId.Text + "'", con); 
                cmd.ExecuteNonQuery(); 
                MessageBox.Show("deleted"); 
                cmd.Dispose(); 
                con.Close(); 
                Getgrid(); 
            }        
            // Method for Retrieve the values 
            private void btnRetrieve_Click(object sender, EventArgs e) 
            { 
                SqlConnection con = new SqlConnection("Data Source=SQLEXPRESS; Initial Catalog=SQLDATABASE; Integrated Security=SSPI "); 
                con.Open(); 
                      SqlCommand cmd = new SqlCommand("select * from employee where emp_id='" + txtId.Text + "'", con); 
                SqlDataReader dr = cmd.ExecuteReader(); 
                if (dr.Read()) 
                { 
                    txtId.Text = dr[0].ToString(); 
                    txtName.Text = dr[1].ToString(); 
                    txtDesigid.Text = dr[2].ToString(); 
                    txtEmploc.Text = dr[3].ToString(); 
                } 
            }        
            // Method for Clear values in textbox 
            private void btnClear_Click(object sender, EventArgs e) 
            { 
                clearmethod();             // calling clear method 
            }        
            public void clearmethod() 
            { 
                txtId.Text = ""; 
                txtName.Text = ""; 
                txtDesigid.Text = ""; 
                txtEmploc.Text = ""; 
            }      
        } 
   } 
Happy coding! 

HostForLIFE.eu ASP.NET 5 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



HostForLIFE.eu Proudly Launches Drupal 7.37 Hosting

clock June 1, 2015 09:29 by author Peter

European Windows and ASP.NET Spotlight Hosting Partner in Europe, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the Drupal 7.37 hosting technology.

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

Drupal is an open source content management platform powering millions of websites and applications. Thousands of add-on modules and designs let you build any site you can imagine. Drupal 7.37 Includes bug fixes and small API/feature improvements only (no major new functionality); major, non-backwards-compatible new features are only being added to the forthcoming Drupal 8.0 release. If you are looking for the right Windows ASP.NET Hosting provider that support Drupal 7.37, we are the right choice for you.

The 7.37 update also includes fixed a regression in Drupal 7.36 which caused certain kinds of content types to become disabled if we were defined by a no-longer-enabled module, removed a confusing description regarding automatic time zone detection from the user account form (minor UI and data structure change), allowed custom HTML tags with a dash in the name to pass through filter_xss() when specified in the list of allowed tags, allowed hook_field_schema() implementations to specify indexes for fields based on a fixed-length column prefix (rather than the entire column), as was already allowed in hook_schema() implementations, fixed PDO exceptions on PostgreSQL when accessing invalid entity URLs, added a sites/all/libraries folder to the codebase, with instructions for using it and added a description to the "Administer text formats and filters" permission on the Permissions page (string change).

HostForLIFE have hosted large numbers of websites and blogs until now. Our clients come from diverse backgrounds from all sectors of the economy. HostForLIFE.eu clients are specialized in providing supports for Drupal for many years. We are glad to provide support for European Drupal 7.37 hosting users with advices and troubleshooting for our client website when necessary.

HostForLIFE.eu is a popular online Windows based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market. Our powerful servers are especially optimized and ensure Drupal 7.37 performance. We have best data centers on three continent, unique account isolation for security, and 24/7 proactive uptime monitoring.

For more information about this new product, please visit http://hostforlife.eu/European-Drupal-737-Hosting

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.



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.



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