Thursday, July 25, 2013

Getting a MAC Address with ASP.NET 4.0 and C#

Getting a MAC Address with ASP.NET 4.0 and C#

See More C# or Network ASP.NET Tutorials

Adding the Default.aspx PageTo view the MAC address we will be getting, we will need a simple web site that will allow us to display some data. At this point, I have created a new ASP.NET Empty Web Site and need to add in a Web Form with a label. To do this:
  1. Right click the project in your Solution Explorer.
  2. Select Add New Item…
  3. Select a Web Form.
  4. Name it Default.aspx.
  5. Click Add.
  6. Open Default.aspx up to Design mode.
  7. Drag and drop a Label onto the Web Form.
Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we’ve found so far.
Getting the MAC Address in C#Next, we need to add some code that will grab the MAC address from the current computer and display it on the web page. To do this:
  1. Open Default.aspx.cs up for editing.
  2. At the top of the class add the following using statement:
    Code Block
    Default.aspx.cs
    The using statement we need for accessing NetworkInterfaces.
    using System.Net.NetworkInformation;
  3. In the Page_Load event method add in the following code:
    Code Block
    Default.aspx.cs
    The code to display the MAC address.
    protected void Page_Load(object sender, EventArgs e)
    {
        //get all nics
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        //display the physical address of the first nic in the array,
        //which should correspond to our mac address
        Label1.Text = nics[0].GetPhysicalAddress().ToString();
    }
I just signed up at Server Intellect and couldn’t be more pleased with my fully scalable and redundant cloud hosting! Check it out and see for yourself.
Let’s review what this code is actually doing. First, we create an array of NetworkInterface objects and then populate that using the GetAllNetworkInterfaces method. Then, we display the physical or MAC address of the first NetworkInterface in the array which will correspond to your MAC address. Depending on your hardware you may want to use a different index of the array, however this will suffice for most machines.
mac address asp4 csharp

Add Data to GridView from Multiple Tables in ASP.NET 4.0 and C#

Add Data to GridView from Multiple Tables in ASP.NET 4.0 and C#

See More C# or Database ASP.NET Tutorials

When using the gridview control there are a few different ways that we can bind data to it. Here we will walk through the steps to databind a datatable to a gridview by populating a datatable with data from multiple tables within our database. To do this we will need to create a simple web site with a small database.
We chose Server Intellect for its cloud servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.
Adding the Default.aspx PageFirst, we want to add a simple web form to the project. At this point, I have created a new ASP.NET Empty Web Site. Next, we need to do the following:
  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a gridview control onto the web form
Adding the DatabaseNext, we need to add a database with two tables in it that we will use to populate the gridview with data. To do this:
  1. Right click the project in your solution explorer.
  2. Select add ASP.NET folder.
  3. Select App_Data.
  4. Right click the App_Data folder in your solution explorer.
  5. Select add new item…
  6. Select a Sql Server Database.
  7. Click add.
Now that we have a database, we need to add two tables to it with some sample data. To do this:
  1. Expand the Database.mdf folder in your server/database explorer.
  2. Right click the Tables folder.
  3. Select add new table
  4. Add the following columns with their respective types to the table:
     Column NameData Type 
     IDint 
     Datanvarchar(50) 
  5. Save the table as ‘Table1′.
  6. Right click the Tables folder.
  7. Select add new table.
  8. Add the following columns with their respective types to the table:
     Column NameData Type 
     IDint 
     Datanvarchar(50) 
  9. Save the table as ‘Table2′.
If you’re ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.
Next, we need to add some sample data to the tables. To Table1 add the following:
 IDData 
 1 T1 Temp data 1 
 2 T1 Temp data 2 
 3 T1 Temp data 3
To Table2 add the following:
 IDData 
 1 T2 Temp data 1
 2 T2 Temp data 2
 3 T2 Temp data 3
Adding the ConnectionStringNow that we have a database, we need to add a new connection string to it. To do this, open up the Web.Config file for editing and add in the following code between the <configuration> and <system.web> tags:
Code Block
Web.Config
The connection string.
<connectionStrings>
 <add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Adding Data to the GridViewNext, we need to databind our data from the tables to our gridview. To do this, we need to open up Default.aspx.cs for editing and add in the following using statements:
Code Block
Default.aspx.cs
The using statements we will need.
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
Next, we need to add the following code to the Page_Load event method:
Code Block
Default.aspx.cs
The Page_Load event method.
protected void Page_Load(object sender, EventArgs e)
{
    //data reader we will use to read data from our tables
    SqlDataReader rdr;
 
    //data table we will format and databind to our gridview
    DataTable dt = new DataTable();
    //add the 4 columns we will use to our table
    dt.Columns.Add("t1ID");
    dt.Columns.Add("t1Data");
    dt.Columns.Add("t2ID");
    dt.Columns.Add("t2Data");
 
    //datarow we will use to add new rows to our datatable
    DataRow dr;
 
    //connect to our db
    SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
 
    //send a sql command to select everything from the first table
    SqlCommand cmd = new SqlCommand("SELECT * FROM Table1", conn);
    cmd.CommandType = CommandType.Text;
 
    using (conn)
    {
        //open connection
        conn.Open();
        //read data from the table to our data reader
        rdr = cmd.ExecuteReader();
 
        //loop through each row we have read
        while (rdr.Read())
        {
            //create a new row in our datatable
            dr = dt.NewRow();
            //add data to our row
            dr["t1ID"] = rdr["ID"].ToString();
            dr["t1Data"] = rdr["Data"].ToString();
            //add row to the table
            dt.Rows.Add(dr);
            //update datatable
            dt.AcceptChanges();
        }
    }
 
 
    //get data from second table
    //connect to our db
    conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
 
    //send a sql command to select everything from the second table
    cmd = new SqlCommand("SELECT * FROM Table2", conn);
    cmd.CommandType = CommandType.Text;
 
    //a counter to keep track of which row we are adding data to
    int i = 0;
 
    using (conn)
    {
        conn.Open();
        rdr = cmd.ExecuteReader();
 
        //loop through each row we have read
        while (rdr.Read())
        {
            //add data to our row
            dt.Rows[i]["t2ID"] = rdr["ID"].ToString();
            dt.Rows[i]["t2Data"] = rdr["Data"].ToString();
            //increment our counter
            i++;
        }
    }
 
    //databind our datatable to our gridview
    GridView1.DataSource = dt;
    GridView1.DataBind();
}
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
This code will create a datatable object, populate it with the data from both of our tables, and then databind it to our gridview.
TestingTo test this out, go ahead and load up the web site. You should see something similar to this: 

