European ASP.NET 4.5 Hosting BLOG

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

European ASP.NET 4 Hosting :: How to Create Custom Objects in ASP.NET 4.0 with C#

clock July 28, 2011 05:38 by author Scott

In this tutorial, we will be creating our own class that will represent a Person object, which we will store in a database. Within this class, we will create custom properties and methods to interact with that object. We will also show you how to use a collection class to group together these objects and handle them with ease.

To get started, we will create a new web application in Visual Studio. We will be working primarily with the Default.aspx page and a .cs file. So let us begin by adding the Class. Right-click the App_Code folder in the Solution Explorer (if you do not see it, right-click your solution and choose Add ASP.NET Folder > App_Code), and then choose Add New Item… We want to add a new Class; name it People.cs and click Ok. We should get something like this:

using
 System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
/// <summary>
/// Summary description for People
/// </summary>
public class People
{
public People()
{
//
// TODO: Add constructor logic here
//
}
}


First, let’s wrap the Class in a namespace. This makes it easier for us to keep our code together, especially when building bigger applications and grouping multiple classes in one namespace. Then rename the Class to Person – People will be the wrapper namespace; Person will be the class.

namespace
 ProgrammingHelp.People
{
    public class Person
    {
 
    }
}


The next thing to do will be to create the default constructor for the Class and set the Properties. The default constructor (public Person()) will instantiate an empty Person object, when called. It will look like this:

public Person()
{
}

We can wrap our Properties in a #region. We will need to specify all properties of our object, and set the default values and data types. We do this as follows:


#region properties
 
        /// <summary>
        /// Gets or sets PersonID. [Default value is 0].
        /// </summary>
        public Int32 PersonID
        {
            get
            {
                return _PersonID;
            }
            set
            {
                _PersonID = value;
            }
        }
        private Int32 _PersonID = 0;
 
        /// <summary>
        /// Gets or sets the First Name of the Person. [Default value is ''].
        /// </summary>
        public String FirstName
        {
            get
            {
                return _FirstName;
            }
            set
            {
                _FirstName = value;
            }
        }
        private String _FirstName = "";
 
        /// <summary>
        /// Gets or sets the Last Name of the Person. [Default value is ''].
        /// </summary>
        public String LastName
        {
            get
            {
                return _LastName;
            }
            set
            {
                _LastName = value;
            }
        }
        private String _LastName = "";
 
        /// <summary>
        /// Gets or sets the City of the Person. [Default value is ''].
        /// </summary>
        public String City
        {
            get
            {
                return _City;
            }
            set
            {
                _City = value;
            }
        }
        private String _City = "";
 
        /// <summary>
        /// Gets or sets DateTime the Person was added. [Default value is the current Date/Time].
        /// </summary>
        public DateTime DateTimeAdded
        {
            get
            {
                return _DateTimeAdded;
            }
            set
            {
                _DateTimeAdded = value;
            }
        }
        private DateTime _DateTimeAdded = DateTime.Now;
 
        /// <summary>
        /// Gets or sets the Age of the Person. [Default value is 0].
        /// </summary>
        public int Age
        {
            get
            {
                return _Age;
            }
            set
            {
                _Age = value;
            }
        }
        private int _Age = 0;
 
        #endregion

Notice we make the Properties public so that we can reference them outside of the class, and we set the defaults within the class, using Private. We also want to create a constructor that will instantiate a usable object. We can create many constructors that take various overloads. Let us start with the first, which will be used to build the object using a SqlDataReader. First, we will create a method that the constructor will use to parse the DataReader and set the object with the values:

private void SetObjectData(SqlDataReader theObjReader)
        {
           this._PersonID = Convert.ToInt32(theObjReader["PersonID"]);
           this._FirstName = theObjReader["FirstName"].ToString();
           this._LastName = theObjReader["LastName"].ToString();
           this._City = theObjReader["City"].ToString();
           this._Age = Convert.ToInt16(theObjReader["Age"]);
           this._DateTimeAdded = Convert.ToDateTime(theObjReader

         ["DateTimeAdded"]);
        }

We place all the Class’s methods below the Properties, and can use another #region to group them together. The SetObject method takes a parameter of a SqlDataReader, which is then used to set the properties of the object, using the correct data types as specified in the Properties. Now we can call this method using a constructor like so:


public Person(SqlDataReader theObjReader)
{
   SetObjectData(theObjReader);
}

This constructor will be used to build an object from a SqlDataReader. When this constructor is called, a SqlDataReader must be passed, and a Person object will be returned. However, we’re not always going to be able to use a SqlDataReader to build an object from. This constructor will be mainly used for internal methods, when retrieving records from the database and returning an object, for example:

A more common constructor to use would be one that takes the parameter of the object ID. This way, we can take that ID, pull the corresponding record from the database and then return the object. To do this, let’s add our database. Right-click the App_Data folder in Solution Explorer, then choose to Add New Item.. SQL Server Database. Give it a name and hit OK. Once opened, we want to create a new table People. We can do this straight in the Visual Studio environment using Server Explorer:



We will create the same columns as our Class Properties, with similar types – PersonID will be bigint; FirstName varchar(50); Age smallint, and DateTimeAdded datetime for example. Once saved, you can right-click the table and choose to Show Table Data. This will allow you to enter some sample data to test with. Add a test record or two.

In this example, we are going to illustrate how to use a custom class to make use of collections of data. Going back to our class, we will make a collection class of the existing Person class, which we can call People. To do this, we need to create a new class outside of the Person class, but within the namespace, and we need to inherit from the CollectionBase class. First thing to do is to make sure we have the following reference at the top of our code and declare the class like so:


using System.Collections;
//And the class we will be declaring

[Serializable]
public class People : CollectionBase
{
}

