Windows Gadget To Display VWorker Recent Open Projects

by Naveen 26. January 2012 21:18

Download Gadget For Vworker Recent Projects (22.07 kb)

In this post I will discuss how to write a Windows 7 gadget. It has been long since I wrote a gadget. This week I was looking at putting some scroll view of freelance projects from vWorker web site. They have a piece of HTML code that you can put on your web site to show latest open projects in a scrolling view. When I am working on some project or executing some other tasks on my desktop, then I do not any web site open. I want to have a view of latest open projects on side of my big desktop view. So, developing a gadget made more sense to me. So in this past I will share that gadget with all of you who use VWorker for doing freelance work. And I will show steps to write this windows gadget as well.

Develop Windows Gadget

If you are considering Windows gadget development, then I will strongly encourage to read Microsoft documentation on gadget framework. It will give some good basic background on gadget development. Here are steps that you will need to follow to write a simple Windows gadget like I wrote for displaying latest open freelance projects on VWorker site.

  • Create a folder with name same as what you would your gadget to be named. For example I create a folder named VWorkeLatestProjects.gadgets
  • Create a 64x64 image (recommended size by Microsoft) that you would like to use a logo for your gadget. This is the logo that will show up in Windows control panel UI when you look at available gadgets on your machine.
  • Create a XML file named Gadget.xml in this folder. This file will contain manifest of your gadgets. In simple terms, this file contains all details about your gadget. This file does not contain implementation of gadget itself. Following is how my file looks like.

    <?xml version="1.0" encoding="utf-16"?>
    <gadget>
      <name>VWorker Recent Projects</name>
      <namespace>microsoft.windows</namespace>
      <version>1.0.0.0</version>
      <author name="ByteBlocks.com">
        <info url="http://www.byteblocks.com" text="Byteblocks.com"/>
        <logo src="logo.png"/>
      </author>
      <copyright>
        © 2012</copyright>
      <description>See latest open projects at vWorker.</description>
      <icons>
        <icon width="64" height="64" src="icon.png"/>
      </icons>
      <hosts>
        <host name="sidebar">
          <autoscaleDPI><!--_locComment_text="{Locked}"-->true</autoscaleDPI>
          <base type="HTML" apiVersion="1.0.0" src="VWorkerLatestProjects.html"/>
          <permissions><!--_locComment_text="{Locked}"-->Full</permissions>
          <platform minPlatformVersion="1.0"/>
          <defaultImage src="drag.png"/>
        </host>
      </hosts>
    </gadget>
    

    As you can see from this file content, it lays out blue print of the gadget.

  • Now comes the implementation of the gadget. There is an entry with tag name BASE that defines the entry point for implementation. You will notice that I have set it to VWorkerLatestProject.html. What this means is that when gadget loads it will load up this HTML file. So, add an HTML file in your folder that is going to be entry point. Following is snapshot of contents of my HTML file.

    <html dir="ltr">
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link href="css/vworkerlatestprojects.css" rel="stylesheet" type="text/css" />
        <title>VWorker Latest Projects</title>
      </head>
      <body id="VWorkerProjectFeedGadget">
      <g:background id="VWorkerFeedBG">
      <div id="feedbody">
      <iframe id="VWorkerFeedIFrame" frameborder="1" scrolling="no" width="150" height = "300"
            src = "http://www.vWorker.com/RentACoder/misc/LinkToUs/ScrollingBidRequests.asp?
            txtWidth=150&txtHeight=300&blnHideChannelSubscribe=true&
            blnLaunchLinkInNewWindow=true&blnFullTitle=true&txtBgColor=white">
    		Your browser does not support inline frames...However, you can click 
    		<a href="http://www.vWorker.com/RentACoder/misc/LinkToUs/ScrollingBidRequests.asp?
             blnHideChannelSubscribe=true&blnLaunchLinkInNewWindow=true&blnFullTitle=true">
    		here</a> to see the related document.
    		</iframe>
      </div>
      </g:background>
      </body>
    </html>
    

    As you can see, implementation is just like developing a regular HTML page. For my gadget it was as simple as putting IFrame content for VWorker site into my HTML page. So you can see how I included that IFRAME tag inside g:background tag of this gadget.

  • Yes, that was the whole implementation of this gadget. It is ready to be deployed and used.