bind gridview mult table asp4 csharp

ASP.NET Forums Website Part 3 Adding the Topic Page

ASP.NET Forums Website Part 3 Adding the Topic Page


Adding the Topic.aspx Page 
The next thing we need to do is add our page that will display the posts for a given topic. To do this, we will be pulling posts from our Posts table based on their associated TopicId. The way we will pass the TopicId to the Topic.aspx page is via a query string. To begin:
  1. Right click the project in your Solution Explorer.
  2. Select Add New Item…
  3. Select a Web Form and name it Topic.aspx.
  4. Ensure that the Select master page checkbox is checked and click Add.
  5. Select the MasterPage.master we added earlier and click OK.
Yes, it is possible to find a good web host. Sometimes it takes a while. After trying several, we went with Server Intellect and have been very happy. They are the most professional, customer service friendly and technically knowledgeable host we’ve found so far.
We will be using a repeater with a table in it, similar to what we did in the Default.aspx page to display links to all of the different posts on our page. To add the repeater, open Topic.aspx up to Design mode and:
  1. Expand the Data tab in your toolbox.
  2. Drag and drop a Repeater into the ContentPlaceHolder1 on the Web Form.
  3. Expand the Repeater Tasks Menu.
  4. In the Choose Data Source DropDownList, select <New Data Source…>.
  5. In the Data Source Configuration Wizard, select a Sql Database and click OK.
  6. It will now prompt you to choose your data connection, in the DropDownList select the ForumDBConnectionString we added earlier.
  7. Next, we need to configure the Select Statement, to do this select the Posts table from the Name DropDownList.
  8. Click the WHERE… to add a Where clause.
  9. Set the Column to TopicId.
  10. Set the Operator to =.
  11. Set the Source to QueryString.
  12. Set the QueryString field to id.
  13. Click Add.
  14. Click OK.
  15. Click ORDER BY…
  16. Set the Sort by DropDownList to PostDateTime and choose Descending.
  17. Click OK.
  18. Click Next.
  19. Click Finish.
We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect’s help, we were able to avoid any headaches!
Next, we need to format this repeater to output links to our posts in a table, as well as display who made the post and at what time. To do this open up Topic.aspx to Source mode and:
  1. In the Repeater tags, add the following code for the header:
    Code Block
    Topic.aspx
    The header.
    <HeaderTemplate>
        <table border="1" width="800px" cellpadding="5px">
        <tr>
            <td colspan="2">
                <a href="NewPost.aspx?id=<%= Request.QueryString["id"] %>">New Post</a>
            </td>
        </tr>
    </HeaderTemplate>
  2. Under the HeaderTemplate tag, add in the following code for the items:
    Code Block
    Topic.aspx
    The items.
    <ItemTemplate>
    
        <tr>
            <td>
                <a href="Post.aspx?id=<%# Eval("PostId") %>"><%# Eval("PostTitle"%></a>
            </td>
            <td>
                By: <%# Eval("PostUserName"%> @ <%# Eval("PostDateTime").ToString() %>
            </td>
        </tr>
                    
    </ItemTemplate>
  3. Under the ItemTemplate tag, add in the following code for the footer:
    Code Block
    Topic.aspx
    The footer.
    <FooterTemplate>
        </table>
    </FooterTemplate>
What this has done is setup a table with a header that links to a NewPost page and passes the TopicId as a query string. Then, we add in the ItemTemplate which will contain a column for a link to the Post page passing the PostId as a query string and displaying the PostTitle. Also, there is a column that displays the username and time the user posted it. Finally, we end the table tag in the footer.
At this point we need to test this out, but first we need to add some sample posts into our Posts table to be displayed on this page. For this, I am going to add in a few entries to the Post table, with a TopicId of 1 which corresponds to the General Discussion topic so that we will see them when we click the General Discussion link on our home page. To do this:
  1. Open up the Server or Database Explorer.
  2. Right click the Posts table and select Show Table Data.
  3. Add in the following entries:
    PostIdTopicIdPostTitlePostUserNamePostDateTime
    11Introductionsadmin1/1/2001 12:00:00 AM
    21Forum Guidelinesadmin1/1/2001 12:00:00 AM
    31Interesting Linksadmin1/1/2001 12:00:00 AM
If you’re ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.
Now that we have some content, let’s test this out. Go ahead and load up the Default.aspx page and click on the General Discussion link. You should be linked to your Topic.aspx page that looks similar to this: 
 
This is pretty much it for the Topic page, next we need to create the Post page that the posts link to. 
ASPdotNET Forums Website Tut