Moving Sites

Hello fellow bloggers and subscribers. It has come time in my blogger life as many do, to upgrade from the free WordPress.com site to a hosted solution due to traffic increases and lack of plugin support.

Over the next few days, I will be migrating my site. During this time, there may be a few hiccups where you may either get duplicate emails or links will not work as expected. I will do my best to make this as smooth a process as possible, but as anyone in technology knows, thing rarely go that way. If researching on WordPress migration, all my subscribers should be able to still get content if you are a subscriber via email. If you are a WordPress specific subscriber, you will need to resubscribe to get updates.

I apologize in advance for any inconvenience this may cause, and look forward to providing the best content to my viewers as my blog progresses. Thank you for everyone’s support!!

 

As always, Happy Coding 🙂

Advertisements
Posted in .NET, C#, Classes, Uncategorized | Tagged , , , | Leave a comment

New FREE .NET Training

Hello readers!

I wanted to let everyone who subscribes to my blog ( and those visiting for the first time) that there is a new You tube channel I have created tailored to your needs as .NET developers.

Who is this channel for?

Good question. This channel is for EVERYONE! I am in the middle of uploading videos for a series on ASP.NET MVC from beginner to advance lessons. Click Here.You will learn what MVC means, why it’s a great design pattern, as well as how to implemented it in the best way for excellent performance and future proofing your project code maintenance.

We also have a series for those of you just getting into the C# .NET space. Even for beginning programmers that haven’t touched code before. All you need is Visual Studio Express and the aptitude to LEARN! Click HERE to visit that series.

The playlists are constantly growing and so is what is in them. The best part about these tutorials is that they are based on real live scenarios. So you will never say ‘you must do it this way’ or ‘this is the proper way to do something’. The reason for this is that I write and do videos based on REAL LIFE Experience. Not textbook answers or solutions.

So join me in my journey as we explore together the .NET possibilities!!

Posted in .NET, .NET 4.5, ASP.NET, C#, Classes, Controllers, Generics, MVC, Uncategorized, Validation, Views | Tagged , , , , , , , , , , , , | Leave a comment

Understanding LINQ to SQL and IQueryable / IEnumerables C# .NET

I am often asked what the difference is between IQueryable, IEnumerable and LINQ. This is a loaded question, but I will try my best to explain it in this blog. This blog will focus mostly on each from a database point of view but we will NOT be going over using any ORM providers such as Entity Framework.

What exactly is an IQueryable and LINQ -> SQL?