Deploying Windows Gadget

Deployment of windows gadget is very simple. You just need to copy your gadget folder at either of following two locations depending on scope and visibility of this gadget.

%USERPROFILE%\AppData\Local\Microsoft\Windows Sidebar\Gadgets (for user gadgets)
%SYSTEM_ROOT%\Program Files\Windows Sidebar\Gadgets (for global gadgets)

For example in my case, I want every user of may desktop to be able to see this gadget. So I copied it at following location.

C:\Program Files\Windows Sidebar\Gadgets\VWorkerLatestProjects.gadget

Adding Windows Gadget To Desktop

Once you have deployed the gadget, you can follow these steps to put the gadget on your desktop

  • On your desktop go to Control Panel > Appearance and Personalization. Or right click on your desktop screen.

  • There you will see option for Gadgets. Click on it and it will bring up dialog box with Gadgets installed on your machine. You will find your own gadget there was well.

  • Double click on the gadget icon you would like to install. It will appear docked to right side of your desktop screen.

Windows Gadget For VWorker Latest Projects

I have attached this gadget with this post. Download the zip file, unzip it in one of the two locations that I earlier specified and you will be good to go.


 

Views: 184

Tags: ,

Windows | Windows 7

How to get emails from all exchange mail folders on iPhone

by Naveen 23. January 2012 23:42

Recently I replaced my Blackberry with iPhone 4s at work. It was such a relief. Using Blackberry was a total nightmare because of various reasons. Everybody had different reasons to not like it. Here are some that always pushed me away from Blackberry.

  • Very low battery life
  • Usability

Anyhow this post is not about Blackberry. This post is about setting up Microsoft Exchange email folders on your iPhone 4s. After I received my iPhone from our IT guys, I noticed that I was only getting emails in my Inbox folder. I have set up a lot of email rules to move emails to various folders when they arrive. I remember that on Blackberry I had to make some modifications in sync application so that I could receive emails on selected folders along with Inbox. So following intuition, I went to Settings in iPhone and found the way to do it. Here are the steps that you can follow to push emails from all or selected folders in Microsoft Exchange to folders on iPhone.

  • Select Settings from main screen of your iPhone
  • Scroll down a little in Settings screen and you will find Mail, Contacts, Calendars option. Click on this item in the list.
  • On Mail, Contacts, Calendars screen look under Accounts section for the exchange account for which you want to make the changes. And click on that account item in the list.
  • On this exchange set up screen, at the bottom you will find Mail Folders to Push item. Click on this item in the list.
  • On this Mail Folders to Push screen, you will complete list of email folders available for you. Just select the folders that you would like to include.

Now you will be all set to receive emails from your selected folders on your iPhone.


 

Views: 527

Tags:

Apple

Skype Crashes On Windows 7

by Naveen 10. January 2012 07:32

I am a very heavy user of Skype. All my communication with my team members and clients happens through. Yesterday when i logged into Skype, within 5 seconds the application crashed. My first impression was that I probably forgot to restart my machine after installing Windows updates. So I restarted my laptop, same deal. The application crashed right after I logged in. This happened few times. So l looked at the event logs and found the following details.

Faulting application name: Skype.exe, version: 5.5.59.124, time stamp: 0x4e96c098
Faulting module name: KERNELBASE.dll, version: 6.1.7601.17651, time stamp: 0x4e211319
Exception code: 0x0eedfade
Fault offset: 0x0000b9bc
Faulting process id: 0x1310
Faulting application start time: 0x01cccedd641f3439
Faulting application path: C:\Program Files (x86)\Skype\Phone\Skype.exe
Faulting module path: C:\Windows\syswow64\KERNELBASE.dll
Report Id: b189e264-3ad0-11e1-b713-415645000030