Now, similar to our Properties of the Person class, we will add Properties and Methods of the collection class:

[Serializable]
public class People : CollectionBase
{
    public int TotalRecords
    {
        get
        {
            return _TotalRecords;
        }
        set
        {
            _TotalRecords = value;
        }
    }
    protected int _TotalRecords = 0;
 
    public int Add(Person thePerson)
    {
        this.TotalRecords++;
        return List.Add(thePerson);
    }
 
    public void Insert(Int32 index, Person thePerson)
    {
        List.Insert(index, thePerson);
    }
 
    public void Remove(Person thePerson)
    {
        List.Remove(thePerson);
    }
 
    public bool Contains(Person thePerson)
    {
        return List.Contains(thePerson);
    }
 
    public int IndexOf(Person thePerson)
    {
        return List.IndexOf(thePerson);
    }
 
    public void CopyTo(Person[] array, int index)
    {
        List.CopyTo(array, index);
    }
 
    public Person this[int index]
    {
        get
        {
            return (Person)List[index];
        }
        set
        {
            List[index] = value;
        }
    }
}

Because we are inheriting from the CollectionBase class, a lot of the functionality is already there – we are simply customizing it for our Person class. Now to demonstrate how this works, we will create a method in our Person Class that will get all records (People) from the database, and return them in a People collection. So the method will look something like this:

public static People GetAllPeople()
{
People PeopleCollection = new People();
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
SqlCommand cmd = new SqlCommand("sp_GetAllPeople", connection);
cmd.CommandType = CommandType.StoredProcedure;
 
connection.Open();
SqlDataReader objReader = cmd.ExecuteReader();
while (objReader.Read())
{
Person newPerson = new Person(objReader);
PeopleCollection.Add(newPerson);
}
objReader.Close();
connection.Close();
}
catch
{
connection.Close();
}
return PeopleCollection;
}

Notice that although they are two separate classes, we have full access to the People collection from the Person class. This is because they both reside in the same namespace. So we start by declaring an empty People collection, then define our connection string. Next, we use a try..catch to attempt to execute the Stored Procedure to retrieve all records from the database. Our Stored Procedure looks something like this:

ALTER PROCEDURE dbo.sp_GetAllPeople
 
AS
 
SELECT FROM People

Once the Stored Procedure is executed, we check to see if any records are returned, and if so, we call the Person constructor to set the new object with the SqlDataReader, and then add it to the new collection. Finally, once all records have been processed, we close the connection and the method will return the People collection it just built. The great thing about collections, is that we can assign them to the DataSource of ASP.NET Controls and their Properties can be used directly. For example, we will use this method to assign the collection to a Repeater’s DataSource, then display the Properties on the page. To do this, move to the Default.aspx page and add a Repeater control like so:

<asp:Repeater ID="repeater_People" runat="server">
            <HeaderTemplate>
                <table width="600">
                <tr>
                    <th width="100">ID</th><th width="150">Name</th>
                    <th width="100">City</th><th width="100">Age</th>

                    <th width="150">Added</th>
                </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td><%# Eval("PersonID"%></td>
                    <td><%# Eval("FirstName"%> 

<%# Eval("LastName"%></td>
                    <td><%# Eval("City"%></td>
                    <td><%# Eval("Age"%></td>
                    <td><%# Eval("DateTimeAdded"%></td>
                </tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Notice we are using the Property names to display to the page. We can assign the collection on page load, but first, we must remember to add the reference to the namespace then we can reference the method to get all People, and assign it to the repeater.

using ProgrammingHelp.People;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindRepeater();
            SetDropDown();
        }
    }

Now if you run the page, the repeater should display the contents of your database table. This may seem like the long way around getting a few items to display in a repeater, and it is. Custom Objects, however, are extremely useful when using larger amounts of data across multiple pages.


Success!



ASP.NET 4 Hosting - ASPHostPortal :: ASP.NET 4.0 Web Forms Model

clock July 21, 2011 06:03 by author Scott

ASP.NET 4.0 platform is built up with various components Web Forms,ASP.NET MVC, Dynamic Data Controls and ASP.NET AJAX. It has the same foundation as in ASP.NET 3.5 SP1 but refined the above features. This post speaks about features in the Web Form model.

ASP.NET 4.0 features are nothing new, all are in 3.5 but this version gives more control over frequently used features.

Example: ASP.NET 4.0 Web Forms give developers more control over viewstate management, generation of Control ID’s, and HTML generated by some template based controls.

Control Over the Viewstate

Every developer knows that ASP.NET Viewstate burdens the page and waste of bandwidth. Same developers welcomed the ASP.NET MVC because of its complete absence of viewstate. If you ignore the viewstate on your page then you need to reload the data from server to controls.

The Viewstate is functional to Web Forms model, as it caches the contents from cache for control in the page.The overlooked feature is we can turnoff the viewstate for the page or control.The viewstate support is turned on for each page by default. The property EnableViewstate is defined is System.Web.UI.Control class and can be used to turn it on or off.

You can turn off the viewstate for ASP.NET page either declaratively or programmatically during the page’s life cycle.

void Page_Load(object sender,EventArgs e)
{
//Disable viewstate for the page and all of its child controls

this.EnableViewState = false;

....

}

Viewstate setting in ASP.NET has hierarchical nature, which means if the viewstate is enabled on the parent control, it can not be disabled on any of its child controls. You can disable the viewstate at page level and enable it in control level wherever it required.

ASP.NET 4.0 feature is you can enable viewstate at control level. In ASP.NET 4.0, the System.Web.UI.Control class exposes a new property named ViewStateMode:

public virtual ViewStateMode {get; set; }

ViewStateMode enumeration has the following values

Value

Description

Inherit

Inherits the value of ViewStateMode property from the parent control