Well, that’s a great question. An IQueryable actually extends IEnumerable which means that it can do iterations (for each loops) in the same way that IEnumerable can. IQueryable is very often used to build up queries to be used to call a database. Since an IQueryable is an in memory query (in other words has not been executed to the database yet, you can chain filters to the queryable before it executes.

For example, if you wanted to do a select on a product by it’s name, you would build the select query and then the where clause (filter) using LINQ to SQL (now known as LINQ to Entities).

Note: An IQueryable is NOT calling the database. To call the database you must turn it into a concrete object! If you do a .ToList() at the end of your query, that will make the call to the database. Until then it is just a string SQL statement in memory. Common functions that will trigger a call to the database are Where(), ToList() and Select().

 So what is and how do you use LINQ to SQL

LINQ to SQL (LINQ to Entities) ORM (Object relational mapping) is a query language build within the .NET framework which provides the developer the ability to query a database without having intimate understanding of the TSQL language. This is done by providing a programmatic syntax (using Lamda expressions) similar to C#. This code then gets compiled down into a query which can be sent to the database and return the results to the developers code.

A very basic example would be something like this. Suppose you have a database structure similar to the one below. A pretty simple ordering database schema. The Products table is the main system and you will notice that there is a one to many relationship between Product and Category.

linq-sql-diagram

Now, with the given diagram above, you can use LINQ to query the database using entity framework (I will not be going into the intricacies of EF at this time). If anyone comments below that they would like me to, I certainly can.I will also be doing many intro courses on my you tube channel if you are interested.

Here is a great image that explains what each syntax keyword means.

linq-query-syntax

Reference: TutorialsTeacher.com

You will notice that strList is considered an IQueryable. This is because until the select s is called, the query is just an in memory TSQL script and has NOT yet been executed. This means you cannot pull any actual data from it until the select is called.

So How do we use it?

Lets say that you want to query against the database for a product that had the name of Beverages. How would you do that in LINQ? Simple. Here is the code.

 

linq-to-sql-example-1

The syntax here (which I cannot remember offhand what it is called) will give you exactly that. The code is creating an entity context and using it to retrieve data from the products table. Then you are defining a filter condition. You are saying get me all the products where the CategoryName column in the Category link table has a value of Beverages.

Note: If you write this syntax out and leave out the ‘select p’, you will not be running the query. It will still be in memory as mentioned above and ‘p’ will be null.

This syntax is actually very similar to raw SQL actually, so if you are looking for something that is expressive for a DBA to look at, this might be the syntax for you.

The other syntax (and my favorite) are called LINQ Methods or Chaining. Using the same database schema example as above lets say that now we want to query the database for a product with a ProductName of Toy 1. That syntax may look something like this:

linq-sql-example-2

Since this article is not about EF, we will skip the assignment and saving to the database part. After creating the database context, the LINQ calls the method Single on the database where ProductName equals Toy 1Single means that it will only return one record. If more than one record is found, an exception will be thrown stating that more than one record is found. If you want to return the first record use the FirstOrDefault method.

I hope everyone has a better understanding of the diferrence between IQueryable and LINQ to Entities. Next article I will explain normal IEnumerables and how they differ from IQueryable.

So When to Use IQueryable and When to Use IEnumerable?

Excellent question, I’m glad you asked! Since IQueryable extends IEunmerable, it would be a good assumption that they have all the same capabilities. That assumption would absolutely correct. The key difference is how and when they handle and manipulate the data.

To follow my videos on C# basic and advanced topics, click here

IEnumerable in this context is used whenever you want to return the data from the database, until you convert an IQueryable to an IEnumerable, the query hasn’t been sent to the database for execution. IEnumerable is also best use when you already have an list of concreate objects in the form of  IList, Dictionary, HashTable etc…

At the end of the day, you really want to make sure that you don’t mix them up when building your call to the database otherwise you can see some very undesirable results.

A great example of this is when you want to do a similar where clause as before:

var products = databaseContext.Products.ToList();

products.Where(x => x.ProductName ==”Toy 1″);

Although this seems like you are doing the right thing by filtering the Product by name, the problem is that the first line returns ALL the products and then you filter the local list of all the products to see what names are ‘Toy 1’.

Obviously, this is not ideal if you have 100,000 records and you want 1 toy. Instead, you should build up your query to send the filter within the query to execute. Here is a better way to do it.

var products = databaseContext.Products.Where(x => x.ProductName ==”Toy 1″).ToList();

 

 

I hope this has all made sense to everyone. Please feel free to leave some comments and let me know if there is anything I can clarify and or things I can blog about in the future.

 

As always, To follow my videos on C# basic and advanced topics, click here

Happy Coding :).

Posted in .NET, .NET 4.5, ASP.NET, Best Practices, C#, Classes, Coding standards, Data Mapping, Databases, Entity Framework, Exception handling, Generics, HTML, HTML Tags, Interfaces, Lazy Loading, LINQ, LINQ To SQL, Long Polling, MVC, Namespaces, Partial Classes, Programming, Programming Paradims, SQL, SQL Server, Uncategorized, Validation | Tagged , , , , , , , , , , , , , , , , , , , , , , , , , | Leave a comment

Concept of the virtual keyword and when to use it in EF 5+

Today, I wanted to talk about eager loading versus lazy loading in entity framework. This is a very important architecture decision when initially setting up entity framework and has come up in quite a few projects over the years.

