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

Latest Posts

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, July 29, 2021

 In this post we are going to create our first Entity Framework migration and creating an actual database in MySQL. 

In order to do that we need to add a few NuGet packages to our Asp.Net Core project including the Entity Framework Core package.  But, before we do that we want to find out what what version of .NET Core we are running.  Obviously I have it memorized, but for the rest of you, you can type the command dotnet --version to figure out what the version is :)  It's always a good idea to try and match the package version with the .NET Core runtime you have.  It's one of the more annoying thing with Angular and Asp.Net Core, it's changing constantly. So as you can see my version 3.1.xxx so I should try to install packages that are made for 3.1.x.

The first package we are going to install is the Microsoft.EntityFrameworkCore.  So open the ACMEBank.API project with Visual Studio Code.  Press Ctrl+Shift+P and type NuGet and select

Thursday, July 8, 2021

Before we run our Asp.Net Core application for the first time we are going to copy a controller from Asp.Net Core 2.2 to help us create the skeleton for our application.  A skeleton are the plumbings we do at the beginning of our application to make sure all the mechanisms work.  It's called the ValuesController which has been replaced with a more complicated WeatherForecastController.  The ValuesController is just a lot easier to work with to get things set up.


Just create a new controller in the "Controllers" and call it "ValuesController.cs" Here is the code for it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace ACMEBank.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

Thursday, July 1, 2021

 For those of you who works with Visual Studio, working with C# comes out of the box, but with Visual Studio Code you need to install some extensions from the Marketplace to make it suitable for C# development.  

Here are the extensions you need to install:

  • C#: This extension by Microsoft gives us IntelliSense, references, code editing and highlighting and debugging support

  • C# Extensions: This extension let's you create C# files, like classes and interfaces also some keyboard shortcuts like creating.  This one seems to be no longer in development for a long time, but it works fine.

  • NuGet Package Manager: This extension let's us install new NuGet packages which we will need from time to time.

Wednesday, March 22, 2017

In the previous blog we created the NorthwindCafe database with Entity Framework Core.  Now we are going to seed the database so that we can work with the data.

Here are the steps to seed the NorthwindCafe database:

1.  Create a file call DBInitializer in the NorthwindCafe.Web folder, in the file type in the following code


using System.Linq;

namespace NorthwindCafe.Web.Models
{
    public class DbInitializer
    {
        public static void Initialize(NorthwindContext context)
        {
            context.Database.EnsureCreated();

            if(context.Categories.Any())
            {
                return;
            }

            var categories = new Category[]
            {
               new Category {Name = "Coffee", Description="Coffee", Products = new Product[] { new Product { Name = "Dark Roast", Description = "Dark Roast", Price = 2.0M } } },
               new Category {Name = "Tea", Description="Tea", Products = new Product[] { new Product { Name = "Chai", Description = "Chai", Price = 1.5M } } },
               new Category {Name = "Pastry", Description="Pastry", Products = new Product[] { new Product { Name = "Cupcake", Description = "Cupcake", Price = 1.25M } } },
               new Category {Name = "Food", Description = "Food", Products = new Product[] { new Product  { Name = "Hamburger", Description = "Hamburger", Price = 5.0M } } }
            };

            foreach (var c in categories)
            {
                context.Categories.Add(c);

            }

            context.SaveChanges();
        }
    }
}


Monday, July 18, 2016

In the previous post we have enabled MVC on our application.  Now we want to add our first MVC controller and view to test out verify that MVC is working.  We also have to tell ASP.NET Core what pattern to look for when looking for our controllers and views.


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>


Namespace:

System.Collections.Generic

Declaration:

Dictionary<string, string> account = new Dictionary<string, string>();

Adding Items:


account.Add("id","1");
account.Add("username", "jackd");

Use in ArrayList: Namespace:

Saturday, June 18, 2016

In our previous blogs we've created an ASP.NET MVC from scratch.  In this blog we are going to use Entity Framework as the ORM (Object Relational Mapping) as a conduit to our database, so that we can query our data as an object.  An ORM as the name implies maps database tables, views, and stored procedures as objects in a programming language so that developers can work with the data as objects.

Step-by-Step Instructions:

1.  First we need to add the Entity Framework 6.1.3 to our ASP.NET MVC, we accomplish by right-click on "References" then select "Manage NuGet Packages"

Thursday, March 26, 2015

There are times when you see a class property without it's private member counterpart and all you see is the {set; get;} accessors. What you are looking at are auto properties that you can create  in C#, the only requirements is that the set; and get; accessors contains no logic.  Usually there are private members that the properties expose to other classes using the get/set accessors, like the code below:


    public class Product
    {
        private int productId;
        private string name;
        private string description;
        private decimal price;

        public int ProductId
        {
            get
            { return productId; }
            set
            {
                productId = value;
            }
        }

        public string Name
        {
            get
            { return name; }
            set
            {
                name = value;
            }
        }

        public string Description
        {
            get
            { return description; }
            set
            {
                description = value;
            }
        }

        public decimal Price
        {
            get
            { return price; }
            set
            {
                price = value;
            }
        }

    }

Sunday, March 15, 2015

log4net is the most commonly used ASP.NET logging package.  It is robust and flexible in it's features.  You can choose to log your errors on the database or in a log file or multiple log files.  However, it is not as straight forward to set up.  In this blog we will go through the steps to install log4net using NuGet Package Manager.

