More RIA Domain Service difficulties with EF

clock April 3, 2009 03:45 by author Giovanni

Another error I recently ran into with RIA Domain Services and the Entity Framework model:

The type 'ProjectName.Web.YourType' already contains a definition for '_fieldName'
 
This is usually followed immediately by a second error (described the same way) except it shows the property name.  This seems to occur when a navigation link in EF is named exactly the same as the internal SQL Server column name.  For example, let's say you have a table with a field/column named ModifiedBy (represented as an int, and is a foreign key to another table), when the table is added to the EF model, it is represented as a navigation link.  If you decide to rename the link to "ModifiedBy", EF will allow this, but when RIA generates metadata for the client side, it will complain because, in the metadata, it internally creates both - the object for the navigational link as well as the internal type of the field.


Invalid member projection specification - RIA Domain Services

clock April 1, 2009 23:11 by author Giovanni

While working with RIA domain services and Silverlight 3 beta, I ran across a strange problem.  I would create the domain service based on my entity framework model, and the code generated was causing an error.  I verified that the entity framework ran on its own, but it took me a while to figure out why I was getting an error similar to the following:

Invalid member projection specification : Projection path 'MyTableId' is
invalid for member 'MyNamespace.Web.MyTable.MyTable'

This error message is not very friendly.  The reason why this happened is because inside the EF designer, I renamed the primary key in MyTable (we'll say from MyTableId to SomethingId).  EF has no problems with renaming the primary key field, and compiles without any problem on its own.  Unfortunately when you try to create a domain service, if you add the EF object along with other objects that associate to it (via the primary key), it fails to compile and gives the error message above.  Whatever magic occurs behind the scenes when RIA generates the client metadata, it does not like the primary key to be different.  The only workaround I know of is to rename it back to whatever it was.  Unfortunately, if you are trying to use RIA Domain services with an existing EF model that has changes to the primary key names, you may have to play with it to get it to work.



Securing Silverlight with Custom Forms Authentication

clock January 2, 2009 08:42 by author Giovanni

.Net 3.5 and Silverlight 2.0

I've been working on a Silverlight application with a colleague of mine (John Papa), and we wanted to create a secure login that would tell the hosting asp.net page to authenticate the user.  We looked at Tim Heuer's example and decided to go with a similar approach.  This basically involves hosting the WCF Authentication service in a web application, and then creating and using in Silverlight via a service reference.

The only issue is that Tim's approach uses the built in .NET membership provider which creates and uses a local SQL Express database.  Since the project I'm working on already has a database with user/pass information, I wanted to avoid creating a second database that would be used for nothing other than maintaining user and password info.  The solution to using your own database is to create a custom provider (i.e. inherit from the abstract class called System.Web.Security.MembershipProvider).  The amount of work required to do this depends on how much you need it to do for you.  If you want to be able to create your own users via the ASP.NET conifguration tool, you'll have to override and define many of the methods.  Since we only needed the very basic "Is this a valid user" scenario, it only involved defining two methods and one property.

public class MyMembershipProvider : MembershipProvider
{
    private string _connectionString;
    
    public override void Initialize(string name,
                    System.Collections.Specialized.NameValueCollection config)
    {
        _connectionString = config["connectionString"];
    }
    
    public override bool ValidateUser(string username, string password)
    {
        SqlConnection sqlConnection = new SqlConnection(_connectionString);
    
        try
        {
            sqlConnection.Open();
            string sql = "select Username from [UserTable] where Username=@User 
                    AND Password=@Pass";
    
            SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
            sqlCommand.Parameters.AddWithValue("@User", username);
            sqlCommand.Parameters.AddWithValue("@Pass", password);
            SqlDataReader sdr = sqlCommand.ExecuteReader();
            if (sdr.HasRows)
                return true;
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            sqlConnection.Close();
        }

        return false;    
    }

    public override string Name
    {
        get
        {
            return "MyMembershipProvider";
        }
    }    


    // override the rest below 
    ...
}
 

These are the main 3 things you need to override and define.  You must also override all of the other methods and properties, but for the ones you don't need, you can just throw a NotImplementedException() and leave it undefined.  You will want to change the code in ValidateUser() method to either use a stored procedure or change the SQL code to work with your table. 

The next step is to make your web application use this rather than the default provider.  In order to do this, you must add the following to your web.config within the <system.web> opening and closing tags.  You will need to make sure you set authentication mode to forms as shown below, and then add the <membership> tags

<authentication mode="Forms"/>

<membership defaultProvider="MyMembershipProvider">
    <providers>
        <add name="MyMembershipProvider" type="YourNamespace.MyMembershipProvider"
                connectionString="Data Source=(local)\SQLExpress;
                                  Initial Catalog=YourDB;
                                  Persist Security Info=True;
                                  User ID=test;Password=test" />
    </providers>
</membership>

Obviously, you will name your MembershipProvider something other than "MyMembershipProvider", and you will have to provide your own ConnectionString.

Before being able to access this via Silverlight, you'll want to test it.  The easiest way to test it is to use the asp.net Login control.  Since we defined our web.config to use our provider, the Login control will use our ValidateUser() method.  In a webpage, throw a simple asp.net Login control onto a page, so that the aspx page looks like this:

<div>
    <asp:Login ID="Login1" runat="server" DestinationPageUrl="~/HomePage.aspx">
    </asp:Login>

</div>

This is all you'll need to test it.  Place some breakpoints in your membership provider to make sure that it's being used. If everything works, you'll be ready for the next step.

Once you've verified it works, you are set to follow Tim Heuer's approach.  In your web project, you will want to add a new folder and call it Services.  Inside of that, add a new blank text file and call it Auth.svc.  Add the one and only line of text:

<%@ ServiceHost Language="C#" Service="System.Web.ApplicationServices.AuthenticationService" %>  

Follow the rest of Tim Heuer's example to edit the web.config file and create the service reference: Tim Heuer's Example

I have provided a sample application that does the entire process.  Click here to download



.NET Compile Issues with Service References

clock December 30, 2008 21:00 by author Giovanni

I was working on a Silverlight application and went to create a service reference to a WCF service.  The files generated properly, but when I went to compile I got a few errors that looked similar to below:

The type name 'MyService' does not exist in the type
'MyProjectNamespace.MyProjectNamespace'
C:\..\Service References\MyService\Reference.cs

I though it was very strange because this is code that was generated by Visual Studio .NET 2008.  After playing with it for a while, I decided to try creating the reference in another application with nothing in it.  It worked perfectly.  The problem I ran across has to do with naming issue.  The reason it failed is because there was a class with the same name as the namespace of the project.  For example, if the namespace is called EmployeeAdmin, and there is also an EmployeeAdmin class, everything will work until you create a service reference.  It throws an error because the interfaces are generated in the reference.cs file and look like this:

public interface MyServiceChannel : EmployeeAdmin.MyServiceRefName.MyService,
System.ServiceModel.IClientChannel
{ }

The compiler is getting confused and thinks you are inheriting from a type within the EmployeeAdmin class rather than the EmployeeAdmin namespace.  The only way to fix this, that I know of is to rename your class so that it doesn't match your namespace.  I'm sure there's some documentation somewhere that says to never name a class the same as a Namespace.  Under normal conditions, it wouldn't be a problem, but here's an example where it can be.



Updated Blu-Ray / DVD Comparison Utility

clock December 29, 2008 20:37 by author Giovanni

I updated my blu-ray/dvd comparison utility. The new version has a larger set of pre-loaded images to compare against. I also added the ability to create a link that shows the current images you are currently viewing.  If you are using the rectangle mode, the created link will be defined so that when others click on it, they can see the original rectangle you created which is good when trying to point out a particular location. Click the following link to check it out: Blu-ray/DVD Comparison

I'll be adding more features soon.



Problem with casting enums in LINQ to Entities

clock November 7, 2008 05:55 by author Giovanni

I've been working with the Entity Framework lately, and I tried to do a LINQ query that returned a record/object with an id that was equal to a value represented by an enum type.  I ended up getting the following error: "Unable to create a constant value of type 'Closure.type'.  Only primitive types ('such as Int32, String, and Guid') are supported in this context."
The code looked similar to below:

public void Test(MyEnum mEnum)

{ var s = (from mt in MyContext.MyTable where (mt.ID == (int) mEnum) select mt).FirstOrDefault(); }

Even though we are casting mEnum before evaluating it, Linq to Entities has a problem. 

 

The solution is to create an int variable prior to running the query as shown below:

public void Test(MyEnum mEnum)
{
    int myEnumValue = (int) mEnum;
    var s = (from mt in MyContext.MyTable where (mt.ID == myEnumValue) select mt).FirstOrDefault();
}
 
Based on this blog post I found: Matt Hidinger's Blog Post I found out why you cannot do high level comparisons (objects) or even functions that return primitives, so I guess we can extend this to say the casting of an enum doesn't work either!


Post SQL Saturday

clock October 25, 2008 15:32 by author Administrator

<p>I'd like to thank everyone for attending my SQL Saturday session on SQL Server Management Objects (SMO).&nbsp; A couple of you asked about the source code/project files.&nbsp; They can be downloaded <a href="code/SMOTest.zip">HERE.</a>&nbsp; The project is for Visual Studio 2008, but if you'd like I can make the 2005 project available as well. Let me know if you have any issue with compiling.&nbsp; Thanks!</p>



Books by Colleagues

clock October 23, 2008 22:44 by author Giovanni

Over the past few months, I've had the pleasure of tech reviewing some awesome books by my fellow colleagues. 

Brian Peek co-authored "Coding4Fun: 10 .NET Programming Projects for Wiimote, YouTube, World of Warcraft, and More".  Brian is well known for writing WiimoteLib, a fully managed .NET Library which allows anyone with .NET experience to integrate the Nintendo Wiimote into their applications.  There are two chapters in the book that use this library to create some fascinating projects.  One of them is a Wiimote controlled car, and the other is a Wiimote Whiteboard (video: Wiimote Whiteboard ).  By reading these chapters, you'll learn how to recreate those projects and will be given the necessary tools to do some amazing things with the Wiimote.  There are also a couple of chapters on game creation that I really enjoyed.  One of them teaches you how to create a game using the XNA framework that will run on the PC, Xbox 360, and the Zune.  The other is a Lego game created using Popfly, a Silverlight based game creator.  There's definitely a ton of cool stuff to learn from this book, and it's coming out really soon (November 15th).   Be sure to check it out.  You can pre-order it on Amazon.

For those looking to build business applications using the Silverlight 2, you should check out the upcoming book "Data Services with Silverlight 2" by John Papa.  John has done many presentations VS Live and frequently writes articles for MSDN magazine.  He also likes the Yankees, which is a plus in my book :)  The book is definitely geared towards the intermediate to advanced developer.  The first few chapters start off by teaching you the basics of Silverlight and data-binding. Afterwards you'll learn how to use Silverlight to communicate via WCF and consume REST services  via WebClient.  I especially like the last few chapters which put the knowledge you've learned to use in building full applications.  One of them is a Twitter client, and the other is a storefront that communicates with Amazon and their shopping cart system.  Speaking of Amazon, you pre-order this book here which comes out in December.

