A Simple Method to Clone an EntityObject

Written by Brad Foley. Posted in .NET Development

 

I’ve just come across a problem where I needed to clone an Entity and add the duplicate value to the context only changing one property. I don’t know where I got this from originally, but I’ve made tweaks to it, and it works like a charm.

public static EntityObject Clone(EntityObject entity)
        {
            var type = entity.GetType();
            var clone = Activator.CreateInstance(type);

            foreach (var property in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.SetProperty))
            {
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference<>)) continue;
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>)) continue;
                if (property.PropertyType.IsSubclassOf(typeof(EntityObject))) continue;

                if (property.CanWrite)
                {
                    property.SetValue(clone, property.GetValue(entity, null), null);
                }
            }

            return (EntityObject)clone;
        } 

This is a simple method that could even be made an extension method. Enjoy!

A Very Simple Introduction to the Task Parallel Library (TPL) in C#

Written by Brad Foley. Posted in .NET Development

So many times I have shunned away from doing Async programming. Most commonly because the programs that I write are simple and needed in a hurry. Even though using Async would have allowed for a better user experience and better performance. I never have been a fan of the current Async programming models, however TPL has caught my eye. So lets look at a few quick examples…

So, in my first example I have two simple web services that get the same data from different sources. Neither is particularly reliable or fast, so what I want to to is to hit both at the same time, and take which ever one comes back first, that way I can provide the best user experience. I’ve done this through a simple console application.

 static void Main(string[] args)
        {
            List<Task> tasks = new List<Task>();
            CancellationTokenSource cancelToken = new CancellationTokenSource(); 

            string result = String.Empty;

            Task t_MethodA = Task.Factory.StartNew(() =>
                {
                    result = Services.GetResultsMethodA();
                    cancelToken.Token.ThrowIfCancellationRequested(); 
                },cancelToken.Token);
            Task t_MethodB = Task.Factory.StartNew(() =>
                {
                    result = Services.GetResultsMethodB();
                    cancelToken.Token.ThrowIfCancellationRequested(); 
                },cancelToken.Token);

            tasks.Add(t_MethodA);
            tasks.Add(t_MethodB);

            Task.WaitAny(tasks.ToArray());
            cancelToken.Cancel(); 

            Console.WriteLine(result);
            Console.ReadKey();
        }

Now for you windows programmers, lets look at a quick WPF example where were doing to do a simple Async call to grab some data, and place it in a text box for the user to later manipulate.

private void button1_Click(object sender, RoutedEventArgs e)
        {
            button1.Content = "Processing...";
            button1.IsEnabled = false;

            Task t = Task.Factory.StartNew(() =>
                {
                    System.Threading.Thread.Sleep(5000);

                }).ContinueWith(o => 
                {
                    button1.Content = "Process";
                    button1.IsEnabled = true; 

                },TaskScheduler.FromCurrentSynchronizationContext()); 
        }

Using this method the user can still access the user interface because the UI thread isn’t locked, and will allow them to update other fields, do other processing, and avoid the “(not responding)” dialog we’re all custom to.

Now something new, because I think retyping is annoying, I’m putting my samples solution on CodePlex located here.

Working With Databases In Visual Studio Without SQL Server Installed

Written by Brad Foley. Posted in .NET Development, SQL Server

When you get the following error after trying to connect to a database in Visual Studio 2010.

—————————
Microsoft Visual Studio
—————————
Could not load file or assembly ‘Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91′ or one of its dependencies. The system cannot find the file specified.
—————————
Simply download and install the following components.

Microsoft SQL Server System CLR Types – http://go.microsoft.com/fwlink/?LinkId=123721&clcid=0×409

Microsoft SQL Server 2008 Management Objects – http://go.microsoft.com/fwlink/?LinkId=123708&clcid=0×409

Microsoft SQL Server 2008 Native Client – http://go.microsoft.com/fwlink/?LinkId=123717&clcid=0×409

I run into this quite a bit when working on client provided developer workstations and they don’t find the need in installing a local SQL Server or the management objects.

The other alternative is to simply download and install SQL Server Management Studio.

ODAC Released with Entity Framework and LINQ Support

Written by Brad Foley. Posted in .NET Development

Oracle Data Access Components Released with Entity Framework and LINQ Support

The production version of ODAC 11.2 Release 4 (11.2.0.3) has arrived for Entity Framework and LINQ developers! It includes 32-bit and x64 versions with the option of using an automated installer or xcopy deployment.

The release incorporates Oracle Database client 11.2.0.3, which can access Oracle Database 9.2 and higher. Oracle supports Entity Framework and LINQ with Microsoft Visual Studio 2010 and .NET Framework 4, including Entity Framework 4.1 and 4.2.

