Category Archives: ASP.NET

Entity Framework – The type was not mapped issue solution


While working on the Entity Framework, you may face an issue with the exception saying:

An unhandled exception of type ‘System.InvalidOperationException’ occurred in EntityFramework.dll

The type ‘xxx’ was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.

Here is the console based code which can reproduce this exception:


class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.WriteLine("Please enter blog name:");
string blogName = Console.ReadLine();

Blog blog = new Blog();
blog.Name = blogName;
blog.DateCreated = DateTime.Now;
db.Blogs.Add(blog);
db.SaveChanges();

// List all available blogs in the DB
Console.WriteLine("All blogs in the DB:");
foreach (var item in db.Blogs.ToList())
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
}
public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public virtual List<Post> Posts { get; set; }
}

public class Post
{
[Key]
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int IDBlog { get; set; }
public virtual Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
}

Solution:

The issue is POCO classes and DbContext was nested within POCO class. Entity framework does not like nested classes.

Please note: Nested class means, a class defined within another class.

Error free code:


class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.WriteLine("Please enter blog name:");
string blogName = Console.ReadLine();

Blog blog = new Blog();
blog.Name = blogName;
blog.DateCreated = DateTime.Now;
db.Blogs.Add(blog);
db.SaveChanges();

// List all available blogs in the DB
Console.WriteLine("All blogs in the DB:");
foreach (var item in db.Blogs.ToList())
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
}
}

public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public virtual List<Post> Posts { get; set; }
}

public class Post
{
[Key]
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int IDBlog { get; set; }
public virtual Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

Hope this helps.

Advertisements

Entity Framework – Code First Approach Example


In this article, Let’s see an example of Entity Framework – Code First approach

If you don’t know about Entity Framework, please go through this article.

Just to revise, In the Code First approach, You write your classes first and then create database from these classes.

Entity Framework – Code First Approach Example

1. Let’s create a console application. Name it as “EFCodeFirstExample”.

2. Since it’s Entity Framework project, let’s add reference to “Entity Framework” assembly via nuget package manager.

There are many ways to do it. We can add it by right clicking the project and selecting the “Manage Nuget Packages” menu. A window will appear, select “Online” from left hand side and enter “EntityFramework” on top right hand side, press enter to search. Entity Framework package will appear in search result, press “Install” to continue.

3. Once done, you can see from the project references that the reference to “EntityFramework” is added.

Also we need to add a namespace reference to Entity framework.


using System.Data.Entity;

4. Let’s start with coding part. We will create 2 simple classes (POCO) to understand the code first approach namely “Blog” and “Post”.

Consider following Blog class.


public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}

5. Consider following Post class


public class Post
{
[Key]
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int IDBlog { get; set; }
public virtual Blog Blog { get; set; }
}

6. We have specified Key attribute to “IDBlog” and “IDPost”, which means both are primary keys for respective tables (Tables are created once we run the application).

Virtual properties (virtual List<Post> Posts and virtual Blog Blog) are marked for lazy loading, which means when we try to access them, entity framework will load the associated data. Those are called navigation properties, which means they will create foreign key constraints in the DB.

7. Let’s create a context class now. Consider following BloggingContext class.


public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

Here please note that our BloggingContext class is derived from the “DbContext” class.

8. Now let’s write our main program where we will add a new blog and list the blogs in the DB.


class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.WriteLine("Please enter blog name:");
string blogName = Console.ReadLine();

Blog blog = new Blog();
blog.Name = blogName;
db.Blogs.Add(blog);
db.SaveChanges();

// List all available blogs in the DB
Console.WriteLine("All blogs in the DB:");
foreach (var item in db.Blogs.ToList())
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
}
}

9. Now you will think about connection string to DB. We did not mention about DB and connection string in the project. By default, visual studio 2012+ has local DB.

By convention DbContext has created a database for you.

1. If a local SQL Express instance is available (installed by default with Visual Studio 2010) then Code First has created the database on that instance

2. If SQL Express isn’t available then Code First will try and use LocalDb (installed by default with Visual Studio 2012+)
10. The database is named after the fully qualified name of the derived context, in our case that is EFCodeFirstExample.BloggingContext.