That is not a very good sign that the application is crashing inside a system DLL Kernelbase.dll. This was obvious sign of some corruption in installation or something changed in OS that is causing the errors. So I decided to re-install Skype client. After cleaning up old install and re-install, the problem did not go away. Skype kept crashing right after login. Then I went onto Skype's support site and forums and found out that there is some known issue in Version 5.5 client. Some of the advertisers are pushing in some code that is causing this unstable behavior in Skype itself. Skype is asking people to download Beta version 5.7 of Skype to try. After i installed version 5.7 (Beta), the problem disappeared and no more crashes. I have provided link to Skype's page from where you can download the beta client.

Click here to download Skype Beta version


 

Views: 474

Tags:

General

Set file download folder for Chrome

by Naveen 9. January 2012 05:56

One of most performed action in Internet browsing is that we all download lot of music, videos, document etc. to our local hard disk for later viewing. A lot of time we view those files immediately and some time we want to do it later. If you want to view it later then you will need to know where exactly that file is stored. By default Google Chrome stores file at the following location.

C:\Users\{user name}\Downloads

This is location for Windows 7 and assuming C drive is your system drive. A lot of time I have run into situations where I have downloaded same files multiple times. Chrome and other browsers do a good job of renaming a file if it is going to duplicate copy of an existing one. Then you know that you really did not need this file because you already have it. But when you use multiple browsers then lot of time you have duplicate files at multiple locations. If you designate a folder on your machine where you want to keep downloaded files, then you can easily manage those files.

In Chrome you can change the default location of downloaded files as described below.

  • Click on little wrench looking icon on upper right side of the browser bar and click on Options menu item.

    chrome options
  • Now you will presented with Options screen in a new tab. Click on on Under the Hood option in left navigation bar.

  • In Options - Under the Hood screen, in right view there is a section for Downloads as shown below. In this section you can change the default location. You will notice a check box that allows you to set the option so that browser will always ask for location where file should be saved.

You will find similar options in other browsers as well. This way you can consolidate downloaded files at one location.


 

Views: 192

Tags:

Google

The database principal owns a database role and cannot be dropped

by Naveen 27. December 2011 07:09

This morning I was migrating Microsoft SQL databases from an old server to a new server. After migrating the database, I needed to delete an existing login user from the database and add a new one. When I tried to delete the user I got the following error thrown at me.

The database principal owns a database role and cannot be dropped

I opened the Database Roles node under Security and found a long list of roles. Following image shows partial list of those roles.

I remember that user login had db_owner role on old server. So I click on that role and found the user name there. I deleted the user from that role. I tried to delete the user, again the same error. This means we need a way to list all the roles that are owned by this user. Lets see some underlying system tables where this information is available.

sys.database_principals Database Table

You will find all the principals in your server in sys.database_principals table. You can do a quick Select query on this table to see what all is there. Following image shows part of the information from that table.

As you can see it lists all the roles in your server and principals associated with it. The column of interest in this table is owning_principal_id. This is the field that contains the ID of user who owns that schema. So you just need to run a query that will list all the roles in this table that has owning_principal_id same as principal_id and you have all that you need.

select dbp1.name as DbRole, dbp2.name as DbRoleOwner 
from sys.database_principals as dbp1 
inner join sys.database_principals as dbp2 
on dbp1.principal_id = dbp2.owning_principal_id 
where dbp1.name = 'dbuser'

To run this query in your database, replace dbuser with whatever user you are trying to delete. This query will give you all the roles owned by this user. Then you can go to each of those roles in Database Roles node and replace it with some universal role. Replacing it with dbo will be a safe bet. Once you have changed owner of all those roles, you can simply delete that user from security node of that database. After that you can change the role owner to new user if you need to.


 

Views: 299

Tags:

SQL Server

How to create GridView programmatically in code behind