ODAC New Features List

Getting User Information For all the users in an Active Directory Group.

Written by Brad Foley. Posted in .NET Development

A recent requirement came up for a quick bit of code to retrieve the names and e-mail addresses from an ActiveDirectroy group. I did this in code instead of power shell in order to be able to use these methods in further logic.

So here we go….

First we’re going to create a simple structure to represent the user information we need:

        public struct UserInfo
       
{
            public string DisplayName;
            public string Mail;
            public string Login;
        }

Next were going to create a simple entry point in which we will use to test our methods:

static void Main(string[] args)
{
    ArrayList ar = GetADGroupUsers("GroupName");

    List<UserInfo> users = new List<UserInfo>(); 
    foreach (string user in ar)
    {
        users.Add(GetADUserInfo(user));

    }
}

 

Now we will need to implement the two methods seen above. First the method to get all the users in a group:

 

static public ArrayList GetADGroupUsers(string groupName)
{
    SearchResult result;
    DirectorySearcher search = new DirectorySearcher();
    search.Filter = String.Format("(cn={0})", groupName);
    search.PropertiesToLoad.Add("member");
    search.PropertiesToLoad.Add("mail");
    search.PropertiesToLoad.Add("samaccountname");
    result = search.FindOne();

    ArrayList userNames = new ArrayList();
    if (result != null)
    {
        for (int counter = 0; counter <
                 result.Properties["member"].Count; counter++)
        {
    
            userNames.Add((string)result.Properties["member"][counter]);
        }
    }
    return userNames;
}

Now that we have the ArrayList of users, we will need to get the information about the users:

static public UserInfo GetADUserInfo(string userName)
{
    SearchResult result;

    DirectoryEntry de = new DirectoryEntry("LDAP://mydomaincontroller/"+userName);

    UserInfo ui = new UserInfo();
    ui.DisplayName = de.Properties["displayName"].Value.ToString();
    ui.Mail = de.Properties["mail"].Value.ToString();
    ui.Login = de.Properties["sAMAccountName"].Value.ToString(); 
    return ui;

}
And that’s it, now we have a nice list of users with their email addresses.

A great place to get started with .NET Micro Framework

Written by Brad Foley. Posted in .NET Development, .NET Micro Framework

I have long been an advocate of GHI Electronics and their development systems for use in my tinkering.

Today they announced something that I am going to add to my must have tinkering list.

The FEZ Spider Starter kit is now on the website for pre-order.

On a high level it includes:

So for anyone looking to get starting with device building, robotics and/or tinkering this is a great place to begin.

And the best part.. the current price is only $250.

To .Close() or .Dispose() on a SqlConnection

Written by Brad Foley. Posted in .NET Development

So it has been asked here around the office and I’ve heard it in many discussions. So I decided I would do a deep dive into when and why to use each. For the code examples, these are taken from .Net Reflector Pro. The framework version I will be using is .Net Framework 4. First lets look at a simple T-SQL Operation using a SqlConnection and SqlCommand object. We will also be implementing the using statement. So our code example starts out with a simple SELECT statement that retrieves the hostname from the database server.
using (SqlConnection oConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI"))
{
SqlCommand oCmd = new SqlCommand("Select HOST_NAME()", oConn);
oCmd.CommandType = System.Data.CommandType.Text;

oConn.Open();

string hostName = oCmd.ExecuteScalar().ToString();
}
Now in implementing this, it would appear as though we are leaving our SqlConnection both open and undisposed. However this is not the case. As outlined in the documentation for the using statement. The using statement ensures the correct use of IDisposable objects. So what is actually happening is that when your code is leaving the using block the Dispose method is being called. So lets take a quick gander at the Dispose method of the SqlConnection object.
protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}
Now you’ll notice that the Dispose method contains a parameter of disposing. However when the Dispose() method is called from the using statement no parameter is passed. So lets actually look at the base dispose method. For this we actually have to go down to the base class of System.ComponentModel.Component.
public void Dispose()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}
So here is where the magic happens, so you see that when the Dispose method is called, it turns around and calls the Dispose() method with the true parameter. When the Dispose method is called with a true parameter [Dispose(true)] the User Connection Options and Pool Group are both set to null, and then the connection is closed, and then, the resources are released. In summary, explicitly calling close before dispose, implements double work. It shows up in some patterns and design books as being the proper way to handle this scenario, however it is not. So when do we use the close, we’ll that’s simple, when we need to reopen the connection later, in an enumeration for example.