Tech Junkie Blog - Real World Tutorials, Happy Coding!: ASPNET

Latest Posts

Showing posts with label ASPNET. Show all posts
Showing posts with label ASPNET. Show all posts

Saturday, August 31, 2019

When you need to do an insert into multiple database table you need to the get the ID of the insert so that you could use that ID for the next insert. Here is how you would do that with the Scope_Identity()which gets the last inserted ID back to you if you execute your query with the ExecuteScalar() method.

                SqlCommand cmd = new SqlCommand("INSERT INTO Users (" +
                    "LoginName," +
                    "FirstName," +
                     "LastName," +
                     "Password," +
                     "Email," +
                     "DOB," +
                     "Sex" +
                     ") VALUES (" +
                    "@Email," +
                    "@FirstName," +
                     "@LastName," +
                     "@Password," +
                     "@Email," +
                     "@DOB," +
                     "@Sex)" + 
                     " Select Scope_Identity();",conn);


Monday, August 1, 2016

In this tutorial we will add icons to your navbar.  In the previous tutorial we added a responsive layout with bootstrap.  In this post we will add some icons to your navigation.  Font-Awesome gives you professional looking vector graphics, which are implemented using CSS.  Bootstrap will use Font-Awesome as it's icons starting version 4.0 and beyond. Glyphaicons will go away. So we might as start using it, in anticipation of Bootstrap 4.0.

Friday, July 15, 2016

In this post we will go over the process of enabling ASP.NET MVC in our application.  Just like static files, in order for us to use MVC in our application we have to tell ASP.NET Core to use Mvc in the Startup.cs file.  We will continue to use the application "NorthwindCafe" that we used in our previous blog.

Here are the steps to add MVC to your application:

1.  Open the Startup.cs file, then in "ConfigureServices" method type in the following to enable MVC

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

Sunday, June 19, 2016

Suppose you have an enum type like the one below, and you want to bind the enum type to a DropDownList control in a Web Forms application.  How would you do this?  There's an easy way to do this with just a few lines of code.  You'll be amaze at how simple it is.

First of all here is our markup code in our .aspx page

<%@ Page Language="C#" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="Sandbox.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    </div>
    </form>
</body>
</html>


The GridView data grid control is probably the most popular and flexible data grid control in the ASP.NET arsenal.  In this tutorial we will create a new GridView data grid on a web form.

Here are the steps:

1. Click on the "Design" tab in main window of Visual Studio


string dobStr = ddlMonth.SelectedValue + "/" + txtDay.Text + "/" + txtYear.Text;
SqlParameter dob = new SqlParameter("DOB", Convert.ToDateTime(dobStr));
dob.SqlDbType = SqlDbType.Date;
cmd.Parameters.Add(dob);

Next: ASP.NET: Getting The Inserted ID Back With Scope_Identity()

In this blog we will get the current page file name that the user is currently on.

string[] currentUrl = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
string pageFileName = currentUrl[currentUrl.Length-1];

In this example we will use the SqlDataAdapter to fill a DataTable then bind the data to a GridView

 1. Drag a GridView into your ASP.NET page

2. Use the following code to the fill the dtProducts DataTable with the adapter SqlDataAdapter, then bind it to the GridView1 control.


        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dtProducts = new DataTable();

              string connString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

              using (SqlConnection conn = new SqlConnection(connString))
                {
                    SqlCommand cmd = new SqlCommand("SELECT * FROM Products", conn);
                    conn.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(dtProducts);

                    GridView1.DataSource = dtProducts;
                    GridView1.DataBind();

                }
        }


Next: SqlDbType.Date

The Categories table is a perfect example of how sometimes you have to populate the DropDownList control to data from the database. In this example we will populate the DropDownList control to the Categories table in the Northwind database.

 1. Drag the DropDownList control into a .aspx page.

So you have following connection string to the Northwind database in your Web.config and you want to connect to the database in the code behind instead using query builder.

  <connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.
SqlClient"/></connectionStrings>

Here is how you would do it

1. Get the connection from the Web.config file programmatically, you can look at this blog to find out how perform this step by step.  But here is the code to get the connection string from the Web.config file

string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

Out of the box the ASP.NET provider databases works with the local database file call aspnetdb.mdf, however in a production environment you cannot use this file because you need to work with the production database. To create the provider databases on a full version of SQL Server perform the following steps.