Enabled

Enables viewstate for this control even if the parent control has set the viewstate property disabled.

Disabled

Disables viewstate for this control even if the parent control has set the viewstate property enabled.


Auto-Generated IDs

It is possible that rendered HTML can contain the same ID. When search for an element using getElementById, you will simply get an array of elements.Most data-bound controls generate their output by repeating the HTML for every data-bound item.


The sample generated Id string look like the following

ctl00$ContentPlaceHolder2$Gridview11$TextBox1

First issue might be with the length of the string, which repeated for several elements, makes the downloaded larger. Predicting the ID of a given control from script is difficult.

A frequently used technique for the above issue is

var btn = document.getElementById("<%=Button1.ClientID %> ");

ASP.NET 4.0 supports another option for autogenerated ids problem and developer can has greater control over generating the clientid of a control.

The System.Web.UI.Control Class now has a brand new property named ClientIDMode.

The ClientIDMode property values can be

Value

Description

Legacy

Indicates that ID should be generated as in earlier versions of ASP.NET

Static

ASP.NET doesn’t make any attempt to scope the client ID. The ID is assigned as-is.

Predictable

The ID is obtained by simply concatenating the ID of parent controls and ignoring master page’s parent elements.

Inherit

The control will use the same algorithm as its parent.


Consider the following code:

<asp:GridView ID="GridView1" runat="server"
              ClientIDMode = "Predictable"
              RowClientIdsuffix="CustomerID">
  ......

</asp:GridView>

In this case, each row of the grid is identified by one or more columns in the data source with a trailing index. Example

Panel1_GridView1_ALFKI_1

Finally, note that the ClientIDMode property affects only the ID attribute of the resulting HTML.

HTML Enhancements

In the early version of ASP.NET developer didn’t have much control over programmatically accessing the HTML tags of a Web Page.


In ASP.NET 4.0, the Page class exposes two new string properties to set some common tags in the <head> section of a page. The two properties are Keywords and Description. The Keywords and Description properties can also be set directly as attributes of the @Page directive as shown below

<%@ Page Language="c#"
    AutoEventWireup="true"
    CodeFile="Default.aspx.cs"
    Inherits="_Default"
    Keywords="ASP.NET, AJAX "
    Description="ASP.NET 4.0 WebForms" %>

Conclusion

ASP.NET 4.0 Web Forms contains a number of features that together can make it a bigger development platform. It is moreover a refinement of existing features.



European ASP.NET 4 Hosting :: How to Extend ASP.NET Web Pages - Create Your Own Helpers

clock July 20, 2011 05:54 by author Scott

The Beta1 version of WebMatrix comes with a number of Web Pages helpers to make your life simple. These include helpers to work with file uploading, images, email, caching, grids, Twitter feeds and a lot more. I suspect that as the product evolves towards full release, more will be added. Nevertheless, the developers of WebMatrix and Web Pages cannot anticipate every requirement, so there will be a time when you feel you need something extra. Adding your own helpers is quite easy, as this article shows.

One area where there is no helper currently is consuming RSS feeds. So I am going to build a helper that allows the user to display part of an RSS feed on a web page. The code that I will show here does the job, although it is far from perfect. Its purpose is to illustrate the main points involved in creating a helper, and not to be a production-ready example of how to produce an Rss reader. It lacks far too much exception handling for one thing, and I felt that adding too much would obscure the main thrust of this article. For that reason, I won't delve too deeply into the actual helper code, but I will draw attention to the key areas that should be considered when developing helpers.

The first thing to do is to add a new folder to the web site. This folder must be named "App_Code". Future versions of WebMatrix may offer this in something like an "Add New ASP.NET Folder" menu option at some stage, but that's not currently available.
App_Code is a special folder. ASP.NET will compile anything inside this the first time the site is run, and it will be available to other code throughout the site. Within that folder, add a new file. The type of file is a C# class file.



Call this file "RssReader.cs", and then remove all the code that's in it, then replace it with the following:

using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;

public static class RssReader
{
  public static HtmlString GetHtml(string url, int numberOfItems = 5,
                        bool showDescription = true, bool showDateCreated = true, int width = 300)
  {
    TagBuilder divTag = new TagBuilder("div");
    TagBuilder pTag = new TagBuilder("p");
    TagBuilder anchor = new TagBuilder("a");   

    var doc = XDocument.Load(url);
    XNamespace a10 = doc.Root.GetNamespaceOfPrefix("a10");
    var items = doc.Descendants("item").Select(feed => new
    {
      Title = feed.Element("title"),
      Link = a10 != null ? feed.Element(a10 + "link").Attribute("href").Value : feed.Element("link").Value,
      Date = feed.Element("pubDate"),
      Description = feed.Element("description")
    }).Take(numberOfItems);

    divTag.MergeAttribute("id", "rssDiv");
    divTag.MergeAttribute("style", "width:" + width + "px");
    foreach(var item in items)
    {
      anchor.InnerHtml = item.Title.Value;
      anchor.MergeAttribute("href", item.Link);
      pTag.InnerHtml = anchor.ToString();
      divTag.InnerHtml += pTag.ToString();
      if(showDateCreated)
      {
        TagBuilder pTag2 = new TagBuilder("p");
        DateTime dateValue;
        if(DateTime.TryParse(item.Date.Value, out dateValue))
        {
          pTag2.InnerHtml = dateValue.ToString("G");
        }
        divTag.InnerHtml += pTag2.ToString();
      }
      if(showDescription)
      {
        TagBuilder pTag3 = new TagBuilder("p");
        pTag3.InnerHtml = item.Description.Value;
        divTag.InnerHtml += pTag3.ToString();
      }
    }
    return new HtmlString(divTag.ToString());
  }
}

