An Update On My ASP.NET Core Project

My previous post reviewed over utilizing ASP.NET Core to create a Web API endpoint. In that post, I stated that there was nothing as of that writing that prevented me from continuing the usage of ASP.NET Core and .NET Core. However, as time went on, it was decided to use OData. This is where my roadblock appeared. As of the writing of this post, OData support does not currently exist for ASP.NET Core. I’ve got a separate project that didn’t make sense to use OData, so we’re going with ASP/.NET Core for that project. I’m pretty excited about that, considering all the benefits I’d talked about in my previous post.

For those unfamiliar, OData (Open Data Protocol) is a standard that defines how to build and utilize RESTful APIs. This standard is utilized in the .NET world via the Microsoft.Data.OData Nuget package, and can be utilized in an ASP.NET project using the Microsoft.AspNet.OData Nuget package (both described in more detail here). With OData, a client can specify what data they would like returned via a query string or other parameter. This in turn is translated into a specific query that only returns the specified dataset. This is very useful for minimizing data traffic and ensuring the client gets what they need.

For the project in question, we had a project returning JSON data with multiple fields and child objects. The total payload, including all objects and fields, was over 600MB. For a mobile experience, this would be unacceptable. There would also be multiple clients requesting different pieces of this data at any given time. While the clients could receive the full payload, and just ignore the fields and objects they don’t need, this is a waste of traffic. I could also create different endpoints for each need, but that could become difficult to manage over time as more needs arise. OData gave us the opportunity to specify a generic endpoint, and allow the client to decide what data they receive.

Looking into OData support for ASP/.NET Core, I found nothing. Looking deeper into the documentation, I found the RESTier project. At face value, this seems to be utilizing a more ASP.NET Core approach to creating an OData endpoint. However, it is also not supported for ASP/.NET Core at this time. Perhaps some time in the future, this may change.

In the meantime, I’ve pulled that project over to a full .NET 4.6.2 and AspNet.Mvc 5.2.3 project. That process was not too difficult; I created a new ASP.NET MVC project, added the existing files to it, switched IActionResults to IHttpActionResults, changed NoContent() results to StatusCode(HttpStatusCode.NoContent) results, and swapped out the Core Nuget packages for full .NET packages and using statements. Overall, it wasn’t too painful, even if I’d rather avoid doing it again.

Thanks for reading!

Advertisements

Getting Started With ASP.NET Core

Over the course of the last month, I’ve had the opportunity to learn, experiment with, and implement a Web API project utilizing ASP.NET Core. While this has been a very edifying experience, I found that the details of the newer technology is a bit spread out across multiple sources. My aim of this post is to compile those details, describe how I’ve started out, and explain what’s available and possible.

The first thing that I’d like to review over is probably my favorite part of .NET Core as a whole: portability. Do you want to use the rich features of Visual Studio to develop your application? Great, that still works as before. Would you rather just pull up Visual Studio Code or other simpler editor to make changes, big or small, and then build the code easily? The dotnet CLI gives you that capability, along with being able to create new projects, run tests, publish, and others. Do you want to develop .NET software, but don’t have an installation of Windows? No worries – .NET Core can be installed on Linux and Mac.

Next, we tackle one of the concerns that I’ve had – dependencies. Many well-used Nuget packages simply aren’t compatible with .NET Core. One would think this is a deal-breaker, but that’s not quite the case. Many third parties, such as the xUnit team, have created a .NET Core-specific Nuget package to be used in this instance. As of the writing of this blog post, I’m successfully using xUnit 2.2.0-beta5-build3474 and xUnit.Runner.VisualStudio 2.2.0-beta5-build1225 (the runner is used to run the tests in Visual Studio’s Test Runner). These versions can be found in the Nuget Package Manager by checking the box to ‘Include prerelease’ packages, which is next to the search box. As further proof of this point, I’m also using NLog.Web.AspNetCore version 4.3.1 for logging, and Swashbuckle.AspNetCore version 1.0.0-rc3 to bring in the visual documentation tool Swagger UI.

For anyone who has created an ASP.NET/Web API project in the past, you may find that some namespaces have either moved, or are not implemented at all. An example of this is when pulling settings from a configuration file. With the full version of .NET, one may likely use ConfigurationManager. However, as Jonathan Danylko succinctly states here, it is not available in .NET Core. Not all hope is lost for configuration-file based settings – dependency injection can be used to pass around the settings (see his post on the matter, or the documentation, for more information). Thus far, I’ve found nothing of this nature that prevented me from continuing with the project. The pieces seem to all be there, and may just be implemented in a different way.