11. Once you run the application, it will create the DB for us upon our defined POCO classes. Here is the output for our application.

12. Now if we need to change the table schema, then what? In such case, we need to change out classes which in turn update our DB. To do this we have a feature in Entity Framework called Code First Migrations, or Migrations.

13. Consider following change in out blog class.


public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public virtual List<Post> Posts { get; set; }
}

14. To update this change in our DB, we need to enable Code First Migrations for our BloggingContext. Open the “Package Manager Console” from the solution and run the command. Enable-Migrations

15. This command will add 2 files in the project named “Configuration.cs” (This file contains the settings that Migrations will use for migrating BloggingContext) and “201310141156476_InitialCreate.cs” (it represents the changes that have already been applied to the database).

16. Now let’s run the command Add-Migration AddDateCreated command in Package Manager Console to update out DB for new changes. It will create a file called “201310141332176_AddDateCreated.cs”


public partial class AddDateCreated : DbMigration
{
public override void Up()
{
AddColumn("dbo.Blogs", "DateCreated", c => c.DateTime(nullable: false));
}

public override void Down()
{
DropColumn("dbo.Blogs", "DateCreated");
}
}

17. Run the Update-Database command in Package Manager Console. This command will apply any pending migrations to the database. You can use the –Verbose switch when calling Update-Database to see the SQL that is being executed against the database.

18 And you will see the DateCreated column is added in our DB.

Hope this helps. Please comment below the post if you have any doubts or questions.

Source Code Download:

Github [Repository Link]

Entity Framework Basics


What is Entity Framework (EF)?

Microsoft has defined the Entity Framework in following words:

The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.

It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.

ORM is a tool for storing data from objects to relational database like MS SQL Server in an automated way without much programming. Other well known ORM frameworks for .net are DataObjects.Net, NHibernate, OpenAccess, SubSonic etc. ADO.NET Entity Framework (Open source) is from Microsoft.

Please note: Entity framework not only supports MS SQL Server, but also other database like Oracle, DB2, MySQL etc.

Types of Entities in Entity Framework:

1. EntityObject

2. POC (Plain Old CLR Object)

3. POCO Proxy

4. Self-Tracking Entities.

Each entity can have two types of properties, Scalar properties and Navigation properties.

Scalar properties are properties whose actual values are contained in the entity. Whereas Navigation properties are pointers to other related entities.

Modeling techniques using Entity Framework 4.1

1. Code first

In the Code First approach, You write your classes first and then create database from these classes. There are two new objects introduced for Code First approach, DbContext and DbSet. DbContext is the primary object for interacting with a database using a specific model. DbSet(Of TEntity) is used to perform CRUD (Create, Read, Update and Delete) operations against a specific type from the model in Code First approach.

2. Model First

In Model First approach, you create Entities, relationships, and inheritance hierarchies directly on EDMX File. So in Model First approach, when you add ADO.NET Entity Data Model, you should select ‘Empty Model’.

After creating required entities, associations and inheritance on design surface of the empty model, you can use designer’s context menu option ‘Generate database from model’ to generate the database.

3. Database First

In the Database First approach, you will reverse engineer a model from an existing database. The model is stored in an EDMX file (.edmx extension) and can be viewed and edited in the Entity Framework Designer. The classes that you interact with in your application are automatically generated from the EDMX file.

We will see examples of this approaches in upcoming articles to clear the terms more better.

Please comment below for any doubts or questions.

AngularJS – A Javascript MVC Framework


What is AngularJS?

AngularJS is a Javascript MVC framework created by Google to build properly architectured and maintainable web applications. It extends HTML into a more expressive and readable format. It decreases emphasis on directly handling DOM manipulation from the application logic, allowing for easier testing. It employs efficient two-way data binding and sensible MVC implementation, reducing the server load of applications.

Why AngularJS?

AngularJS is a MVC framework that enhances HTML by attaching directives to your pages with new attributes or tags and expressions in order to define very powerful templates directly in your HTML. It allows to declare dynamic views in web-applications. It also lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

Now let’s have a closer look at all those features.