I decided to blog about the two options because there is often misconceptions that revolve around these two options and how they work and interact with other .NET extensions. There are several ways to accomplish toggling the two options, but I find the most common way that causes confusion is when and how to use the virtual keywords on your navigation properties.

What exactly is eager and lazy loading?

Eager loading and lazy loading are common terms used in software development that define at what point data is loaded into an object. Even though a field is created and a calculation has been assigned to it, the calculation is not run until some predefined event is triggered.

In entity framework this related to when a navigation property is given a value or when a SQL query will be run. I often as a question in interviews what the difference is between IQueryable and IEnumerable as it related to EF and SQL queries, but we can leave that for a  different blog entry. Today, we will focus on the navigation properties scenario.

So what are they and how do we use them?

So what are these mysterious and commonly misunderstood entity framework options? Good question Smile. Eagar loading means that you want Entity Framework to load the data when you want it to and not when it thinks is the best time to. Usually, when you want to eagerly load data, it’s because you need it for some column in the returned data that has some relation to another query (maybe an Id from a newly inserted row. Entity can return this, but maybe for some reason you aren’t doing this). Here is an example of eagerly loading the data.

 

   public Employee GetEmployeeById(int id)
        {
            using (var dbContext = new Blog_EFEntities())
            {
                var employee = dbContext.Employees.FirstOrDefault(p => p.EmployeeId == id);
                return employee;
            }
        }

The code above shows a method that creates the Entity Framework context with a using. This is good to use when you are creating custom contexts because as soon as you are outside the curly braces for the using, the context is disposed of for you to prevent memory leaks. I typically use repository and unit of work patterns to handle this, but it is great for smaller applications. Also for blog posts Smile.

Inside the using, we are taking the context and requesting the first or default of the employees found with an Id of whatever the caller passes in. This takes the IQueryable and converts it into a concrete type. In this case an Employee object (table in the database). This is eager loading because you are asking entity to return you the data immediately, not when it feels a good time to do it.

There are problems with this method. When you have this code set up and maybe you get this data and then use it based some other check statements. Well, you just called the database for no reason. Now in this case, it’s not a big deal because it will only ever be one record, but what if you were getting all employees that were active and there were 600,000 of them? That might raise an issue. With that said, I tend to align more with this pattern because I like to have control of when data is being returned especially in the next section where we will discuss where this fits in with Navigation Properties.

How does this relate to Navigation Properties?

Good question! Navigation Properties in EF are the properties of a class that relate to another class/table. In database speak, foreign relationships. For example, in the example above, we have a Person class as our abstract and an Employee class that has a foreign relationship to the Person class. Here are the classes:

 public partial class Person
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Person()
        {
            this.Employees = new HashSet<Employee>();
        }
    
        public int PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Employee> Employees { get; set; }
    }

 public partial class Employee
    {
        public int EmployeeId { get; set; }
        public int PersonId { get; set; }
        public string Title { get; set; }
        public string Department { get; set; }
    
        public virtual Person Person { get; set; }
    }

You will notice, that there is a Person.Employees property that returns a collection of employees. This is a Navigation Property. It allows the developer to get a list of Employees using a LINQ query through the navigation of a Person object. Some code for this would be something like:

   public List<Person> GetEmployees()
        {
            using (var dbContext = new Blog_EFEntities())
            {
                var employees = dbContext.People.Where(x => x.Employees.Any());
                return employees.ToList();
            }
        }

Here we are using the People object (pluralized version of Person table) and navigating through the Employees table to return any people that contain Employees.

Now, using the above examples, lets say that we did not do a ToList() on the returned variable employees and instead left it an IQueryable. When the caller received the result, until it calls the ToList() or something else that makes it become a concrete type, entity framework will be lazy and not make the call to the database. Pretty cool huh? What’s even cooler is that when the call is finally made, an inner join is made to get you Employee navigation property data as well.