From logging to dependency injection, unit testing to data access, and many things in-between, ASP.NET Core has proven to me that it is a stable, reliable option to make cross-platform APIs. If you have a project coming up that could use flexibility, extensibility and mobility, and/or you would like to work with some really interesting technology, I recommend this stack to you.

How To Set Up Entity Framework 6 In ASP.NET MVC

In an effort to give back to this awesome community, I’m going to write on things that I’ve recently learned, and give ways to fix the problems that I ran into along the way. Without further ado, here goes…

Recently, I was working with fellow Improving Enterprises employee Nick Hunter on our MVC project, and had decided to use Entity Framework for our data storage and retrieval. We had used an MVC template in Visual Studio to start our project, which set us up with EF 5. As part of the Model View Controller (MVC) style, when properties are created in the model, Entity Framework automagically migrates that data into columns on a table that it creates. The way you tell EF what model to do this to is create a class that inherits from DbContext, and create DbSet properties.

As an example, say you’re making an MVC project that should list restaurants with location information, and also reviews for those restaurants with details. These two pieces of data should be in two different models and tables to keep everything organized. In this case, there would be a class called Restaurant and another called RestaurantReview in the Models folder. The Restaurant model would have properties for Name, Address, Phone Number, and possibly Category, among other things. The RestaurantReview model would have properties for ID that would refer to a restaurant, Rating, Details and others. Then a class should be created for the database context, so let’s call that PlacesToEatDb (I’m not great at naming things :P) and have it inherit from DbContext. Then set the following properties:

public DbSet Restaurants { get; set; }
public DbSet RestaurantReviews { get; set; }

After all that is done, new-up your PlacesToEatDb in your controller, and you’ll have a database that EF created to work with.

If you’re using current technology, this database was created in a new developer-focused database called a LocalDb. This is slightly different than SQL Express, in that it doesn’t run as a service; it runs on demand when you need it. When I first fired this up, it actually wasn’t working. I had to go to a command prompt and type SQLLocalDb Start v11.0, and then was able to connect to it.

Once you connect, you’ll notice that EF created two tables (named the same as the DbSets you created earlier) that already has columns populated (named the same as the properties in the models). If you want to have EF automatically change this whenever you add another property to the models, you’ll have to enable automatic migrations. This can be done by accessing the console in Visual Studio by selecting Tools->Nuget Package Manager->Package Manager Console. In this console, type Enable-Migrations –EnableAutomaticMigrations. You’ll then notice that a Migrations folder is created with a Configuration file in it. If you open this file, you’ll notice an EnableAutomaticMigrations flag. If everything was done correctly, migrations should automatically work when you add a new property to one of your models. If not, make sure that EnableAutomaticMigrations flag is set to true.

Also, if you wanted two different databases, you would create two different classes that inherit from DbContext. You can still have automatic migrations, but would need to specify -ContextTypeName when doing so. As an example, let’s say our project name is called PlacesToEat, and you created a different context for both the Restaurants and the RestaurantReviews. Your command would look like this: Enable-Migrations -ContextTypeName PlacesToEat.RestaurantContext.Configuration and Enable-Migrations -ContextTypeName PlacesToEat.RestaurantContext.Configuration (NOTE: for this path, make sure to use the periods instead of slashes. Slashes will not work.).

On some of these steps, we seemed to have ran into some glitches. To fix, we used Nuget to install EF 6 over EF 5. I wouldn’t recommend trying to uninstall it first, as the install of EF 6 takes care of this. Also, the uninstall will error out anyway, saying that some things depend on EF.

Well, that’s all I have for now. If you’d like more information, K. Scott Allen does a great job of explaining it in his Pluralsight course, which is currently free to view. Link: http://pluralsight.com/training/Player?author=scott-allen&name=mvc4-building-m1-intro&mode=live&clip=0&course=mvc4-building

Thanks for reading!

Learning New (And Secure) Tricks

Last time, I’d explained the start of my form, where I’m now adding items to a list and then adding those items to a checkboxlist. I also said in the last post that I wanted to give users the ability to delete items from the list in case any mistakes were made. This one actually wasn’t too hard to do, but it was difficult at first because I didn’t know the syntax to get it done.

On the event that the Remove button is clicked, I do a foreach loop through the checkboxlist. For each checkbox that’s selected, I remove the item from the list _items based on the checkbox item’s value. Note: when I first did this, I was trying to remove the items from the checkboxlist. That didn’t work, because every time the page reloads, all the items from _items repopulates the checkboxlist, so it just comes right back. It has to be deleted from the source for it to work.

void btn_remove_Click(object sender, EventArgs e)
        {
            ItemNumberRepository _myTempDatabase = new ItemNumberRepository();
            foreach (ListItem checkbox in UPCList.Items)
            {
                if (checkbox.Selected)
                {
                    _items.Remove(checkbox.Value);
                }
            }
            PopulateItemsList();
        }