by Naveen 12. December 2011 08:36

Download Sample Project

I have talked about using and customizing GridView, DataGrid and other grid like controls in lot of my previous posts. In this post I am going to discuss how you can build GridView programmatically. First question that you may be asking what do I really need to design and build GridView in code behind and not using designer and control tags. For most cases you may not have to do it. But think for a moment a case where you do not know the number of columns you will need ahead of time and depend on some run time conditions or configuration changes. Then you won't be able to specify column tags in your design view.

I will split this post into multiple parts to tackle different parts of the solution. In this particular post I am going to concentrate mainly on creating the GridView and displaying the data.

  • How to programatically add columns to GridView
  • How to format data into GridView columns at run time

I am not going to discuss how to handle changing data in grid view columns in this post. I will do that in subsequent posts. Here are steps that you will follow to build your GridView at run time.

  • Add a GridView on your ASP.Net page. Your smark up will look like something as shown below.

    <asp:GridView ID="Sales_Grid" runat="server" 
     AutoGenerateColumns="false" GridLines="None" CssClass="salesgrid"
     onrowcreated="OnGridRowCreated" 
     onrowdatabound="OnGridRowDataBound"></asp:GridView>
    

    The most important part of this mark up is that you need to set AutoGenerateColumn property to false. By doing so you will disable GridView from automatically generating any columns.

  • At run time, add columns to GridView. For example following cone snippet shows how BoundField columns are being added to Grid based on a collection that we get at run time.

    void SetupGridStructure()
    {
       var gridColumn = new BoundField();
       Sales_Grid.Columns.Add(gridColumn);
       foreach (SalesPeriod period in _salePeriods)
       {
          gridColumn = new BoundField();
          gridColumn.HeaderText = period.PeriodName;
          Sales_Grid.Columns.Add(gridColumn);
       }
    }
    
  • Subscrive to RowCreated and/or RowDataBouns event(s) on GridView depending on at what stage you want to set the data in the columns. You can see those event specified in first step in the GridView mark up. in these events you will set the data for each columns. The following code snippet shows how I did it for showing some dummy sales figures for each month of the year

    protected void OnGridRowDataBound(object sender, GridViewRowEventArgs e)
    {
      switch(e.Row.RowType)
      {
          case DataControlRowType.Header:
            RenderHeaderRow(e);
            break;
          case DataControlRowType.DataRow:
            RenderDataRow(e);
            break;
          default:
            break;
      }
    }
    
    void RenderDataRow(GridViewRowEventArgs args)
    {
        // Accesss the data.
        var rowData = args.Row.DataItem as SalesData;
        // Get product name.
        ..... Rest of the code .....
        ............................
    }
    

Attached sample project shows all this in action. There are more features implemented in the sample that I will be discussing in subsequesnt posts.


 

Views: 754

Tags:

ASP.Net | GridView

How to use transaction in Entity Framework

by Naveen 22. November 2011 05:51

In previous posts, how to insert new records using entity framework and how to update records using entity framework. Those two processes are foundation blocks of most of the data operations we all perform in an application. The examples that showed in those posts were very simple involving one record for one table. In more complex work flow processes you have more than one database operations that need to take place to accomplish the intended outcome. When you have multiple records and tables being manipulated, you have to ensure ACID nature of transactions. There are very few cases I have come across where one could afford to have change in one table succeed if another operation in the same chain fail.

In this post I will show how to use transactions in Entity Framework. If you have dealt with transactions in SQL server queries or for that matter any database operations, you will notice that when using Entity Framework the concept stays the same. You perform the following steps.

  • Create a transaction
  • Perform database operations with in scope of that transaction
  • Commit or rollback transaction depending on out come of database operation

When you are using Entity Framework, transactions are handled by Transaction framework. You will not find reference to those namespaces in EntityFramework assembly. Those references exist in System.Transactions assembly. Lets see how you will use transactions in entity framework.

Assembly reference and namespace