I definitely recommend both of these books depending on if you're looking to do some fun projects or if you're trying to build business applications in Silverlight. Check em out! 



SQL Saturday 2008, Orlando

clock October 22, 2008 21:25 by author Giovanni

I will be presenting at the 2008 SQL Saturday event in Orlando on October 25th.  The session will be an introduction to to SQL Server Management Objects (SMO).  For more information about attending this event, please visit the SQL Saturday web site: http://www.sqlsaturday.com/eventhome.aspx?eventid=11

as well as the schedule

http://www.sqlsaturday.com/schedule.aspx



Blu-Ray / DVD Image Comparison Utility

clock July 8, 2008 20:39 by author Giovanni

I've been working on a Silverlight application to compare two images. One from an HD source (such as blu-ray) and one from a standard definition source (DVD).  The goal is to see how much of an improvement one can expect if they were to repurchase a movie on blu-ray.

Right now, the tool offers a few comparison modes:

1) Dual View - This allows you to see two images as if they were 1.  When you move the mouse left or right, you can see more of one image and less of the other.

2) Swap View - This allows you to see one image in its entirety, and then, when mousing over, you can see the other image.

3) Rectangle View - This mode shows one image on the screen and allows you to draw, with your mouse, a rectangle.  The rectangle will show you part of the other image so that you can compare a specific portion of one image to the other.

The other thing you can do is enter the URL to two images and load them within this application.  As of right now, the images should be 1920x1080.  Images can be found on several AV forum websites.

I plan to add more features, and also to include links to existing more images for comparison.

Check it out.  You will need Silverlight 2 Beta 2 runtime in order to view this.

BD/DVD Image Comparison