1. Navigate to the .NET Framework version that you want to use. Version 4.5 and Version 2 has the provider database wizard. I am using version 4.5 so the path is C:\Windows\Microsoft.NET\Framework\v4.0.30319

2. Double click on the file aspnet_regsql.exe, the ASP.NET SQL Server Setup Wizard will apear, click "Next" to continue

So you have to work with multiple connection strings that you want to use in the Web.config file and you want to use it in the code behind file.    Below are the steps to retrieve multiple connection strings in the web.config file programmatically.

1. Make sure you have connection strings in your Web.config file.  A connection string looks something like this.

  <connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True"
      providerName="System.Data.SqlClient" />
    <add name="AdventureWorksConnectionString" connectionString="Data Source=(local);
Initial Catalog=AdventureWorks;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>


So you have a connection string that you want to use in the Web.config file and you want to use in the code behind file.  You can do that with a single line of code in your .cs file.  Below are the steps to retrieve a connection string in the web.config file programmatically.

1. Make sure you have a connection string in your Web.config file.  A connection string looks something like this.

  <connectionStrings>
    <add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True" 
providerName="System.Data.SqlClient"/>
  </connectionStrings>


The SqlDataSource control provides you with a quick and easy way to access database data.  Most of the time you don't even have to write a single line of code.  Now this can a be a good thing and a bad thing, depends on how you look at things.  Most of the configuration and querying is performed via a configuration wizard.

Here are the steps to creating a SqlDataSource:

1. In a ASP.NET project/web site drag a SqlDataSource control in under "Data" in the "Toolbox" tab into a .aspx page.

In my previous post we've created the Northwind products page using the SqlDataSource data control, even though there's nothing wrong with the solution.  SqlDataSource is a an old technology and is not meant to be an enterprise solution.  SqlDataSource is the stone age of .NET data access technology.  The future of .NET is the Entity Framework.

The goal of the Entity Framework is to create a conceptual model of your data store so that you can work with tables and rows as objects, or entities.  In essence the developer does not know or care what the data store is, he does not have to be a dba to work with the data.

To demonstrate the Entity Framework let's create the Northwind products page using the Entity Data Model of the Northwind database.

Here are the steps:

1. Open the Northwind project you created with the SqlDataSource

You can use Visual Studio for all of your web server needs for local development, but it's essential that you familiar yourself with a full blown IIS version.  In this tutorial I will show how to install IIS on a Windows 7 machine.

1. Open the "Control Panel"

2. Select "Programs and Features"

I could go on, and on about ASP.NET features and how awesome it is, but most of the time you come to a blog to learn about real world situations.  So why not create a web application base on the Northwind database.

Just from looking at the database tables we know that we could divide the web site into two sections. The e-commerce side of the business and then the internal side of the business. So the e-commerce site deals with the products are being offered by the Northwind corporation, and the internal side of the site deals with the sales team and the employees.

If you look on the web you will eventually find an example that refers to the Northwind sample database in one of the their examples.  What they fell to tell you is where to find this sample database and how to add to your database.

Follow these steps to add the Northwind sample database to your SQL Server:

1. Go the URL http://www.microsoft.com/en-us/download/details.aspx?id=23654 and download the Northwind and pubs sample database from Microsoft.

The purpose of this blog is to show you the bare bones of ASP.NET.  Often times when you search for a tutorial on the web you see that the tutorials are way too complex or an overkill of what you are trying to do at that moment.  So the in this blog series I want to cut through all the fat and just show you how to get things done quickly.

The best way to start an ASP.NET web application is to create an empty project.  In this tutorial I will show you how to create an empty web application project in Visual Studio 2012.

You can download Visual Studio 2012 at http://www.microsoft.com/visualstudio/eng/downloads#d-2012-editions  you can get a 90 trial by registering with microsoft.com.  Another alternative is to download the free Visual Studio Express version at http://www.microsoft.com/visualstudio/eng/downloads#d-2012-express 

Saturday, June 18, 2016

A lot of people think that you can only create one kind of ASP.NET MVC  project, the one with the sample application.  But the reality is that you can create an Empty ASP.NET MVC, you just need to do more work.  However, it is cleaner and you can add what you need, instead of having everything in place already like the default template.  So you might run into more errors with the empty project, but I think you will learn more about MVC than if you just have the default template.  Plus it's more streamline.  I always start with an empty project on my MVC projects.  In order to follow this tutorial you must have Visual Studio 2017 installed.

Search This Blog