1. Expressions

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by the $parse service.

For example, these are all valid expressions in angular:

2+2
7*10 | currency
user.name

2. Directives

Directives adds new tricks to HTML. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

Angular comes with a built in set of directives which are useful for building web applications but can be extended such that HTML can be turned into a declarative domain specific language (DSL).

Jsfiddle Example

3. Data Binding

Data-binding in Angular web apps is the automatic synchronization of data between the model and view components. The way that Angular implements data-binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. When the model changes, the view reflects the change, and vice versa.

ngModel Is a directive that tells Angular to do two-way data binding. It works together with input, select, textarea and even custom form controls that use NgModelController exposed by this directive.

4. Filters

In order to change the way your data are displayed in your page, AngularJS provides you with the filter mechanism.

e.g we can put the name in upper case with {{user.name | uppercase}} filter

You can also easily create your own filters.

5. Modules

In AngularJS, applications are structured in modules. A module can depend on other modules and a module can contain controllers, services, directives and filters.

jsfiddle Example

6. Scopes

Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.

7. Controller

Controllers are the behavior behind the DOM elements. AngularJS lets you express the behavior in a clean readable form without the usual boilerplate of updating the DOM, registering callbacks or watching model changes.

Related Videos

BrowserSwarm – Spend Less Time Testing Your JavaScript Project


What is BrowserSwarm?

It is a tool that automates your testing of JavaScript across browsers. Spend less time testing and more time innovating. It is a project from appendTo, Sauce Labs and the Internet Explorer team.

BrowserSwarm provides test results using top frameworks and libraries such as prototype.js and Modernizr. You receive an overall pass rate across browsers and devices, along with individual test pass rates for top browsers.

You can register an account on BrowserSwarm here.

How BrowserSwarm works?

  1. BrowserSwarm connects directly to your GitHub code repository.
  2. When your team makes updates, BrowserSwarm automatically runs your project’s Unit Test Suite and supports Frameworks, like QUnit, in the cloud using SauceLabs browser automation.
  3. You can easily view or download the results.

See test results for top libraries: (Screenshot)

Here is the sample test result for jquery.

Here is the screen for Build details and Build History for jQuery.

From the Dashboard, you can configure your BrowserSwarm projects.

There are various options through which you can configure your BrowserSwarm project.

Configuration options:

1. Collaborators

2. Github Config

3. Heroku Config

4. Webhooks

5. Deactivate

6. Custom Scripts

7. Environment

8. Saurce Config

9. Jelly-Proxy Config

10. QUnit Config

Create and Setup a Facebook (FB) Application (App)


In this article, let’s see how to quickly setup a Facebook application

Steps to Follow:

1. Go to http://developers.facebook.com/

2. Login to Facebook with your valid credentials. If you don’t have Facebook account, you can create a new Facebook account by clicking here.

3. Once logged in, you can see “Apps” menu on the top of the page. Click on it.

4. Once you are in, click on “Create New App” button.

5. You will see a popup window, enter your app name and set the category from the dropdownlist. Click on “Continue” button.

6. Enter the captcha. After that you will be presented with the Basic settings screen of your Facebook application.

Here please note down your “App ID” and “App Secret” keys.

7. Now click on “Website with Facebook Login” panel.

8. Enter your website name (which you will use to communicate with Facebook) and click on “Save Changes” button.

And done! You have just created a Facebook application.

Please comment below in case of any doubts or issues. Hope this help you.

LINQ to Twitter Library using ASP.NET


In the last article, we have discussed, how to create and setup a twitter application. In this post, let’s discuss about how to use LINQ to twitter library using C# ASP.NET.

About LINQ to Twitter:

“LINQ to Twitter is an open source 3rd party LINQ Provider for the Twitter micro-blogging service. It uses standard LINQ syntax for queries and includes method calls for changes via the Twitter API.”

Let’s discuss an example which uses LINQ to Twitter library.

1. Create a new ASP.NET empty web application. We call it as “LinqtoTwitterExample”.

2. Download LINQ to Twitter library from here. Since we are using .NET framework 4.5, add a reference to “LinqToTwitter.dll” file from net45 folder.