At this point, I had the ability to add and delete. I’m done, right?… Wrong. Considering this information is pretty sensitive stuff, I wanted to be able to keep track of when items were added and by whom. Also, since two people were going to be keying this information in, I needed a centralized database for them both to add to. Thankfully, we had an instance of MS SQL that wasn’t being used heavily, so I started asking questions about how I can add my items to an SQL table. There’s some frameworks that help, but Matt Groves encouraged me to start humbly by using ADO.NET. That way I know exactly how it all works without being pampered by a framework.

I first started by getting a background of how and why ADO.NET was created. Wikipedia has a pretty good post about it, but I didn’t confirm the resources, so reader beware. I then took a look at the ADO.NET Overview on MSDN, which has many links to great resources that’ll teach about all you’d want to know about it. Also, a quick search through Pluralsight’s library can bring up many good examples and resources.

After wrapping my head around the fundamentals, I jumped in and started writing. I didn’t want to hit the database too much, so I decided to do a final submit that would send the entire list in one shot instead of sending each item individually. However, my boss wants me to have a backup in case the machine crashes in the middle of data entry, so I may go with adding individually if I can’t find a better solution. Enough about that though; on to the code! First, you need a connectionString that specifies what server and table to connect to. This can be put in the config of the project, but I’ve been lazy and just haven’t done it yet. Next, I do a for loop to run through all the items in the checkboxlist and run a command to add all the items into the table and add the account number that’s typed into the acctNum field on each field.

protected void final_submit_Click(object sender, EventArgs e)
        {
            string connectionString =
            "Data Source=server;Initial Catalog=table;"
            + "User Id=userid;"
            + "Password=password;";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                for (int i = 0; i < UPCList.Items.Count; i++)
                {
                    string acctnum = AcctNum.Text;
                    string finalSubmit =
                        "INSERT INTO Boxes (BoxNumber)"
                        + "VALUES (@boxnumber)"
                        + "INSERT INTO DestructionOrder (AccountNumber)"
                        + "VALUES (@accountNumber)";

                    SqlCommand command = new SqlCommand(finalSubmit, connection);
                    command.Parameters.AddWithValue("@boxnumber", UPCList.Items[i].ToString());
                    command.Parameters.AddWithValue("@accountNumber", acctnum.ToString());
                    command.Connection.Open();
                    command.ExecuteNonQuery();
                    command.Connection.Close();
                }
            }
        }

The variables @boxnumber amd @accountNumber are parameters that are passed in instead of the live data from the textboxes. This will stop people from being able to inject SQL into my form and mess around with my tables. More info about this and many other security issues can be found at Keith Brown’s ASP.NET Security Pluralsight course.

The insert here is pretty simple: you specify which table (Boxes) and which column (BoxNumber) the data (@boxnumber) should go into (FYI: The pluses(+) are necessary if you decide to put your query on more than one line. They’re not necessary if you put your entire query on the same line). After that, you have to open your connection, execute the command and then close the connection. I would explain why closing the connection immediately is necessary in more detail, but I think Keith Brown does an amazing job at it, so just go watch that.

Well, that’s it for this week. I’m writing this to help people out where I’ve struggled in the past, so if you know anyone that’s new to ASP.NET, webforms, or ADO.NET, please share this with them…and once again, thanks for reading!

Never fear, help is here!

Last time, I’d just realized I didn’t know enough to get the ball rolling on my new ASP.NET Web Forms project. I’d begun to watch some videos on Pluralsight and try to get associated with the fundamentals, but lost focus quickly and couldn’t retain very much information. I was going nowhere fast, and really needed to do well on this project so I could amaze my boss and company so I could get more opportunities in this field.

Considering going to school would’ve taken quite a bit of time (I’m still considering going anyway), I decided to ask for help. Utilizing all the contacts I had on Twitter, I put out a broad tweet for some help. I’d gotten replies from quite a few, but went with the first guy that I was most acquainted with, which was Matt Groves. He and I utilized Skype to speak to each other, and Join.Me for him to give me direct advice. I also received some help from Jonathan Stevens and John Nastase from CodeandCoffee, looked up some things myself, found answers on StackOverflow, and posted some questions myself. All this help and information went into making the application that I’ll be explaining in this post and some of the ones that follow. Without further ado, here goes…

I wanted to give my users the ability to add items to a list and then select and delete them if any mistakes were made. Through some searching, I’d found the CheckBoxList class, which is made of a list and check boxes beside each item that can select multiple items individually. This has to bind to a data source to display the items of that source, so Matt showed me how to add items to a list of strings and then return the items to the CheckBoxList to display them.