Right - before you pass out, let me explain how this code works. It's simple, really. The first 5 lines make certain namespaces available to the code so that when we reference items within them, we do not have to use their fully qualified name. You can see public static HtmlString near the beginning of the code. The fully qualified reference for HtmlString
is System.Web.Mvc.HtmlString, and without adding a using statement to make System.Web.Mvc available to the class file, we would have to type the fully qualified name every time we wanted to reference HtmlString. System.Web.Mvc also makes TagBuilder available in a short-handed fashion too.

You should also note that both the RssReader class and the GetHtml method are static. This means we do not have to create an instance of RssReader in order to call the GetHtml method from a web page or other code. This is typical of helper methods, and other utility methods in general.

The parameters for the GetHtml method are worth noting too. The first one is a required parameter. In other words, when the GetHtml method is called, you must pass a string as an argument. Ideally, that string will be a valid Uri pointing the the location of an RSS feed. There's no checking in the method to make sure it is. This is one of the missing pieces of exception management I mentioned earlier. The other 4 parameters are all optional. In other words, the caller does not need to provide any values for them. You can see they are optional as they have default values.
Optional parameters were added in C# 4.0, and are a terrific way to add flexibility without the need for creating multiple overloaded versions of the GetHtml method. Optional parameters must always be declared AFTER all required parameters (except for one case involving params arrays, but that's not important here).

The next thing of note is the 3 TagBuilder objects that are created. TagBuilder is a very useful class introduced with ASP.NET MVC if you ever want your helper to render html elements, along with HtmlString. TagBuilders allow you to specify an html tag such as a <p> for paragraph, or <input type="text" />, without having to fiddle around with building the string manually, which can be error prone, especially when trying to deal with embedded double quotes. HtmlString ensures that the resulting concoction of tags and html are rendered as html, rather than being html-encoded.

The RSS feed is obtained via the XDocument.Load() method, which is part of System.Xml.Linq. I'm not going to go into too much detail about
Linq To XML but it is a nice way to deal with XML, which is what an RSS feed is, once you get to grips with the basics of the subject (which I hope to do one day...). Suffice to say that assuming the Load method actually managed to retrieve the XML file (again, error checking should be in place there) some items are retrieved from it and used to build a collection of objects. How many objects are built depends on the value passed in to the numberOfItems parameter. If no value was provided, it will default to 5 items.

Now that we have a collection of objects, they are iterated through to build some html. The resulting RSS feed will be housed in a div element, with a width of 300px by default. This can be customised by the user if they choose to pass a value into the method. While iterating the collection, the code builds an html link from the item's Link property, and puts that into a paragraph element. Then it checks ot see if the caller decided to include the published date in their RSS Reader. If they did, or left the default value, this is added to another paragraph element. Finally if the showDescription value is true, item descriptions are added to another paragraph, before looping to the next item in the collection. Finally, the whole lot is returned to the caller as a string of Html.

Before showing how this code can be used in a cshtml file, I will take a second to review the key points about constructing helpers:

1. App_Code is the place for class files which need to be made available across the site
2. Helper classes and methods should invariably be static
3. HtmlStrings ensure that anything to be rendered by the browser is sent as Html
4. TagBuilders make building valid Html a lot easier
5. Optional parameters save a lot of code by reducing the need to create overloaded methods

Here are a couple of ways in which the helper can be called within a Web Pages file:

@RssReader.GetHtml("http://dotnet4europeanhosting.hostforlife.eu/rss")

@RssReader.GetHtml("http://dotnet4europeanhosting.hostforlife.eu/rss/", showDescription: false, width: 400, numberOfItems: 10)

The first line makes use of all default values applied to the optional parameters, while the second one changes the number of items to 10, increases the width of the housing div, and elects not to display descriptions. It leaves the helper to show the date. You should also notice that the optional parameters arguments are prefixed by the name of the parameter, and are not added to the method call in the order in which they appear in the method parameter list itself. Named parameters was also introduced in C# 4.0, and the link to Optional parameters provided earlier explains more about this too.



European ASP.NET 4 Hosting :: ASP.NET & Javascript - Multiline TextBox Counter in Twitter

clock July 14, 2011 05:27 by author Scott

Here, we'll see how to implement a Twitter like multiline asp:TextBox character counter that counts how many characters are entered in the asp:TextBox using simple javascript. We'll also restrict user to post (submit) Text, if the entered character count is greater than Max. allowed characters by disabling the Button.

Let's start by creating a new ASP.Net website named 'TwitterLikeTextCounter', say. In the 'Default.aspx', insert three controls i.e. a multiline asp:TextBox (used to enter character input), a readonly asp:TextBox (used to show the character count) and a button. As we want to impose some Max. allowed characters restriction on the Multiline asp:TextBox, if the character count in asp:TextBox exceeds the maximum allowed characters then the submit button is disabled and the character counter CSS is also changed. Add the below code in head section of page:

<script language="javascript" type="text/javascript">
  function GetButtonTwitterLikeCounter() {
    return document.getElementById('<%= btnTwitterLikeCounter.ClientID %>');
  }
  function GetTextBoxCharacterCounter() {
    return document.getElementById('<%= TextBoxCharacterCounter.ClientID %>');
  }
  function SetTextBoxCharacterCounter(src) {
    txtCount = GetTextBoxCharacterCounter();
    txtCount.value = 100 - src.value.length;
  }
  function checkLength(src, len) {
    txtCount = GetTextBoxCharacterCounter();
    txtCount.value = len - src.value.length;

    try {
      if (src.value.length > (len)) {
        if (txtCount.value < 0) {
          txtCount.className = "WarningTwitterLikeCounter";
          GetButtonTwitterLikeCounter().disabled = true;
        }

        return false;
      }
    } catch (e) { }

    txtCount.className = "NormalTwitterLikeCounter";
    GetButtonTwitterLikeCounter().disabled = false;
  }