But now, lets say that we want a list of all the People with the first name that starts with a ‘J’, but don’t care about the Title or Department because this is just a dropdown of name value pair. In the current structure, the virtual will always return the employee information which may be quite a bit of data depending on tables size. This is especially important in a web platform.

To get rid of this, you would get rid of the virtual keyword on the classes navigational properties. Then, whenever you want to get the employees, you can do make a call to do so using the include method in LINQ.

   public List<Person> GetEmployeesWithInclude()
        {
            using (var dbContext = new Blog_EFEntities())
            {
                
                var employees = dbContext.People.Include("Employee").Where(x => x.Employees.Any());
                return employees.ToList();
            }
        }

You will notice that Include uses magic strings, which I am not a fan of. There are plugins on Nuget that will override this method. I created my own implementation that I will share in another post. Maybe I’ll update this one. This is getting a little long, so I may not.

I hope this has helped clear some confusion on the options for eager and lazy loading in Entity Framework.

References:

http://stackoverflow.com/questions/5597760/what-effects-can-the-virtual-keyword-have-in-entity-framework-4-1-poco-code-fi

Happy Coding Smile.

Posted in .NET, .NET 4.5, ASP.NET, C#, Classes, Databases, Entity Framework, Exceptions, Extension Methods, Generics, Interfaces, Lazy Loading, LINQ, LINQ To SQL, MVC, Namespaces, Programming, Programming Paradims, SQL Server | Tagged , , , , , , , , | Leave a comment

Namespace changes with Silverlight 8.1

Today I’m going to talk about the dreaded namespace changing (this also applies to project renaming). Most of the time, when you decide to change the project name and or namespaces in an application, there is almost always some hidden issue that pops up. It has been my experience that there is usually a different ‘gotcha’ with each application type (For example Windows Phone, Windows Phone Silverlight, ASP.NET MVC application etc..). This particular article will focus on a Silverlight application.

I have posted several namespace type posts before. One in particular here that relates to changing namespaces in an MVC application and how it changes the way routes are interpreted. I will be talking about another recent issue I had with namespaces and WebAPI in a future post.

What most seem to miss in Silverlight Application project / namespace changes (Including myself).

So I recently changed the namespace on one of my personal projects due to my personal issues with perfection and anal retentiveness for everything to be consistent and unambiguous.  After doing this, I followed the typical steps most do when doing a rename like this. These entail the following:

  1. Update the Assembly information to match the new namespace.
  2. Update the WMAppManifest.xml file Packaging section.
  3. Update the App.xaml to reflect the new x:Class section.
  4. Update any XAML files to the new namespace. Update both the .cs and .xaml file (The .xaml files are updated in the x:Class section at the top of the page).
  5. Update all classes to use the new namespaces.
  6. Update the Package.appmanifest file with the proper entry point if updated and the Packaging section.
  7. Clean out (delete not just run a clean) the obj  and bin folders.
  8. Rebuild the project. This will ensure that the files associated with the project are renamed appropriately to match the new namespace and project name changes. Not doing this can cause adverse affects.

After doing all of these things, most of the time, you have covered all your basis and everything will build successfully and run as expected…. but not alwaysSad smile.

So.. What happened?

Funny you should ask. So I built the project asfter doing everything above and I got a successful build. So we are good right? Wrong! Once I started the project in debug mode, I always got an AgHost.exe exited error, but no diagnostics would run. No exception thrown. No nothing. The complete error I got every time was as follows:

AgHost.exe’ has exited with code -532265403 (0xe0464645)

The key here is the code. –532265… Usually, the exit code is –1, which is pretty much exiting the application, but expectedly. About an hour after Goggling the error code, I found an interesting SO post. There seems to be a bug in Visual Studio 2013 and 2015 that causes the Startup Object  in the Properties section to be empty. To get to this section, right click the project and go to Properties => Application => Startup Object. See below for a visual.

StartupObjectimage

Where it says not set, you should set this from the dropdown to the desired start App XAML file.

 

Hope this helps others from pulling their hair out.