Add references to System.Transactions.dll assembly in your project. And now include System.Transactions namespace in your code file.

Create new transaction

Key to using transaction is creating a transaction or logically speaking create a transaction scope which will enclose all the data operations that need to be included in one single transaction. Use TransactionScope class to create new instance of implicit transaction scope for operations.

using System.Transactions;

var txScope = new TransactionScope();
using (txScope){ ......  }

Perform database operations

With in scope of transaction perform all the data operations that I talked about in previous posts.

try
{
 dataContext.Projects.Add(project);
 dataContext.SaveChanges();
}                        

Commit Transaction

After all the database operations have completed and succeeded, then you can commit transaction by calling Complete method on TransactionScope object.

try
{
 dataContext.Projects.Add(project);
 dataContext.SaveChanges();
 txScope.Complete();
}

If you are looking for method like Rollback, you will not find it. No, this does not mean that transaction can not be rolled back using Entity Framework. The framework is designed to commit a transaction only after Complete method is called. If you do not want to commit a transaction, you can explicitly call Dispose on TransactionScope object or wait till TransactionScope object goes out of scope.

Here is complete code snippet from one of my sample projects.

protected void OnAdd(object sender, EventArgs e)
{
  if (!ValidateContracts())
  {
    ErrorMessage_Label.Visible = true;
    return;
  }

  var project = new Project()
  {
   ProjectName = AntiXss.HtmlEncode(ProjectName_TextBox.Text.Trim()),
    ProjectDescription = AntiXss.HtmlEncode(ProjectDescription_TextBox.Text.Trim()),
    Active = true,
    Deleted = false,
    ClientId = _thisClient.ClientId,
    CreateDate = DateTime.UtcNow
  };

  var dataContext = new PMDataContext(Global.ConnectionString);
  using (dataContext)
  {
   var txScope = new TransactionScope();
   using (txScope)
   {
    try
    {
     dataContext.Projects.Add(project);
     dataContext.SaveChanges();
     txScope.Complete();
    }
    catch (UpdateException upEx)
    {
     //TODO: log this update exception
     System.Diagnostics.Debug.WriteLine(upEx.Message);
    }
    catch (Exception ex)
    {
     //TODO: log thjis general exception
     System.Diagnostics.Debug.WriteLine(ex.Message);
    }
   }
  }
}

 

Views: 653

Tags: , ,

.Net | ADO.Net | LINQ

How to update record using Entity Framework

by Naveen 18. November 2011 08:53

In previous post How to insert new record using Entity Framework, I discussed one aspect of CRUD operation in an application or process. In this post I will talk about another aspect of the process, how to update a record using Entity Framework. If you are building some kind of business intelligence aplication where only action you have to take is read the data, then you may not be interested in UPDATE part of the process. But most of the applications require you to undertake whole spectrum of operations. And UPDATE is big part of the process.

The process of updating database records using Entity Framework is pretty straight forward. In previous post you saw that you use the collection property of Data Context to add new object in it and then call SaveChanges method. You will still be using SaveChanges method. Only difference is that you are not operating on the collection object. First you will use LINQ query on Data Context to get instance of the record object. Then make the changes to that object and then call SaveChanges. Entity Framework keeps track of what records are being changed when you change any property value of an object. When you call SaveChanges, it prepares a list of objects that need to be updated. And then take appropriate action. All the tracking is transparent to you. The following code snippet shows how you can update record using Entity Framework.