</script>

The page markup code would be as below:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>ASP.Net & Javascript: Twitter like Multiline TextBox Counter</title>
  <style type="text/css">
    .NormalTwitterLikeCounter
    {
      border-color: White;
      border-style: none;
      font-family: Arial;
      color: #FF9900;
      background-color: #FFFFFF;
    }
    .WarningTwitterLikeCounter
    {
      border-color: White;
      border-style: none;
      font-family: Arial;
      color: Red;
      background-color: #FFFFFF;
    }
  </style>
</head>
<body>
  <form id="form1" runat="server">
    <asp:TextBox ID="TwitterLikeTextBox" runat="server" Columns="20" Rows="5" TextMode="MultiLine" onblur="SetTextBoxCharacterCounter(this)" onkeyup="return checkLength(this,100)">
    </asp:TextBox>
    <asp:TextBox ID="TextBoxCharacterCounter" runat="server" ReadOnly="True" Width="35px" CssClass="NormalTwitterLikeCounter">100
    </asp:TextBox>
    <asp:Button ID="btnTwitterLikeCounter" runat="server" Text="Twitter Like TextBox Character Counter" />
  </form>
</body>
</body>

The code for the 'ASP.Net & Javascript: Twitter like Multiline TextBox Counter' is pretty self explainatory and ofcourse you can modify the code for 'ASP.Net & Javascript: Twitter like Multiline TextBox Counter' according to your needs.

That's all, I hope you have got an idea of how to make a Twitter like Multiline TextBox Counter using Asp.Net & Javascript.



European ASP.NET 4 Hosting :: Sending Emails in ASP.Net with Gmail

clock July 12, 2011 06:41 by author Scott

This brief article demonstrates the simplest way and step by step instructions on how to send email from aspx page using a gmail account. After reading this you'll be able to send HTML formatted email messages by using Asp.Net and C#.

In order to send an email from gmail account programmatically, you have to include the following namespace:

using System.Net.Mail; // contains classes for SMTP settings, email sending etc

Let's take a look at the soure of aspx page. It has only three fields and a button to send email

<form id="form1" runat="server">
    <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address:"></asp:Label>
    <asp:TextBox ID="txtEmailAddress" runat="server" Width="300px"></asp:TextBox>
    <br />
    <asp:Label ID="lblEmailSubject" runat="server" Text="Subject of Email:"></asp:Label>
    <asp:TextBox ID="txtEmailSubject" runat="server" Width="300px"></asp:TextBox>
    <br />
    <asp:Label ID="lblEmailMessageBody" runat="server" Text="Email Message Body:"></asp:Label>
    <asp:TextBox ID="txtEmailMessageBody" runat="server" Rows="5" TextMode="MultiLine"
        Width="300px"></asp:TextBox>
    <br />
    <asp:Button ID="btnSendEmail" runat="server" OnClick="btnSendEmail_Click" Text="Send Email" />
    <asp:Label ID="lblEmailStatus" runat="server"></asp:Label>
</form>

Email Address: the address to which the email is to be sent
Subject of Email: The subject line of email and
Email Message Body: As we want to send HTML instead of simple plain text so whatever is placed in this field, will be formatted using html styles.

Pretty simple ... ok let's move to server side code:

protected void btnSendEmail_Click(object sender, EventArgs e)
{
    lblEmailStatus.Text = "";
    if (SendEmails())
        lblEmailStatus.Text = "Your Email has been sent";
    else
        lblEmailStatus.Text = "Error: Sending Email";
}

This is the event handler of Send Email button. It simply calls SendEmails() function and sets the status of label whether the email is sent successfully or not. Now lets look at SendEmail function:


private bool SendEmails()
{
    try
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(txtEmailAddress.Text);
        mail.From = new MailAddress("[email protected]");
        mail.Subject = "Sending Email from aspx: " + this.txtEmailSubject.Text;
        string Body = "<div style='font-family:Comic Sans MS; color:Navy; font-size:small'>" +
        "<br/>" +
        "<b>Email Date and Time:</b> " + DateTime.Now.ToString() + "" +
        "<br/>" +
        "<br/>" +
        "See the Following Email Message:" +
        "<br/>" +
        "<br/>" +
        "<b>" + this.txtEmailMessageBody.Text + "</b>" +
        "<br/>" +
        "<hr/>" +
        "</div>";
        mail.Body = Body;
        mail.IsBodyHtml = true;

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "email password");
        smtp.EnableSsl = true;
        smtp.Send(mail);

        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

First we will build the actual email message i.e. MailMessage, then configure the SmtpClient and send the email using that SmtpClient. One important thing: Gmail is using 587 of the host smtp.gmail.com

Rest the code is pretty simple and neat ... let me know if you have any questions regarding Sending email.

Another same tutorial, How to Send Email Using Gmail in ASP.NET



European ASP.NET 4 Hosting :: Select and Upload Multiple Files Gmail Style using JQuery and ASP.NET

clock July 6, 2011 07:45 by author Scott

In this article I am explaining how to upload multiple files by dynamically adding FileUpload controls using JavaScript.

Here I will explain how one can create a multiple file uploading controls in a very simple manner and very less amount of code. With this example one will able to perform the following functions

1. Add FileUpload Controls dynamically using JavaScript

2. Remove FileUpload Controls dynamically using JavaScript.

Since I am using JavaScript the UI becomes elegant since no need of postback or AJAX to add or remove FileUpload Controls.

Adding and Removing FileUpload Controls using JavaScript

