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



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



Free ASP.NET 5 Hosting - HostForLIFE.eu :: How to Create Profiles in ASP.NET

clock April 14, 2015 06:22 by author Rebecca

The ASP.NET Framework comes with the Profile object which an alternative to using cookies or session state to store user information. The Profile object provides you with a strongly typed, persistent form of session state.

You create a Profile by defining a list of Profile properties in your application root web configuration file. The ASP.NET Framework dynamically compiles a class that contains these properties in the background. The following web configuration file defines a Profile that contains three properties: firstName, lastName, and numberOfVisits.

File: Web.Config

<configuration>
<system.web>

  <profile>
    <properties>
      <add name="firstName" />
      <add name="lastName" />
      <add name="numberOfVisits" type="Int32" defaultValue="0" />
    <add name="xmlLastName" type="String" serializeAs="Xml"/>     
    </properties>
  </profile>

</system.web>
</configuration>

When you define a Profile property, you can use any of the following attributes:

  • name sets the name of the property.
  • type sets the type of the property.

The type can be any custom type, including a custom component that you define in the App_Code folder.

The default type is string.
defaultValue is a default value for the property.
readOnly creates a read-only property.

The default value is false.
serializeAs sets how a property is persisted into a static representation.
Possible values are Binary, ProviderSpecific, String, and Xml.

The default value is ProviderSpecific.
allowAnonymous allows anonymous users to read and set the property.

The default value is false.
provider associates the property with a particular Profile provider.
customProviderData passes custom data to a Profile provider.


