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

Thursday, December 15, 2016

Abstract, sealed and various other C# related interview questions

Whenever I go into a technical interview, invariably I get asked one or more technical questions about the C# language itself so I thought I would share some of these with all of my readers in the event they also encounter these questions on their own interviews:


Tuesday, November 29, 2016

Get Started with Visual Studio Code

If you want to get started with development very quickly without the hassle of installing the full Visual Studio IDE (an hour long or more installation), then you should definitely check out Visual Studio Code!

Visual Studio Code installs in a matter of minutes similar to Notepad++ and offers extensions for C#, MSBuild, XML etc.

You can download Visual Studio Code from here: https://code.visualstudio.com/docs/?dv=win

You can then read more about how to use Visual Studio Code here: https://code.visualstudio.com/docs/editor/whyvscode

To demonstrate how easy it is to get up and running with Visual Studio Code to begin writing C# class files with Intellisense, you can check out the screenshots below:













In less than 5 minutes, I was up and running writing C# class files!  Cool, huh??

Friday, September 30, 2016

Expand or Collapse Regions in Visual Studio 2015

I frequently work with regions throughout my C# code, so I usually need to expand or collapse all regions in my code especially when I am refactoring code.

Therefore, I wanted to see if there was an easy way to accomplish this within Visual Studio.

Well, by default, Visual Studio uses the Edit-->Outlining menu to control the expanding and collapsing of regions:


However, there are some Quick Launch commands also available to you specifically while working with Regions!

These Quick Launch commands come to you courtesy of the Productivity Power Tools 2015: https://visualstudiogallery.msdn.microsoft.com/34ebc6a2-2777-421d-8914-e29c1dfa7f5d

Installing this extension adds Quick Launch items for "CollapseRegions" and "ExpandRegions":



In case you are not already aware, the Quick Launch menu appears in the top right hand corner of Visual Studio and allows you to search for various commands available to Visual Studio:



Thursday, September 15, 2016

Saving connectionString information to an Application Configuration file

If you use a library such as the Microsoft Enterprise Library Data Access Application Block, you may quickly discover that this library is dependent on configuration information stored in the Application Configuration file in order to properly load and function.

Therefore, if you want to implement dynamic functionality to switch database connection information at runtime, you will inevitably want to learn how to modify the Application Configuration file and subsequently save this information back!

Unfortunately, discovering how to accomplish this by searching on the Internet is not as easy as you might think!

I went through a large number of articles and forum posts all providing differing solutions to this common dilemma.

In the end, this solution worked for me:

The biggest difficulty with working with this solution was getting timing information to work properly within my Unit Tests to verify the file changes were being written out correctly. Ultimately, I could not get the timing perfected in my Unit Tests (even by using an Ordered Test) and I consequently gave up trying to succeed with running these changes within Unit Tests!

Wednesday, September 14, 2016

Configuring Enterprise Library for Visual Studio 2015