Below is the HTML markup of the page. As you can see I have added a HTML button in order to add new FileUpload Controls, a DIV FileUploadContainer in which the dynamic FileUpload Controls will be added and a ASP.Net Upload Button in order to upload the files when the Upload Button us clicked.

An important think to note that you will need to add enctype="multipart/form-data to the form in order to allow the uploading of files through dynamic FileUpload controls.

<form id="form1" runat="server" enctype="multipart/form-data" method = "post">
    <span style ="font-family:Arial">Click to add files</span>&nbsp;&nbsp;
    <input id="Button1" type="button" value="add" onclick = "AddFileUpload()" />
    <br /><br />
    <div id = "FileUploadContainer">
        <!--FileUpload Controls will be added here -->
    </div>
    <br />
    <asp:Button ID="btnUpload" runat="server"
      Text="Upload" OnClick="btnUpload_Click" />
</form>

Now in order to add and remove the FileUpload Controls dynamically here is the JavaScript functions that are used.

<script type = "text/javascript">
var counter = 0;
function AddFileUpload()
{
     var div = document.createElement('DIV');
     div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +
                     '" type="file" />' +
                     '<input id="Button' + counter + '" type="button" ' +
                     'value="Remove" onclick = "RemoveFileUpload(this)" />';
     document.getElementById("FileUploadContainer").appendChild(div);
     counter++;
}
function RemoveFileUpload(div)
{    
document.getElementById("FileUploadContainer").removeChild(div.parentNode);
}
</script>

As you will notice above first I am creating a DIV element and then adding a HTML FileUpload Control along with a HTML Button in order to remove the FileUpload Controls. Also onclick of the Remove button I am calling the RemoveFileUpload function which removes the dynamically created FileUpload control. 

Server Side Uploading of Files

Server Side I have written the following code in the Click event of the Upload Button

C#

protected
void btnUpload_Click(object sender, EventArgs e)
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFile PostedFile = Request.Files[i];
        if (PostedFile.ContentLength > 0)
        {
            string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
            PostedFile.SaveAs(Server.MapPath("Files\\") + FileName);
        }
    }
}


VB.Net