File: ShowProfile.aspx

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    void Page_PreRender()
    {
        lblFirstname.Text = Profile.firstName;
        lblLastName.Text = Profile.lastName;

        Profile.numberOfVisits++;
        lblNumberOfVisits.Text = Profile.numberOfVisits.ToString();
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        Profile.firstName = txtNewFirstName.Text;
        Profile.lastName = txtNewLastName.Text;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Profile</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    First Name:
    <asp:Label
        id="lblFirstname"
        Runat="server" />
    <br /><br />
    Last Name:
    <asp:Label
        id="lblLastName"
        Runat="server" />
    <br /><br />
    Number of Visits:
    <asp:Label
        id="lblNumberOfVisits"
        Runat="server" />

    <hr />

    <asp:Label
        id="lblNewFirstName"
        Text="New First Name:"
        AssociatedControlID="txtNewFirstName"
        Runat="server" />
    <asp:TextBox
        id="txtNewFirstName"
        Runat="server" />
    <br /><br />
    <asp:Label
        id="lblNewLastName"
        Text="New Last Name:"
        AssociatedControlID="txtNewLastName"
        Runat="server" />
    <asp:TextBox
        id="txtNewLastName"
        Runat="server" />
    <br /><br />
    <asp:Button
        id="btnUpdate"
        Text="Update Profile"
        OnClick="btnUpdate_Click"
        Runat="server" />

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



ASP.NET 5 Hosting - HostForLIFE.eu :: Configuring Your First Entity Framework in ASP.NET 5

clock April 7, 2015 12:33 by author Rebecca

If you're planning to get started with Entity Framework 7, at first you need to configuring the entity framework. The default is already there but when you need to update to the new versions, you must take a look at what is in the project.json file:

{
  /* Click to learn more about project.json  http://go.microsoft.com/fwlink/?LinkID=517074 */
  "webroot": "wwwroot",
  "version": "1.0.0-*",
  "dependencies": {
    "EntityFramework.SqlServer": "7.0.0-beta3",
    "EntityFramework.Commands": "7.0.0-beta3",
    "Microsoft.AspNet.Mvc": "6.0.0-beta3",

For your information, the startup.cs allowed for configuration to happen in two phases. First, the configuration of the different elements, then the registering of services with the dependency injection layer.

The service container is the dependency injection mechanism built into ASP.NET 5 and the ConfigureServices method is where that happens. Before you can add EF to the DI container, you need to get a connection string.

When I first came to ASP.NET 5, it looked as if the EF configuration would just load the connection string by convention, but it didn’t work. So I had to get it manually and add it (below) when I configured the context object.

// This method gets called by the runtime.
public void ConfigureServices(IServiceCollection services)
{
  var connectionString = Configuration.Get("Data:DefaultConnection:ConnectionString");

The Configuration.Get method allows it to read a setting from the list of configuration sources. Then, the Configuration object is a merge of the config.json file and any environment variables. In the case of the connection string, you’re looking for a string called “ConnectionString” inside an object graph. This should look obvious once you see the config.json file:

{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;..."
    }
  },
  "EntityFramework": {
    "ApplicationDbContext": {
      "ConnectionStringKey": "Data:DefaultConnection:ConnectionString"
    }
  }
}

Now that we have the connection string, what's next?

You can add Entity Framework to the services collection by adding it this code below:

// Add EF services to the services container.
services.AddEntityFramework(Configuration)
    .AddSqlServer()
    .AddDbContext<MyCountriesContext>(options =>
    {
      options.UseSqlServer(connectionString);
    });

SUMMARY

The AddEntityFramework method adds EF to the dependency injection container so it can be served if needed later. Additionally, calling AddSqlServer specifies the data store you’ll be using. Finally, the AddDbContext adds a DbContext object to the EF service. The options lambda allows us to specify the connection string. I suspect this extra step will go away at some point and just read from the configuration by convention, but at this point it’s necessary. If we need the context in another part of the system (e.g. Controllers) we can just let ASP.NET 5 serve it to us in the constructor like any other dependency injection framework.

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 5 Hosting - HostForLIFE.eu :: How to Use POCO Controllers in ASP.NET 5

clock April 2, 2015 13:21 by author Rebecca

As you know, ASP.NET 5 supports POCO controllers. The controller classes doesn’t extend Controller base class. These controllers look a little bit different by some small aspects and sometime,s you may need to help framework detect our POCO controllers. In this post, I will give you complete overview of POCO controllers in ASP.NET 5.

Creating POCO controllers is simple. To use views and other goodies provided by controllers base class we have to use dependency injection to get required services to our POCO controller. If we don’t use MVC regular naming style for controllers we have to write action discovery convention and register it with built-in dependency injection service. To provide common strategy to detect POCO controllers with arbitrary names we can use special attribute or interface for this. We still can inherit our POCO controllers from classes we want. Here is the simple steps that you have to follow:

Simple POCO Controllers

First let’s define that simple controller doesn’t inherit from Controller base class. Follow the code below:

public class PocoController
{
    public IActionResult Index()
    {
        return new ContentResult() { Content = “Hello from POCO controller!” };
    }
}

And to make this controller work with views, you need some additional code.

public class PocoController
{
    private readonly IModelMetadataProvider _metadataProvider;
 
    public PocoController(IModelMetadataProvider metadataProvider)
    {
        _metadataProvider = metadataProvider;
    }
 
    public IActionResult Index()
    {
        var viewData = new ViewDataDictionary<string>(_metadataProvider);
        viewData.Model = “Hello from POCO controller!”;
 
        return new ViewResult() { ViewData = viewData };
    }
}

Now, you have basic primitive POCO controller that you can use in ASP.NET 5.

The second thing that you have to is use a small trick and call our controller just as "POCO" using this code:

public class Poco
{
    // …
}

When trying to use controller now you have run to problems like this. Why? Because ASP.NET cannot detect controller anymore.

How to make the controller is detected by default?

When sniffing around in MVC source you can find the method that MVC uses to find out if given type is controller type of not. It is done in DefaultActionDiscoveryConventions class.

public virtual bool IsController([NotNull] TypeInfo typeInfo)
{
    if (!typeInfo.IsClass ||
        typeInfo.IsAbstract ||
        typeInfo.ContainsGenericParameters)
    {
        return false;
    }
 
    if (typeInfo.Name.Equals(“Controller”, StringComparison.OrdinalIgnoreCase))
    {
        return false;
    }

    return typeInfo.Name.EndsWith(“Controller”, StringComparison.OrdinalIgnoreCase) ||
           typeof(Controller).GetTypeInfo().IsAssignableFrom(typeInfo);

If we have POCO controller andyou don’t name it as SomethingController then MVC is not considering our POCO controller as controller.

Using action discovery convention

If there are additional rules for detecting controllers, you can use action discovery conventions to tell MVC if class is constructor or not. Here is simple discovery convention class that works with our POCO controller.

public class MyActionDiscoveryConventions : DefaultActionDiscoveryConventions
{
    public override bool IsController(TypeInfo typeInfo)
    {
        var isController = base.IsController(typeInfo);
        return isController || typeInfo.Name.Equals(“Poco”, StringComparison.OrdinalIgnoreCase);
    }
}


To make MVC use this class, you have to register it with built-in dependency injection system. You will do it in ConfigureServices() method of your Startup class by calling AddTransient() method.

public void ConfigureServices(IServiceCollection services)
{
    // …
    services.AddMvc();
 
    services.AddTransient<IActionDiscoveryConventions, MyActionDiscoveryConventions>();

}

If you run your application now and try to use POCO controller it works again.

Defining ControllerAttribute

If you are building some extensible system and you need some better way how to detect controllers then besides naming controllers appropriately you can also define attribute in some API library that is available for developers.

public class ControllerAttribute : Attribute
{
}
Other developers who are building plugins for your system can decorate their controllers with this attribute.

[Controller]
public class Poco
{
    // …
}

And here is how you can detect controller in action discovery convention.

public class MyActionDiscoveryConventions : DefaultActionDiscoveryConventions
{
    public override bool IsController(TypeInfo typeInfo)
    {
        var isController = base.IsController(typeInfo);
        return isController || HasControllerAttribute(typeInfo);
    }
 
    private bool HasControllerAttribute(TypeInfo typeInfo)
    {
        return typeInfo.GetCustomAttribute<ControllerAttribute>(true) != null;
    }
}

You can also use marker interface for POCO controllers or some interface with properties and methods defined if your POCO controllers have to provide some functionalities.

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 5 Hosting – HostForLIFE.eu :: How to Create an HTML Control from any HTML Elements in ASP.NET

clock March 30, 2015 07:58 by author Rebecca

Sometimes as an ASP.NET developer, you may want to create your web application using a specific html structure or specific html elements. ASP.NET Web Controls only allow so much customization over the interface and the actual markup that gets displayed in the browser. Well, I will explain to you how to use hand coded html elements known in the framework as HTML Controls. These HTML Controls allow us to have full control over our interface markup yet still allows us to use our own HTML element as a ASP.NET Server Control. Let’s get started!

First, add your element to your aspx file. In order to use the element as a Server Control, we need to specify an element ID and the runat="server" properties. Try to add the following code within the <body> tag in Default.aspx:

<h1 id="the_heading" runat="server"></h1>

To demonstrate the abilities of HTML Controls, we’re going to leave this heading tag blank, and populate it via server side code in the code-behind. This single HTML element is enough for a demonstration, but in a larger production application, you will have many elements that need to be dynamically populated throughout your project.

In order to use an HTML Control we’re going to have to import the HTML Controls namespace in Default.aspx.cs like so:

using System.Web.UI.HtmlControls;

Now that we have the required namespace referenced in the top of the code-behind, we can continue by instantiating and manipulating our HTML Control.

Within the standard Page_Load method in Default.aspx.cs, please type the following:

var a = " World!"
the_heading.InnerHtml = "Hello" + a;

In the code above, we are instantiating a variable named a that contains the string " World!". On the next line we reference our HTML Control via it’s ID attribute the_heading.

We call this method as InnerHtml on the HTML element which replaces the content within the elements tags.

Finally, we specify the content to populate the element with as the string "Hello" concatenated with our variable a to create the message "Hello World!". Now when we compile our program, our empty heading tag should contain the friendly message “Hello World!”.

The entire code-behind should look similar to the following:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace html_controls
{
  public partial class _Default : Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      var a = " World";
      the_heading.InnerHtml = "Hello" + a;
    }
  }
}

That's all about creating an HTML Control from any HTML Elements in ASP.NET. Easy right? Good luck!

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.



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