If you are using Visual Studio 2015 for your development, you may encounter a problem with downloading NuGet packages while running the install-packages.ps1 PowerShell script that comes with the Microsoft Enterprise Library 6 download (https://www.microsoft.com/en-us/download/details.aspx?id=38789).

Well, the reason this occurs is because Microsoft Enterprise Library 6.0 still ships with v. 2.0 of NuGet.exe!

Therefore, when it attempts to connect to the NuGet server, it inevitably fails!

So how do you resolve this issue?

First of all, go ahead and download the latest version of NuGet.exe from the NuGet distribution site: https://dist.nuget.org/index.html

Then, you need to place the latest version of the NuGet.exe executable in the .nuget folder that was originally created when you ran the install-packages.ps1 PowerShell script.

Now, when you re-run the PowerShell script, it should successfully download the NuGet packages!


Tuesday, September 13, 2016

Simplifying Condition-checking in C#

If you need to write a lot of "if" and "else" statements to check conditions in your code, then you definitely want to check out Cutting Edge Conditions!  https://conditions.codeplex.com/

Cutting Edge Conditions dramatically simplifies how to deal with condition checking throughout your code base using a Fluent API!

While Cutting Edge Conditions is a rather old library, it has been forked and is now being actively maintained on GitHub simply as "Conditions": https://github.com/ghuntley/conditions

You can download a NuGet package for Conditions from here: https://www.nuget.org/packages/Conditions/

One of the gaps in the code samples provided on the Conditions site, however, is the ability to display error messages when a particular condition is hit!

This can be simply be done by adding a description to the respective conditions as follows:

Wednesday, August 31, 2016

Implementing Remote Validation using Data Annotations in ASP.NET MVC

If you want to implement Remote Validation using Data Annotations on your ViewModels in ASP.NET MVC, you can follow this article: https://msdn.microsoft.com/en-us/library/gg508808(vs.98).aspx

Even though this article references ASP.NET MVC 3, it still applies to ASP.NET MVC 5.

In order to ensure that you do not encounter conflicts with the System.ComponentModel.DataAnnotations namespace while using the Remote attribute, you should decorate your ViewModels with the fully qualified namespace for the attribute in this manner:

[System.Web.Mvc.Remote("IsUID_Available", "Validation")]

Then, once you have the necessary appSettings configured in your Web.config (these are set by default in most ASP.NET MVC projects), you should be able to leverage your MVC Controller Validation code as follows:



IMPOTANT NOTE: The parameter to the Remote validation method should MATCH the attribute name in the ViewModel, otherwise, you will end up getting a null value passed to your Remote validation method!

This will then perform the validation via an AJAX call seamlessly within your ASP.NET MVC Web Application!

Thursday, August 25, 2016

Using Unity IoC with constructor parameters

I recently decided to switch my IoC container from Ninject to Unity for my ASP.NET Web API Web Application because the Ninject IoC container has poor support for Web API and has not been updated/refreshed in several years.

So, naturally, when I began switching my code over from Ninject over to Unity, one of the questions that immediately came up was how to use constructor parameters for my types in Unity?

Well, after doing some quick searching and experimentation, I came up with this solution:


It is as simple as that!

Monday, August 1, 2016

Using Ninject Extensions Conventions

If you are using Ninject, you may find yourself duplicating a lot of code for binding interfaces to their respective classes.

Fortunately, Ninject has a NuGet package which can take a lot of that tedious work away and bind interfaces to classes automatically!

The name of the Ninject package is called Ninject.Extensions.Conventions:



Once you have installed the NuGet package, you can add the following code to the RegisterServices method of your NinjectWebCommon.cs file:


That is all that is needed to get your Ninject project up and running!

Using Ninject with Generic Types

I have been using Ninject for years to bind Interfaces to Classes, or even Classes to instances of Classes, but I had never earlier bound a generic Interface to a generic Class!  In my case, I was creating a Generic Repository class and needed to bind it using Ninject.

After doing some searching through StackOverflow discussions, I came across this solution which worked well:



As you can tell from the above code sample, the only main difference in the code base is to use the typeof casting operator to get the generic type to resolve correctly!

Thursday, July 28, 2016

Implementing the Repository Pattern in C# with Entity Framework

If you are looking to implement the Repository Pattern in C#, you may find lots and lots and LOTS of conflicting solutions about how to implement the Repository Pattern in your own application.

If you just do a quick search just on MSDN, you will find articles such as the following:

https://blogs.msdn.microsoft.com/wriju/2013/08/23/using-repository-pattern-in-entity-framework/

http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

If you look through the examples above, you will see that they offer different solutions to the same Repository Pattern problem.  However, the second example provides the ability to create a Generic Repository which is much more appealing than creating a different repository for each class in your entire data model!

Unfortunately, the MSDN example lacks a definition of a generic interface which GenericRepository implements.  Looking at the code, you can derive your own IRepository interface, but the example still lacks support for a Dependency Injection or IoC container.  As you will readily notice, the example directly requires an implementation of SchoolContext to be created.  The way in which the example gets around direct creation of the SchoolContext is by using a Unit of Work class which handles the creation of this instance.  While the Unit of Work class can be useful in aggregating multiple repositories, it may not make much sense for instances when you simply need a single repository, which is why an IoC container is very useful!

So how exactly do you get Ninject to work in this scenario?

For Ninject, you simply use the following code to inject your SchoolContext instance:


You can simply add the following code to your RegisterServices method inside of your NinjectWebCommon.cs file and this should do the trick for you!

Tuesday, July 26, 2016

Setting a Default Value for a ViewModel using Data Annotations

In some cases, you may want to set a Default Value for an attribute in your ViewModel (or Model).  Of course, you can do this in your class constructor, but it is much easier and cleaner to set these values using Data Annotations!  This is especially true if you are already using Data Annotations to decorate your ViewModels.

You can do this readily using the DefaultValue Data Annotation as documented here: https://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(v=vs.110).aspx

If you do not use a constant value to assign a value for your DefaultValue attribute, you may encounter the following error message:


This is easily remedied though by simply assigning your value to a constant instead of a statically assigned property such as:

Ultimately, this ends up looking like this for your Data Annotation:

Friday, July 1, 2016

End of Life for Microsoft Enterprise Library Application Blocks...

I have been using the Microsoft Enterprise Library Application Blocks for years and years and recently I noticed for quite some time that these libraries have not been updated in years so I decided to go ahead and check out the CodePlex page for Enterprise Library to see if there has been any activity lately:  https://entlib.codeplex.com/

Of course, when I looked at the page, I was surprised to discover the following text:

This project is no longer under development.


Unity has new ownership and has relocated to GitHub.
The remainder of the application blocks will no longer be developed. However, the source will continue to be available. We encourage any interested parties to fork the source as desired.


Well, that is very unfortunate!  So, it seems that the Unity Dependency Injection Block would still be maintained but all of the other application blocks would be left to die off!!

In the past, I had heavily relied on the Logging and Exception Handling Application Blocks, but I may be switching to other frameworks such as ELMAH and log4Net now.  I will have to research what other frameworks might be available as alternatives to the Enterprise Library Application Blocks, but perhaps Microsoft at some future point in time will reconsider and develop these blocks once again for .NET Core!  I guess we can only cross our fingers and wait...


Thursday, June 30, 2016

Get XML Comments Path for documenting ASP.NET Web API

One common tasks for many projects is documenting their ASP.NET Web API projects using the Xml Comments in the project.

However, the default code in Web API does not know how to locate the Xml Comments file, so you have to write this custom code yourself!

You can easily add this code to your Web API by using the following code snippet:


Wednesday, June 22, 2016

Setting up configuration for AutoMapper

I began using AutoMapper for mapping my Domain Model objects to my ViewModel objects on a relatively recent project and when the same requirement once again arose, I grabbed the latest version of AutoMapper from NuGet and began using it.

Unfortunately, the latest release of AutoMapper deprecated numerous methods of performing mappings, therefore, I was left to determine how to follow the new method of creating mappings in AutoMapper.

After reading this article on AutoMapper's GitHub wiki (https://github.com/AutoMapper/AutoMapper/wiki/Configuration), I still could not figure out how to map multiple objects!

After doing some peer programming with a colleague, we were able to determine the solution to this dilemma as follows:


Mapper.Initialize(cfg =>
{
                cfg.CreateMap<Foo, Bar>();
                cfg.CreateMap<Bar, Foo>();
});

All that was required was to add an additional configuration for each model mapping that was required and surround the entire mapping configuration in curly braces ({})!!


Friday, June 10, 2016

Generating Entity Framework Code First POCO classes

Normally, when you think of Entity Framework Code First, you think that you have to generate all of your POCO classes completely by hand!

Fortunately, though, a clever developer has created the Entity Framework Reverse POCO Generator! https://visualstudiogallery.msdn.microsoft.com/ee4fcff9-0c4c-4179-afd9-7a2fb90f5838

If you are using Visual Studio 2013, you will also need to install the Entity Framework 6 Tools for Visual Studio 2013 from here: https://www.microsoft.com/en-us/download/details.aspx?id=40762

This Visual Studio extension allows you to generate Entity Framework Code First POCO classes directly from your database!

Unfortunately, all of the POCO classes are generated into a single class file, but you can then use a tool such as Resharper to extract the classes into separate C# files and then customize the generated POCO classes to ensure they match the design requirements of your system!

How neat is that??

Tuesday, June 7, 2016

Easily implementing Design Patterns into your C# code using PostSharp

If you want to easily implement common Design Patterns into your C# code, then look no further than PostSharp!

https://www.postsharp.net/features

PostSharp offers a "PostSharp Express Free" edition as well as a Professional and Ultimate edition: https://www.postsharp.net/purchase

In addition, if you are an open-source contributor or a Freelancer, you are eligible to get a Free PostSharp license.  Other organizations are also eligible for some significant discounts as well: https://www.postsharp.net/purchase/discounts

Tuesday, May 10, 2016

Setting the default value on a SelectList in ASP.NET MVC

If you have ever encountered the issue whereby you needed to set a default value on a SelectList (for a dropdownlist control), then you might be wondering how to accomplish this!

For example, if you have a SelectList like the following:


List<SelectListItem> selectList = new List<SelectListItem>() { new SelectListItem() { Text = "IN", Value = "IN" }, new SelectListItem() { Text = "MI", Value = "MI" } };

Then you may want to set a default value for the SelectList as follows:


public List<SelectListItem> GetSelectedValueList(List<SelectListItem> selectList, string selectedValue)
        {
            List<SelectListItem> newSelectList = new List<SelectListItem>();
            foreach (var item in selectList)
            {
                var selectListItem = new SelectListItem() { Text = item.Text, Value = item.Value, Selected = false };

                //if the selected item matches
                if (item.Value.Equals(selectedValue))
                {
                    selectListItem.Selected = true;
                }//if

                newSelectList.Add(selectListItem);
            }//foreach

            return newSelectList;
        }

Now when you pass in an existing SelectList, you will get it populated with a default value like so:

model.State = GetSelectedValueList(selectList, "MI");

return View(model);

That is all there it to it!!

Thursday, May 5, 2016

Using Data Annotations in ASP.NET MVC Web Applications

If you use Data Annotations for your ASP.NET MVC Model or ViewModel classes, it is often difficult to remember exactly which Data Annotations are available to decorate your classes!

Well, fortunately, Microsoft has created an MSDN article covering many of the commonly available Data Annotations for use on your classes:


System.ComponentModel.DataAnnotations Namespace
https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations%28v=vs.110%29.aspx


DataType Enumeration https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.datatype%28v=vs.110%29.aspx




Monday, April 25, 2016

Authorize.Net Error Message: (270) Line item 1 is invalid

I was recently working on using the SIM Authentication method with Authorize.Net, when I suddenly encountered the following error message:

Well, after I consulted the Authorize.Net SIM guide for Itemized Order Information, then I discovered that I needed to provide 5 values in each of my x_line_item values as follows:


paymentModel.x_line_item = string.Format("{0}<|>{1}<|>{2}<|>{3}<|>{4}<|>{5}", model.MembershipTypeID, model.MembershipType, model.MembershipType, 1, model.MembershipCost, "N");

That was all that was needed to fix my issue!