protected void OnUpdate(object sender, EventArgs e)
 {
     if (!ValidateInput())
     {
         ErrorMessage_Label.Visible = true;
         return;
     }

     decimal billRate = 0.0M;
     if (!string.IsNullOrEmpty(BillRate_TextBox.Text.Trim()))
     {
         decimal.TryParse(BillRate_TextBox.Text.Trim(), out billRate);
     }
     var displayName = AntiXss.HtmlEncode(DisplayName_TextBox.Text.Trim());
     if (string.IsNullOrEmpty(displayName))
     {
         displayName = AntiXss.HtmlEncode(FirstName_TextBox.Text.Trim());
         if (!string.IsNullOrEmpty(AntiXss.HtmlEncode(LastName_TextBox.Text.Trim())))
         {
             displayName += string.Format(" {0}", AntiXss.HtmlEncode(LastName_TextBox.Text.Trim()));
         }
     }
     var dataContext = new PMDataContext(Global.ConnectionString);
     var member = (from memberData in dataContext.Members
                   where (memberData.CompanyId == _thisCompany.CompanyId 
                             && memberData.MemberId == _thisMember.MemberId)
                   select memberData).First();

     member.MemberFirstName = AntiXss.HtmlEncode(FirstName_TextBox.Text.Trim());
     member.MemberLastName = AntiXss.HtmlEncode(LastName_TextBox.Text.Trim());
     member.MemberDisplayName = displayName;
     member.Active = _thisMember.Active;
     member.Deleted = _thisMember.Deleted;
     member.BillingRate = billRate;
     member.Availability = Convert.ToInt32(Availability_Dropdown.SelectedValue);

     try
     {
         dataContext.SaveChanges();
     }
     catch (Exception ex)
     {
         // TODO: Log the exception.
         System.Diagnostics.Debug.WriteLine(ex.Message);
     }
}

The implementation gets record for a specified Member using LINQ query. Then updates various values. And at the end calls SaveChanges. Very simple and straightforward process.


 

Views: 561

Tags: , ,

.Net | ADO.Net | LINQ

How to map custom class name to database table with Entity Framework

by Naveen 17. November 2011 08:40

In earlier post, How to insert records in database using Entity Framework, I discussed how you can use code first approach to create a POCO (Plain old CLR object) and then use data context to manipulate the tables. In that example POCO name was one to one match with table names in the database. Entity Framework was able to map the table with class name without any problem.

But you will always have cases where table names will not match with class names. This will happen if you are trying to reuse some existing code where classes were created based on some older schema. But now you have database tables that have totally different names. Another example, which I will use in this discussion, is using ASP.Net membership provider tables and procedures. You will notice that each database table is prefixed with aspnet_ by default. Now if you have classes with named like aspnet_Applications in your project, it will violate all the coding standard constraints and policies. And if you have some TFS check-in policy in place then you are out of luck because all policies will be violated.

There is a simple solution to this problem. You can create your POCO names to comply with standard naming convention. For example in my application, I want to query aspnet_Applications table but I want to keep my class name as Application. Following code snipper shows how I defined my class.

using System.ComponentModel.DataAnnotations;

[Table("aspnet_Applications")]
public class Application
{
 public Guid ApplicationId { get; set; }
 public string ApplicationName { get; set; }
 public string Description { get; set; }
}

I added TableAttribute to the class and set the name of the actual database table to which this class maps to. To add this attribute you will need to include System.ComponentModel.DataAnnotations in your class file.

If you do not add this attribute, you will see an exception like below when trying to query data context for the objects from that table.

Invalid object name dbo.Application

You can follow the same approach to map data base fields to class properties that do not match one to one.


 

Views: 602

Tags: ,

.Net | ADO.Net | LINQ

How to insert new records using Entity Framework

by Naveen 16. November 2011 16:44

In my previous post about using ORM tools, I talked about how to add records to table using Linq to Sql. Recently Microsoft released new version 4.2 of Entity Framework. In this post I will discuss how we can add new records in the database using EF 4.2. In this discussion I will also talk about some of the subtle issues that arise when your table names have some pluralization issues.

Code First Approach

In this post I will be using Code First approach. In this approach you will create your model class first. And then we this class will get mapped to table in the database. You can use this approach to create new table in the database as well. Since I already have my tables creates in database, I am going to concentrate on showing insertion of record to that table.

Create Data Model Class

I will start by creating class representing the object(s) that I want to manipulate in my database. I have create Member class that corresponds to Member table in database.

