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

 



Free ASP.NET Hosting - HostForLIFE.eu :: How to Store Custom Objects in web.config

clock April 28, 2015 05:54 by author Rebecca

Normally, you used to have some data in appSettings section of web.config and read it when required. That is in string form, but there are lot more than this and you can update the data in web.config programmatically as well. You can store some object of custom type in web.config as well, which you normally don’t do it. But this can be very useful in several scenarios.

Have anyone tried to update some value or add some value in web.config? In this post, I'm going to tell you about web.config and how you can store the costum objects in web.config.

First, this is very common to have some constant data at appSettings section of web.config and read it whenever required. This is the way how to read data at appSettings:

//The data is stored in web.config as

<appSettings>

        <add key="WelcomeMessage" value="Hello All, Welcome to my Website." />

</appSettings>

// To read it
string message = ConfigurationManager.AppSettings["WelcomeMessage"];

If you want to update some data of appSettings programatically, you can do like this.

//Update header at config
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings["WelcomeMessage"].Value = "Hello All, Welcome to my updated site.";
        config.Save();


If you want to add some data in appSettings, you can add some app.config data as below:

//Update header at config
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        config.AppSettings.Settings.Add("ErrorMessage", "An error has been occured during processing this request.");
        config.Save();


The above code is adding one new key value pair in web.config file. Now this can be read anywhere in the application.

Now, the question is, Can we store some custom data at config? The answer is YES! We can store some object. Let’s see how:

In this example, I have saved an object of my custom class NewError in web.config file. And also updating it whenever required.
To do this, Follow the below steps.

Step 1

Create a Class that inherit From ConfigurationSection (It is available under namespace System.Configuration ). Every property must have an attribute ConfigurationProperty, having attribute name and some more parameters. This name is directly mapped to web.config. Let’s see the NewError class:

public class NewError:ConfigurationSection
{
    [ConfigurationProperty ("Id",IsRequired = true)]
    public string ErrorId {
        get { return (string)this["Id"]; }
        set { this["Id"] = value; }
    }
    [ConfigurationProperty("Message", IsRequired = false)]
    public string Message {
        get { return (string)this["Message"]; }
        set { this["Message"] = value; }
    }
    [ConfigurationProperty("RedirectURL", IsRequired = false)]
    public string RedirectionPage
    {
        get { return (string)this["RedirectURL"]; }
        set { this["RedirectURL"] = value; }
    }
    [ConfigurationProperty("MailId", IsRequired = false)]
    public string EmailId
    {
        get { return (string)this["MailId"]; }
        set { this["MailId"] = value; }
    }
    [ConfigurationProperty("DateAdded", IsRequired = false)]
    public DateTime DateAdded
    {
        get { return (DateTime)this["DateAdded"]; }
        set { this["DateAdded"] = value; }
    }
}

You can see every property has attribute ConfigurationProperty with some value. As you can see the property ErrorId has attribute:

[ConfigurationProperty ("Id",IsRequired = true)]

it means ErrorId will be saved as Id in web.config file and it is required value. There are more elements in this attribute that you can set based on your requirement.
Now if you’ll see the property closely, it is bit different.

public string ErrorId {
get { return (string)this["Id"]; }
set { this["Id"] = value; }
}

Here the value is saved as the key “id”, that is mapped with web.config file.

Step 2

Now you are required to add/register a section in the section group to tell the web.config that you are going to have this kind of data. This must be in and will be as:

<section name="errorList"  type="NewError" allowLocation="true"

     allowDefinition="Everywhere"/>

Step 3

Now one can add that object in your config file directly as:

<errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="[email protected]" ></errorList>

<errorList Id="1" Message="ErrorMessage" RedirectURL="www.google.com" MailId="[email protected]" ></errorList>

Step 4

And to read it at your page. Read it as follows:

NewError objNewError = (NewError)ConfigurationManager.GetSection("errorList");

And also a new object can be saved programmatically as

NewError objNewError = new NewError()
       {
         RedirectionPage="www.rediff.com",
         Message = "New Message",
         ErrorId="0",
         DateAdded= DateTime.Now.Date
       };
       Configuration config =
           WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

       config.Sections.Add("errorList", objNewError);
       config.Save();


Even one can add a custom group and have some custom elements in in this section. ASP.NET provides very powerfull APIs to read/edit the web.config file easily.

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. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



Free ASP.NET Hosting - HostForLIFE.eu :: Calling ASP.NET Page Methods using AJAX

clock April 21, 2015 06:19 by author Rebecca

In this post, I tell you how to invoke an ASP.NET page method directly from your own AJAX library. A Page method is a method that is written directly in a page. It is generally called when the actual page is posted back and some event is raised from the client. The pageMethod is called directly from ASP.NET engine. To implement PageMethod, first you need to annotate our method as WebMethod. A WebMethod is a special method attribute that exposes a method directly as XML service.

Here are the steps to create the application:

Step 1

Start a new ASP.NET Project.

Step 2

Add JQuery to your page. Then, you can add a special JQuery plugin which stringify a JSON object. And post the codes like below :

(function ($) {
$.extend({
toJson: function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
});
// extend plugin scope
$.fn.extend({
toJson: $.toJson.construct
});
})(jQuery);

The code actually extends JQuery to add a method called toJSON to its prototype.

Step 3

Add the server side method to the Default.aspx page. For simplicity, you can actually return the message that is received from the client side with some formatting.

[WebMethod]
public static string DisplayTime(string message)
{
// Do something

return string.Format("Hello ! Your message : {0} at {1}", message, DateTime.Now.ToShortTimeString());
}


You should make this method static, and probably should return only serializable object.

Step 4

Add the following Html which actually puts one TextBox which takes a message and a Button to call server.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<p>
Write Your message Here : <input type="text" id="txtMessage" />
</p>
<p>
<input type="button" onclick="javascript:callServer()" value="Call Server" />
</p>
</asp:Content>


Once you add this html to your default.aspx page, add some javascript to the page. We add the JQuery and our JSONStringify code to it.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/JSONStringify.js" type="text/javascript"></script>

<script type="text/javascript">
function callServer() {
var objdata = {
"message" : $("#txtMessage").val()
};
$.ajax({
type: "POST",
url: "Default.aspx/DisplayTime",
data: $.toJson(objdata),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhr, ajaxOptions) {
alert(xhr.status);
}
});
}
</script>


The above code actually invokes a normal AJAX call to the page. You can use your own library of AJAX rather than JQuery to do the same.

Hope it works for you!

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. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



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