Happy Coding Smile!

Posted in .NET, C#, Classes, MVVM, Namespaces, New apps, Programming, Silvelight, Web Technologies, Windows Apps, Windows Phone, Windows Phone, Windows Store Apps | Leave a comment

JavaScript Asynchronous Callbacks

 

Today we are going to discuss a scenario found often among developers working in the world of JavaScript. Especially developers that don’t come from a language that considers all functions first class objects. This scenario we will be looking at is this:

Issue To Solve

When you have a function that needs to be called after an asynchronous method, how do you handle it? A good example of this is when you need to get a list of data from a RestFul API and based on these results, populate a browser side data table. The problem is that the asynchronous part of an ajax call by nature means that it does not ‘block’ the thread and continues to execute the rest of the code.

Take this as example.

 

In the example above, alert, will always be undefined for two reasons.

1.) At the top, we are not actually initializing the results variable.

2.) Due to the nature of the Ajax call, even though the getData() method is before the alert, the method returns after the alert. If you try it out and put a breakpoint on the anonymous function in the success line, you will see that the success is triggered after the alert. This is called a callback.

What Exactly Are Callbacks?

So what exactly is a “callback”? Essentially, a callback is a ‘promise’ to the caller that when it returns, ‘this method’ will be called. In the above example, the JQuery Ajax method makes a promise that when it returns, the function linked to the success will be called.

Here is an example of what a callback might look like if you didn’t  use JQuery and created one yourself.

If you try this out, you will notice that the “I’ve been hit” gets called and then the “Hit the callback” gets triggered. This is a callback. The method makeCallback() takes in a parameter. This parameter happens to be a method in this case and after the makeCallback is done with the alert, it then triggers the callmeback() method. This is called the callback pattern. By calling the callmeBack method, we are telling whatever calls makecallback() that we promise to call the method it passes in as soon as it is finished with it’s business (in this case the alert). This is because of a concept JavaScript has called “functions as first class objects”. This means that a function can be passed in just like any other parameter.

So How does this solve our problem?

Well, lets take what we have just learned and apply it to the ajax call. Here is the code:

 

So, here we have abstracted the alert for the data returned into a seperate method called callmeback(). This method takes in the result and then alerts the FirstName property of the first result in the array.

Now, the getData() method accepts a method as a property. We are the assigning the promise made by the ajax method to the success promise. By doing this it accomplishes exactly what we need. The ajax call is made, the UI thread is not blocked, so the user isn’t stuck waiting and on return of the call, the alert is triggered via the callback method. For a better understanding of the ajax method and how I knew what was coming back, go here. For some more information on this and other techniques for callbacks such as JQuery promises and anonymous function in JavaScript, see the SO post here

I hope this post was informative and Happy Coding 🙂

Posted in HTML, HTML Tags, JavaScript, JQuery | Tagged , , , , , , , | Leave a comment

Callbacks versus Closures in JavaScript

In my continued goals to get better aquainted with Javascrtipt as well as my readers, today we will discuss two features of JavsScript that confused me for a while and I think I finally got it! They are Closures and Callbacks. Other than both being related to functions, they are quite different in their definition as well as how they are used. In this post, I will try to describe both by example and then explain the differences between them.

Callbacks