Protected
Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs)
  For i As Integer = 0 To Request.Files.Count – 1
   Dim PostedFile As HttpPostedFile = Request.Files(i)
   If PostedFile.ContentLength > 0 Then
      Dim FileName As String = System.IO.Path.GetFileName(PostedFile.FileName)
      PostedFile.SaveAs(Server.MapPath("Files\") + FileName)
   End If
  Next
End Sub
 

In the above code snippet I am simply looping through the Request.Files Collection which contains the uploaded Files and then I am saving each of them one by one in a Folder called Files within my website root folder. 

Web.Config Configurations

Since this article deals with uploading multiple files it is important to discuss the maximum file size allowed. By default ASP.Net allows files of size maximum 4MB at a time. Hence in order to upload more data we will need to increase this limit. Refer the httpRuntime section of the Web.Config, if it is not present in your Web.Config you can simply paste the one given below in your file.

<httpRuntime
  executionTimeout="110"
  maxRequestLength="4096"
  requestLengthDiskThreshold="80"
  useFullyQualifiedRedirectUrl="false"
  minFreeThreads="8"
  minLocalRequestFreeThreads="4"
  appRequestQueueLimit="5000"
  enableKernelOutputCache="true"
  enableVersionHeader="true"
  requireRootedSaveAsPath="true"
  enable="true"
  shutdownTimeout="90"
  delayNotificationTimeout="5"
  waitChangeNotification="0"
  maxWaitChangeNotification="0"
  enableHeaderChecking="true"
  sendCacheControlHeader="true"
  apartmentThreading="false"
/>

In order to increase the maximum file size limit you will need to change the value of the maxRequestLength attribute in kilobytes (KB). For example if you want to set the upload limit to 10 MB you will have to set the value to 10240. Another important parameter is executionTimeout. It determines the maximum amount of time in seconds ASP.Net will process the request and after which it will stop the processing. By default the value is 110 seconds. You can modify it to the value that suits your needs



The above code has been tested in the following browsers



European ASP.NET 4.0 Hosting :: Using connection strings from web.config in ASP.NET v2.0

clock June 30, 2011 06:42 by author Scott

A typical web.config file in v2.0 could have the following section which is placed directly under the root <configuration> section.

<connectionStrings>
    <
remove name
="LocalSqlServer" />
    <
add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName
="System.Data.SqlClient"/>
    <
add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName
="System.Data.SqlClient"/>
</
connectionStrings>


connectionStrings>
    <
remove name=
"LocalSqlServer" />
    <
add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"
/>
    <
add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName
="System.Data.SqlClient"/>
</
connectionStrings>


You can reference this directly from code using:

[C#]
string connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;


[VB]
Dim connStr As String = ConfigurationManager.ConnectionStrings("MainConnStr").ConnectionString


Note that the namespace for this is System.Configuration so for a console application the full namespace is required.

Or you can reference this declaratively within the ConnectionString property of a SqlDataSource:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
 
ConnectionString
="<%$ ConnectionStrings:MainConnStr %>"
 
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]" />



European ASP.NET 4.0 Hosting :: How to Send Email Using Gmail in ASP.NET

clock June 16, 2011 06:55 by author Scott

If you want to send email using your Gmail account or using Gmail's smtp server in ASP.NET application or if you don't have a working smtp server to send mails using your ASP.NET application or aspx page than sending e-mail using Gmail is best option.

You need to write code like this

First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.

using System.Net.Mail;

Now write this code in click event of button

C# code

protected void Button1_Click(object sender, EventArgs e)

{
  MailMessage mail = new MailMessage();
  mail.To.Add("[email protected]");
  mail.To.Add("[email protected]");
  mail.From = new MailAddress("[email protected]");
  mail.Subject = "Email using Gmail";

  string Body = "Hi, this mail is to test sending mail"+
                "using Gmail in ASP.NET";
  mail.Body = Body;

  mail.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
  smtp.Credentials = new System.Net.NetworkCredential
       ("[email protected]","YourGmailPassword");
//Or your Smtp Email ID and Password
  smtp.EnableSsl = true;
  smtp.Send(mail);
}

VB.NET code

Imports System.Net.Mail

Protected  Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
  Dim mail As MailMessage =  New MailMessage()
  mail.To.Add("[email protected]")
  mail.To.Add("[email protected]")
  mail.From = New MailAddress("[email protected]")
  mail.Subject = "Email using Gmail"

  String Body = "Hi, this mail is to test sending mail"+
                "using Gmail in ASP.NET"
  mail.Body = Body

  mail.IsBodyHtml = True
  Dim smtp As SmtpClient =  New SmtpClient()
  smtp.Host = "smtp.gmail.com" //Or Your SMTP Server Address
  smtp.Credentials = New System.Net.NetworkCredential
       ("[email protected]","YourGmailPassword")
  smtp.EnableSsl = True
  smtp.Send(mail)
End Sub

You also need to enable POP by going to settings > Forwarding and POP in your gmail account


Change [email protected] to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.

If your are getting error mentioned below
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

than you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your web.config file

<system.net>

<defaultProxy>
<proxy proxyaddress="YourProxyIpAddress"/>
</defaultProxy>
</system.net>

If you are still having problems them try changing port number to 587

smtp.Host = "smtp.gmail.com,587";


If you still having problems then try changing code as mentioned below

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("[email protected]","YourGmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);

Hope this help!!



European ASP.NET 4 Hosting :: ASP.NET AJAX 4.0 Template Programming - Part II

clock June 4, 2011 06:23 by author Scott

This article is continuation of ASP.NET AJAX 4.0 Template Programming Part 1. In this part, I explain the different data binding options in ASP.NET AJAX 4.0 templates. Just a recap that I've consumed an ADO.NET data services to fetch AdventureWorks's Product table records. In this article, I explain how to update/add new record from client side.

Bindings

Template supports the following bindings:

- One-time - The expression is evaluated only once when the template rendering happen
- One-way Live Binding - The expression is evaluated and update the value, if items in the data source changed
- Two-way Live Binding - If the data source value changed, the value in the expression updated. And if the value in the expression is updated, it will update data source also.

The below diagram depicts the binding.



In the above diagram, the red dashed arrow shows one-time data binding. Once the data from data source has been fetched by DataView using AdoNetDataContext. The one-way live binding has been shown as purple shadowed arrow. The purpose shadow here is whenever a data updated at data source, it is being updated to data view through AdoNetDataContext. The two-way live binding has been shown as green shadowed two-head arrow. In this case, data context should have the knowledge about update operation on data source and provide an interface to data view to send the modified values.

The these three bindings, ASP.NET AJAX provides the following expression convention:

- {{ }} - One-time (can be used on any HTML controls for example <p>{{ Name }}</p>)
- { binding } - One-way if other than user input HTML controls for example <td>{ binding Name } </td>
- {binding } - Two-way if INPUT HTML controls for example <input type="text" sys:value="{{ binding Name }}" />

Here, the input controls binds the values using sys:value attribute for two-way binding. Before going into the updatable data source, let us see how can we design master-detail layout to display Product name and Product details.

Master-Detail Layout

<body xmlns:sys="javascript:Sys"
xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
  <form id="form1" runat="server">
  <div>
      <!--Master View-->
      <ul sys:attach="dataview" class=" sys-template"
          dataview:autofetch="true"
          dataview:dataprovider="{{ dataContext }}"
          dataview:fetchoperation="Products"
          dataview:selecteditemclass="myselected"            
          dataview:fetchparameters="{{ {$top:'5'} }}"
          dataview:sys-key="master"            
      >
          <li sys:command="Select">{binding Name }</li>
      </ul>

      <!--Detail View-->
      <div class="sys-template"
          sys:attach="dataview"
          dataview:autofetch="true"
          dataview:data="{binding selectedData, source={{master}} }">
          <fieldset>
            <legend>{binding Name}</legend>
            <label for="detailsListPrice">List Price:</label>
            <input type="text" id="detailsListPrice"
                sys:value="{binding ListPrice}" />
            <br />
            <label for="detailsWeight">Weight:</label>
            <input type="text" id="detailsWeight" sys:value="{binding Weight}" />
            <br />              
          </fieldset>
          <button onclick="dataContext.saveChanges()">Save Changes</button>
      </div>
  </div>
  </form>
</body>

Selectable And Editable

An unordered list shows the master details, here the product name (line 15). This line also indicates that the list item is selectable using
sys:command="Select". For maintaining master-detail or selectable item, primary key needs to be specified. The sys-key property of data view refers that primary key. In this example, I call the primary key as "master" (line 13). Also, you can see that I've passed a filter option using fetchparameter
property of data view (line 12). In this example, I request the ADO.NET data service to give only top five records using its filter syntax.

Whenever an item in the master list is selected, the details view needs to be notified. The widget for the details view and binding details should be identified using regular
sys:attach="dataview" and dataview's data property. In this example, dataview:data="{binding selectedData, source={{master}} }" specifies that binding with data view with sys-key name "master"
. The fieldset is used to show set of values for a product. Here, the list price and weight can be editable.

Once an item has been edited, this needs to be notified to the data source through data context. The button with caption "Save Changes" specifies that whenver this button is clicked, save the items in the details view into data source through data context's
saveChanges() method. The corresponding data source's update option should be set on data context's set_saveOperation()
. The following JavaScript code explains this.

var dataContext = new Sys.Data.AdoNetDataContext();
dataContext.set_serviceUri("AWProductDataService.svc");
dataContext.set_saveOperation("Products(master)");
dataContext.initialize();

The ADO.NET Product data service's Products(id) method is used on set_saveOperation. An item can be updated, when Product service of ADO.NET data service is being invoked with product primary key as argument. Here, again I'm referring master layout's "master" sys-key as primary key of Product.

The output of the above code is



The top one is master view where Sport-100 Helmet, Red is selected and the details has been shown in the bottom page. You can edit and update the data source.

The selecteditemclass property of data view is used to show the selected item in different style.

.myselected  {
        color: white;
        font-weight: bold;
        background-color: Silver;
      }



European ASP.NET 4.0 Hosting :: ASP.NET AJAX 4.0 Template Programming - Part I

clock June 2, 2011 05:27 by author Scott

Introduction

When Microsoft released its flavour of AJAX framework named "ASP.NET AJAX" as part of ASP.NET 3.0 preview, it did not have much competency when compared to other AJAX frameworks. But when I evaluated ASP.NET AJAX 4.0, I was really inspired with the new features that are completely focused on your browser technologies such as XHTML and JavaScript. I really admired the effort made by the ASP.NET AJAX team. There could not be any second opinion when you see the following features:

- Template based client side programming
- DataView and DataContext
- Live Data Binding

Template Programming

Template provides pattern to design a web UI form and enables to put placeholders for runtime data. For example, I've designed a web page to display AdventureWorks database Product data through ADO.NET data service. The entity model (edmx) is:



The service code is:

public class AWProductDataService : DataService
{  
    public static void InitializeService(IDataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
    }
}

By ASP.NET templates, the page looks like:

<%@ Page Language="C#" AutoEventWireup="true"

  CodeBehind
="ClientTemplateAndDataViewDemo.aspx.cs"

  Inherits
="CoreEnhancements.AJAX.ClientTemplateAndDataViewDemo"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Microsoft Tech.Ed - Client-side Templating Demo</title>
    <style type="text/css">
        .sys-template {display:none}
    </style>    
    <script type="text/javascript" src="../scripts/MicrosoftAjax.debug.js"></script>
    <script type="text/javascript" src="../scripts/MicrosoftAjaxTemplates.debug.js">
    </script>
    <script type="text/javascript" src="../scripts/MicrosoftAjaxAdoNet.debug.js">
    </script>
    <script type="text/javascript">
        var dataContext = new Sys.Data.AdoNetDataContext();
        dataContext.set_serviceUri("AWProductDataService.svc");
        dataContext.initialize();
    </script>
</head
>
<
body xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView"
  sys:activate="*">
    <form id="form1" runat="server">   
    <div> 
    <table border="1">
        <thead>
            <tr>
                <td>Name</td>
                <td>List Price</td>
                <td>Size</td>
                <td>Weight</td>
            </tr>
        </thead>   
    <tbody class="sys-template" sys:attach="dataview" dataview:autofetch="true"
    dataview:dataprovider="{{ dataContext }}"
    dataview:fetchoperation="Products">                
        <tr>
          <td>{binding Name }</td>
          <td>{binding ListPrice}</td>
          <td>{binding Size}</td>
          <td>{binding Weight}</td>
        </tr>
    </tbody>
    </table>
    </div> 
    </form>
</body>

I have used a typical HTML table for displaying the data. You can see some new attributes in <TBODY> and data place holders in <TD>. ASP.NET AJAX 4.0 has a dedicated template engine to parse these new attributes and data place holders. ASP.NET AJAX has defined a rich set of attributes and data placeholder patterns collectively called as expression language which are none other than X(HT)ML and JavaScript. Remarkable point here is its XHTML compliance, so these are not custom attributes in the regular HTML elements. The class attribute of the <TBODY> is set to sys-template, which is a convention used to hide the initial template from the user. .sys-template {display:none} The fields or properties of a data item which are needed to be rendered on data place holders can be expressed by {{ }} or { }.

DataContext

Template requires data for its place holders as contexts. The data context enables to bind any JavaScript array or objects to template. The real power of data context is to interact with JSON/ATOM based web services. ASP.NET AJAX provides two data contexts in MicrosoftAjaxAdoNet.js:

-
Sys.Data.DataContext

-
Sys.Data.AdoNetDataContext

The data context tracks all changes to the data automatically using new Sys.Observer object. AdoNetDataContext
supports additional features for ADO.NET data services such as identity management, links and association between entity sets. The below code sample describes how to interact with AdventureWorks Product's ADO.NET data service:

var dataContext = new Sys.Data.AdoNetDataContext();
dataContext.set_serviceUri("AWProductDataService.svc");
dataContext.initialize();

The set_serviceUri() method is used to interact with WCF AJAX or ADO.NET data service. The initialize()
method does initialization or invocation.

Data View

This is the fundamental component for templates to display data defined in
System.UI.DataView
. This is similar to server side data source component supports to bind any JavaScript object or array or to any ASP.NET AJAX component. It has two properties to bind a data set:

-
data
- To bind a JavaScript array or object
-
dataprovider - To bind to a WCF service

The fetchoperation property is used to set which method needs to be invoked for fetching data. In the code snippet 1, I've set the dataContext declared in code snippet 2 as data source. To run this application, refer to the following ASP.NET AJAX client side libraries:

- MicrosoftAjax.js
-
MicrosoftAjaxTemplates

-
MicrosoftAjaxAdoNet

The xmlns:sys declares the namespace Sys for the entire page (Code 1. Line 2). The xmlns:dataview declares DataView control. A data view instance has been associated with <TBODY> using sys:attach.

The following figure shows the conceptual model of the template programming:



The output code is:


 



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