3. Add the 5 keys in the web.config file namely “TwitterConsumerKey”, “TwitterConsumerSecret”, “TwitterAccessToken”, “TwitterAccessTokenSecret” and “TwitterScreenName” (it will hold your twitter screen name).


<appSettings>
 <add key="TwitterConsumerKey" value=""/>
 <add key="TwitterConsumerSecret" value=""/>
 <add key="TwitterAccessToken" value=""/>
 <add key="TwitterAccessTokenSecret" value=""/>
 <add key="TwitterScreenName" value="deshpandesuraj"/>
 </appSettings>

You can get the settings from the Twitter App.

4. Add a new aspx page call it as “Default.aspx”.

5. Add a button and a textbox on “Default.aspx” page. Set the max length of textbox to 140 since twitter uses only 140 characters.

In the code behind add reference to namespace: using LinqToTwitter;


var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);
 if (twitterCtx != null)
 {
 twitterCtx.UpdateStatus(textbox1.Text.Trim());
 }

6. Add another button and a listbox on “Default.aspx” page to hold the list of tweets.


var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);

var tweets = from t in twitterCtx.Status
 where t.Type == StatusType.User
 select t;

if (tweets != null)
 {
 foreach (var tweetStatus in tweets)
 {
 if (tweetStatus != null)
 {
 listbox1.Items.Add(new ListItem(tweetStatus.Text, tweetStatus.ID));
 }
 }
 }

Please Note: Your twitter application name will appear over tweet you sent.

Following are the commonly required twitter functions.

Get list of Followings:


List<string> followingsCollection = new List<string>();
 var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);

//cursor is used because twitter returns list partially
 string nextCursor = "-1";

while (!string.IsNullOrEmpty(nextCursor) && nextCursor != "0")
 {
 var followings =
 (from frndship in twitterCtx.Friendship
 where frndship.Type == FriendshipType.FriendsList &&
 frndship.ScreenName == ConfigurationManager.AppSettings["TwitterScreenName"] && frndship.Cursor == nextCursor
 select frndship)
 .SingleOrDefault();

if (followings != null)
 {
 foreach (var follower in followings.Users)
 {
 if (follower != null)
 {
 followingsCollection.Add(follower.Name);
 }
 }
 nextCursor = followings.CursorMovement.Next;
 }
 }
 return followingsCollection;

Get list of Followers:


List<string> followersCollection = new List<string>();

var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);

//cursor is used because twitter returns list partially
 string nextCursor = "-1";

while (!string.IsNullOrEmpty(nextCursor) && nextCursor != "0")
 {
 var followers =
 (from frndship in twitterCtx.Friendship
 where frndship.Type == FriendshipType.FollowersList &&
 frndship.ScreenName == ConfigurationManager.AppSettings["TwitterScreenName"] && frndship.Cursor == nextCursor
 select frndship)
 .SingleOrDefault();

if (followers != null)
 {
 foreach (var follower in followers.Users)
 {
 if (follower != null)
 {
 followersCollection.Add(follower.Name);
 }
 }
 nextCursor = followers.CursorMovement.Next;
 }
 }
 return followersCollection;

Get list of Favorites:


List<string> favoritesCollection = new List<string>();
 var auth = new SingleUserAuthorizer
 {
 Credentials = new InMemoryCredentials
 {
 ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
 ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
 OAuthToken = ConfigurationManager.AppSettings["TwitterAccessToken"],
 AccessToken = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
 }
 };

var twitterCtx = new LinqToTwitter.TwitterContext(auth);

var favorites =
 (from fav in twitterCtx.Favorites
 where fav.Type == FavoritesType.Favorites &&
 fav.IncludeEntities == true
 select fav)
 .ToList();

if (favorites != null)
 {
 foreach (var fav in favorites)
 {
 if (fav != null)
 {
 favoritesCollection.Add(fav.Text);
 }
 }
 }
 return favoritesCollection;

Source Code Download:

Github [Repository Link]

Please note: For security point of view, I have removed twitter config key values from web.config file. If you are using my downloaded example, please add appropriate key values.

If you have any questions or doubts, please comment below.