public class Member
{
   public int MemberId { get; set; }
   public string MemberFirstName { get; set; }
   public string MemberLastName { get; set; }
   public string MemberDisplayName { get; set; }
   public DateTime CreateDate { get; set; }
   public bool Active { get; set; }
   public bool Deleted { get; set; }
   public decimal ? BillingRate { get; set; }
   public int ? Availability { get; set; }
   public int CompanyId { get; set; }
}

In subsequent posts I am going to refine this class to add some related objects to show concept of lazy loading. But for this post, this class definition will suffice. Each property in this class corresponds to fields in database table.

Create Data Context

Next I will create the work horse of entity framework, a class that provides data context for all the operations.

using System.Data.Entity;

public class PMDataContext : DbContext
{
   public PMDataContext() : base() { }
   public PMDataContext(string conn) : base(conn) { }
   public DbSet<Member> Members { get; set; }
}

The class is derived from DbContext class. And you will have to add using statement for System.Data.Entity namespace to work with DbContext class. So far so good and it look very much list what we did for use of Linq To Sql. The difference is that these classes look leaner as compared to what Linq to Sql class wizard generated.

Execute Operation To Add New Record

The operation to add new record using Entity Framework is same as to what I did for Linq to Sql. The difference is that method name is slightly different. In EF you will call SaveChanges. Following code snippet is from web application that I am working on at the moment that uses EF. This code adds new Member record in the database.

protected void OnAddMember(object sender, EventArgs e)
{
   if (!ValidateInput())
   {
      ErrorMessage_Label.Visible = true;
      return;
   }

   decimal billRate = 0.0M;
   if (!string.IsNullOrEmpty(BillRate_TextBox.Text.Trim()))
   {
      decimal.TryParse(BillRate_TextBox.Text.Trim(), out billRate);
   }
   var dataContext = new PMDataContext(Global.ConnectionString);
   var member = new Member()
   {
     MemberFirstName = AntiXss.HtmlEncode(FirstName_TextBox.Text.Trim()),
     MemberLastName = AntiXss.HtmlEncode(LastName_TextBox.Text.Trim()),
     MemberDisplayName = AntiXss.HtmlEncode(DisplayName_TextBox.Text.Trim()),
     Active = true,
     Deleted = false,
     CreateDate = DateTime.UtcNow,
     CompanyId = _thisCompany.CompanyId,
     BillingRate = billRate,
     Availability = Convert.ToInt32(Availability_Dropdown.SelectedValue)
   };

   dataContext.Members.Add(member);
   try
   {
      dataContext.SaveChanges();
      Response.Redirect(_returnUrl);
   }
   catch (Exception ex)
   {
     // TODO: Log the exception.
     System.Diagnostics.Debug.WriteLine(ex.Message);
   }
}

As you can see the code is pretty straight forward. But when I executed SaveChanges statement, I got the following exception message thrown at me.

Invalid object name dbo.Members

The message suggests that Entity Framework thinks that I have a table with Members where I am trying to add records. The problem is that EF is designed to match collection property name to table in database. Since my property is Members that contains all records, so EF maps it to table name Members. This is because of Pluralization convention in entity framework. To fix this problem, you will need to remove that convention from your DbContext. So I had to modify the class as shown below.

public class PMDataContext : DbContext
{
 public PMDataContext() : base() { }
 public PMDataContext(string conn) : base(conn) { }
 public DbSet<Member> Members { get; set; }

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
   base.OnModelCreating(modelBuilder);
   modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
 }
}

After this change, SaveChanges executes without any problem. As you can see, use of Entity Framework 4.2 is pretty straight forward to add new records to the database.


 

Views: 658

Tags: ,

$1.99 Website Hosting- Go Daddy Proud Sponsor of Danica Patrick

Smart Phones Poll

What smart phone do you currently own?





Show Results

Month List

Powered by BlogEngine.NET 2.0.0.49
Theme by Naveen Kohli