Callbacks are nothing specific to JavaScript and neither are Closures. You can use the same knowledge you gain from here and apply it to other languages as well (C# for instance Smile).

Callbacks allow a system to do some sort of work (presumably something that takes a bit of time to complete) and when it returns from doing that work, does this function (callback function). One very common example of this is creating an autocomplete textbox that allows the user to start typing and as they type, the system retrieves data from some data store. Now you don’t want the user waiting all that time while the server returns results and freeze up the UI, so as you probably could have guessed you would use an AJAX call.

Now, lets see what the code for something like this might look like. I am going to assume that you have a working knowledge of JQuery syntax here.

$.ajax({  
           data: 5,    
          url:”/echo/json”,   
          success: function (result) {   
                      alert(‘success’);   
}   });

As you can see above, we have a very simple straight forward AJAX call that calls the JSFiddle API to echo a quick result back to the system. You can pretend that the ‘echo/json’ is returning a list of employee names for a textbox that is being populated using the JQuery autocomplete UI.

The most import part is the success property. This property accepts an anonymous function (I didn’t specifically say callback here for a reason) that will be called upon successful completion of the AJAX call. What makes this a callback function is that it is called after execution of “some code”. The other part that makes this a callback is the fact that the parameter the function accepts is provided by the AJAX function itself. The AJAX success property  passes it’s results from the call directly to the callback.

You can think of a callback as the second part of a handshake. I am not going to say promise here because that means something in JavaScript and I don’t want to get into that. Although as a heads up, this is another place for callbacks. In any case, a callback is the second part of the agreement made between the caller and the object being called that when it finishes doing what you asked it to do, it will also do ‘something else’.

Here is a basic example of creating your own callback that may make a little more sense

// Main function that accepts the callback fn being the callback
function calculator(a, b, fn) {   
// do some internal processing   
return fn(a, b);

// sub functions that are called back to
function sum(a, b) {   
return a + b;
}
function divide(a, b) {  
  return a / b;

var addition = calculator(2, 5, sum);
var d = calculator(10, 5, divide);
alert(“added: ” + addition); alert(“divided: ” + d);

As you can see above, the third parameter being passed to the calculator function is indeed a function. Therefore, you can pass a function into this function that will do some work and then call the function passed in later. To see this in action click here. This is essentially what is done for the Ajax function in JQuery. There are other pieces to it, but this is the basics.

Closures

So now on to closures. Closures are one of the harder things for developers to get that are not primarily functional programmers, but once you get it, there is an AHA moment and it all becomes crystal clear.

The idea of a closure is to allow a function to have access to the variables outside itself. You can almost think of it as a mini global scope between the closure function and it’s parent function. Below is a nice example of creating a generator function that the caller passes in a number and you get something else. This is not a random generator by any means. Just a basic example of what a closure is and how it can be used.

// Main method to generate numbers  
function generateNumber(x) {
    var i = 12;

    // Anonymous function that acts as the closure because it has
    // access to the variables outside itself (i in this case)
    return function () {
        i = i + x;
        alert(“New Number: ” + (i));
    }
}

var b = generateNumber(34);
b();
b();

 

To check out the code live, check it out here. So what you will notice here is that I am calling this generateNumber function and passing in the number 34.  At the beginning of this function, a variable called i is initialized to 12. Under normal “scope” rules, the function in the return statement would NOT have access to this variable because it is not inside the curly braces of that function. This is where the word closure comes in. It closes itself around it’s parent scope and because of this, it has access to the i variable.

Now the function that is returned has nothing passed into it, but has access to the i variable. Because of this, the result will be 46 (12 + 34).

The last thing to note about closures is that they keep a reference to variables even after the parent method completes. Freaky right? So as you can see at the bottom of the code, I call the ‘b’ twice. The first alerts 46, the second alerts 80 (46+34).

Conclusion

So to wrap things up, here is how I view closures and callbacks.

Callbacks are functions that are defined and “used” but executed at some undetermined time. They are often used in returned AJAX calls and events such as a click event to have something happen when the button is clicked.

Closures are inner functions that have access to outer functions variables (enclosing around these functions). A closure also remembers about the variables and environment it as in, so when calling the above method multiple times as we say, it remembers what the ‘I’ variable last was.

I hope this has helped clear it up a bit for some folks. I know it clears it up every time I talk about it a little more each timeSmile

Happy Coding!

Posted in .NET, .NET 4.5, Best Practices, C#, Classes, Coding standards, Interfaces, JavaScript, JQuery, MVVM, Namespaces, Performance, Programming, Programming Paradims, Web Technologies, Windows Store Apps | Tagged , , , , | Leave a comment