The following code shows the button click event for my add button on my form. On this event, I’m setting the text in a field of my form as a variable (so I don’t have to type FRCID.Text every time), then using Trim() to remove all the leading and trailing whitespace from the text input (just in case someone accidentally hits the spacebar when inputting). I then run some validation that makes sure the data being put in is exactly 8 characters long (won’t go into too much detail with this; let me know if you want more info and I’ll elaborate. I will say 2 things though: RegularExpressionValidator and JavaScript’s value.length).

void btn_submit_Click(object sender, EventArgs e)
        {
            var itemCode = FRCID.Text;
            itemCode.Trim();
            Page.Validate();
                if (Page.IsValid == false)
                {
                    Response.Write("Not enough characters");
                }
                string UpcCode = itemCode.TrimNullSafe();
                

Anyway, moving on. In the next area, I had an if statement that was checking for null or empty values. The ! before String.IsNullorEmpty means not, so this line can be read “if the string in FRCID.Text is not null or empty, then move on”. It then adds the item to the list _items and calls PopulateItemsList. In that, the checkboxlist is cleared (UPCList.Items.Clear()) as well as the textbox (I set FRCID.Text as an empty string, which empties the field, so the user doesn’t have to empty the field themselves to add in another item), a new list is created, and then a foreach runs through all the items in _items and adds them to the checkboxlist.

if (!String.IsNullOrEmpty(itemCode))
                {
                    _items.Add(itemCode);
                    PopulateItemsList();
                }
        }
        void PopulateItemsList()
        {
            UPCList.Items.Clear();
            FRCID.Text = string.Empty;
            if (_items == null)
                _items = new List(_itemNumberRepository.GetAllItems());
            foreach (var itemNumber in _items)
                UPCList.Items.Add(itemNumber);
        }

I clear the UPCList because the foreach will add the entire list in _items every time it runs. If I didn’t clear it, it would look something like this:

Type in 321321 -> click Add -> 321321 shows in checkboxlist
Type in 321322 -> click Add -> 321321, 321321, and 321322 shows in checkboxlist
Type in 321323 -> click Add -> 321321, 321321, 321322, 321321, 321322 and 321323 
shows in checkboxlist...and so on.

There’s also a few other things that has been done to this project, but considering this post is getting a bit long, I’ll hold off until next week. Please let me know if you have any questions or comments either here or on Facebook/Twitter…and once again, thanks for reading!

My First Real Project

About 9 months ago, I volunteered to out in small ways on some PHP web forms with good results. That led my boss to offer me an opportunity to write a web form from scratch. My company offers document destruction, and sometimes we get hand-written orders in. They wanted a form that would allow two employees to type in the information that’s on those hand-written list, and then for those lists to be compared to ensure that perception of hand-written characters is the same (from what I hear, they tried to convince all customers to type the orders with mixed results, hence the need for this). Thinking this didn’t sound too difficult, I accepted the offer and started to consider what I’d write it in.

At the moment, I’d only had a little usable experience in HTML and PHP, and neither of those seemed to be a good way of going about this at that time. Considering many of the people I’d met at that point were Microsoft developers, I decided to get into ASP.NET, so I’d have the best possible chance to get support from them. Even to this day, knowing what I know today, I don’t regret that decision. However, I believe a web form of this type could be made using HTML and PHP, so no hating there 😉

I’d fooled around for a bit with Visual Studio 2008 Express and got familiar with the layout, but by this point, two other versions had already come out. With that in mind, I installed Visual Web Developer 2010 Express (I usually wait awhile before using new software so most bugs can be ironed out, just to keep the experience smooth. If I start something new on a bad note, I generally get irritated and don’t follow through, so I wanted to avoid that). With that installed, I started a new ASP.NET Web Application.

New Project

When you start this type of project, it already lays out some default page elements. blog2
I actually didn’t know this when I did it, so I spent some time removing those elements to get the layout the way I needed (the layout was already decided, and looked nothing like what the default provides). However, if I’d looked 4 items down on the New Project list, I would’ve seen Empty Web Application, which is exactly what it says: it has no default page or elements. However, it does have a Web.config, a properties file and all the default references already added to the project.

I’d learned that ASP.NET projects can be written in many different languages. I’d decided to work with C#, again because many others around me were proficient in it, so I could receive help if needed. At this point, I hadn’t really done any programming in C# or really done any Object-Oriented Programming, so I spent some time on Scott Allen’s C# Fundamentals course, as well as Dan Brown’s Intro to C# and .NET. Although I didn’t watch these all the way through, they helped me to understand things much better. However, I was still far off from understanding enough to get moving on my own. I started looking for someone to help me, and found a lot of it…but I’ll explain that in more detail next week!

Hope you all had a great weekend, and have a good week! Thanks for reading!