1.  Create an empty web project, and call it whatever you like, below is the settings that I have, then click "OK"




2. Right click on the solution and select "Manage NuGet Packages for Solution..."


3.  Locate the search box on the left hand side


4. Type "log4net" in the search box, the latest log4net version will show up in the search results in the main window.  Click on the "Install" button.



5.  Select the project that you want log4net to be installed, then click "OK"


6.  After the installation under "References" log4net will be added

7.  

Monday, March 9, 2015

In the last blog we just selected the Products entities from the NorthwindEntities with this Linq Query.

var query = from prod in nwctx.Products
         select prod;

It gets the job done but, the GridView displays the CategoryID and SupplierID as integers, which is not very useful to your users. Plus, we don't want to display the ProductID.












Thursday, February 19, 2015

Arrays are fixed size elements of a type, arrays are stored next to each other in the memory. Making them very fast and efficient.  However you must know the exact size of an array when you declare an array.

Declaring an array:
string[] names = new string[5];
There are two ways you can assign values to an array. The first is to assign the values individually by specify the index of the array inside a square bracket. The index is the position of element in the array. Index starts with 0.
names[0] = "George";
names[1] = "James";
names[2] = "Arthur";
names[3] = "Eric";
names[4] = "Jennifer";

Thursday, February 12, 2015

This is part three of our series on Entity Framework. In the last blog we went over how to create an Entity Framework model with the Northwind database. Now we are going to use that model in our ASP.NET by binding the Entity objects that have created to a GridView in our "Northwind" ASP.NET project. Usually we would put the Entity Framework model in a class library project and use it as our data access layer, but for simplicity I've decided to put in the same project as the ASP.NET pages.

Below are the directions on how to use the Entity objects in our web pages.

1. Create "Default.aspx" page in the "Northwind" web project.



Tuesday, July 22, 2014

The RadioButtonList displays a collection of radio buttons on a web page. There can only be one selection in a group of choices at a time. In this tutorial we will create a RadioButtonList and then bind it to the Categories table of the Northwind database using a DataTable.

To create a RadioButtonList control do the following:

1.  Select the "RadioButtonList" control under the "Standard" control in the "Toolbox" pane on the left.

Monday, July 21, 2014

In this part of the tutorial we will bind a DropDownList control to a list of objects.  This common practice if you are working with business objects that are mapped to the database table.  We will create a business object call "Category" and create a list call "categories" in our .aspx page.


One of the most commonly used server controls in ASP.NET is the DropDownList control.  In this blog I will show you how to bind a list of objects to a DropDownList control.

1. Create a .aspx page
2. Click on the "Toolbox" panel

Friday, July 18, 2014

The RadioButtonList displays a collection of radio buttons on a web page. There can only be one selection in a group of choices at a time. In this tutorial we will create a RadioButtonList and then bind it to the Categories table of the Northwind database using a DataTable.

To create a RadioButtonList control do the following:

1.  Select the "RadioButtonList" control under the "Standard" control in the "Toolbox" pane on the left.

Thursday, July 17, 2014

If you work on the DropDownList control, eventually you will be asked to populate some sort of data grid based on the selection on the list. The most common control you have to populate is the GridView control. This tutorial builds from part 1 and part 2 about DropDownList control. So make sure you go through those blogs before you start this one. In this tutorial we will learn how to populate the GridView via a DropDownList selection.

 1. Select the "GridView" control from the "Toolbox" pane on the left




Wednesday, July 16, 2014

In part one DropDownList Part 1: Bind a DataTable to A DropDownList we learned how to bind a DataTable to a DropDownList.  In this tutorial we will learn to set the default value of the DropDownList control on the page's first load that is before there is a post back to the page.  This behavior is commonly used when you want to default the drop down list to a particular selection.  Such as the "United States" in a list of countries drop down list.

To set a default value in the DropDownList control follow the steps below.

1. Add the SetDefaultSelectItem method to the code behind file.
protected void SetDefaultSelectItem(string txtSelect)
{
   DropDownList1.Items.FindByText(txtSelect).Selected = true;
}

2. Add a condition to only set the default value on the first page load
protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        BindCategoriesList();
        SetDefaultSelectItem("Seafood");
    }
}
3. If you run the application you will now see that "Seafood" is the default selection on the DropDownList control, when the page first load
Default DropDownList selection




Related Blogs:



  1. Bind a DataTable To A DropDownList
  2. (DropDownList) Setting Default Value on First Page Load
  3. Use The DropDownList Control To Populate GridView
  4. Bind DropDownList To A List Of Objects

Tuesday, July 15, 2014

One of the most commonly used server controls in ASP.NET is the DropDownList control.  In this blog I will show you how to bind a DataTable to a DropDownList control.

1. Create a .aspx page
2. Click on the "Toolbox" panel

Thursday, September 5, 2013

In this blog we will go over how to query an Oracle database in ASP.NET using the System.Data.OracleClient data provider in C#.

Namespaces:

using System.Web.Configuration;
using System.Data.OracleClient;
using System.Data;

            string cs = WebConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString;

            using (OracleConnection oc = new OracleConnection(cs))
            {
                oc.Open();
                DataTable dt = new DataTable(); 
                OracleCommand ocmd = new OracleCommand("SELECT * FROM SOMETABLE", oc);
                OracleDataAdapter oda = new OracleDataAdapter(ocmd);

                oda.Fill(dt);

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

            }
Previous: Oracle Date Format And Compare

Search This Blog