Thursday, October 3, 2013

Connect to Wireless Network from Command Prompt or Terminal

Why?

If you're Windows o Mac OS X is not configured to connect automatically to your wireless network, it can be a bit tedious to use the GUI in either OS to connect to your WiFi. Here are two commands to connect to a a wife:

Windows:

The netsh command and its subcommands is a powerful way to interact with windows networking subsystem. Follow this http://technet.microsoft.com/en-us/library/cc755301(v=ws.10).aspx for more on this command. Here is how to connect to a WiFi:

The command:

netsh wlan connect name=your_wireless_network_profile_name ssid=your_wireless_network_ssid

If you are not sure about the network profile (normally it's the same as the ssid) you can use netsh command to list all profile:

netsh wlan show profiles

If you want to see the available networks then use:

netsh wlan show networks

Netsh is a great command and can do a lot more.

Mac OS X:

The networksetup command is a powerful command in the Mac OS X environment to deal with network setup. 

To connect to a wireless network for example:

networksetup -setairportnetwork hardware_port your_wireless_network_ssid your_password

A typical value for hardware_port (wireless) is en1 (ethernet interface # 1).

There is more to this command for sure.

Tuesday, September 24, 2013

Array Traversal i++ vs i--

Array Bounds-Check Removal


One of the optimization done in .NET CLR is removing bounds-check when accessing arrays. It's done in certain cases and this excellent blog post discusses these cases (http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx)

Something that I found really interesting is that it matters as far as bounds-check elimination is concerned whether arrays traversed in an increasing or decreasing order.
for(var i=0;i<someArray.Length;i++){ //array access using i} vs. for(var i=someArray.Length-1;i>=0;i--) { //array access using i }

 So in accessing the array within with the first loop, the bound check is eliminated but in the in the second case (decreasing; i--). The mentioned posts recommend traversing the array in ascending order whenever possible.

Another useful advice from the post is that using the Length property in the condition statement of a for loop is better than using a local variable (unless the local variable is intended to access a subset of the array of course). Interesting stuff.



 
 
 
 

Tuesday, September 17, 2013

Generate SQL to Search All Columns in a Table

If you are searching for a given value in a table with numerous columns not knowing which column could match the value, you'll find it tedious to write as many OR clauses as columns in your table.

Here is a simple T-SQL script to generate SQL code with all the column names and the OR clauses.


 declare @sql nvarchar(max);
 select @sql = 'select * from MY_TABLE_NAME where ';
 select @sql = @sql + c.name + ' = ''value'' or '
 from sys.tables t 
  inner join sys.columns c on t.object_id = c.object_id 
  and c.system_type_id in(231,167) --this restricts target columns to just nvarchar,varchar types
  and t.name = 'MY_TABLE_NAME';
  
 select @sql = left(@sql,len(@sql)-3)+';'; -- remove the last or
 print @sql;

MY_TABLE_NAME has to be changed to your specific table of course. This script can be improved to add conditional casting. When the column type (system_type_id) is string then no casting is needed but when integer then convert to varchar and when the type is datetime for example then use convert(varhcar(10),101) for example.

Sunday, July 21, 2013

C#/VB.NET Optional Parameters and the MissingMethodException Exception

Optional Parameters 

Optional parameters is a useful feature in C# and VB.NET languages. Adding an optional parameter to a method can sometimes make re-factoring a bit easier and less invasive. There is however a catch one should know. I ran into this situation a few days ago and here is my attempt to describe it:

Initially

Suppose you have a library, let's call it OptionsLib. In this class library lets say we have class called Common. In this Common class there is a method call DoSomeWork whose signature looks initially like

public void DoSomeWork(){
   DoStepOne();
   DoStepTwo();
   DoSomeOtherStep();

}

Now we have a consumer of this OptionsLib library and let's call it OptionsClient and it exists in its own assembly. So we have two assemblies: OptionsLib v1.0.0.0 and OptionsClient v1.0.0.0.

New Version: Minor Change

You've decided to make a minor change to your OptionsLib.Common class. Namely you wanted to add some conditional logic to the DoSomeWork method. So the new method would look something like:

public void DoSomeWork(bool someCondition = true){
   DoStepOne();
   DoStepTwo();
   if(someCondition){
       DoSomeOtherStep();
   }
}

There are probably other libraries that depend on the OptionsLib library so making the new parameter optional alleviates you from having to change the way the method called everywhere. The existing behavior is retained by making the new parameter optional and giving it a default value of true. So now re-compiling the whole solution will yield no errors as a result of the new optional parameter. The compiler will realize the new parameter is optional and will take care of passing the default value for you everywhere the method DoSomeWork is called.

The Issue: System.MissingMethodException

Let's say you found a bug in some of the libraries that use OptionsLib library or a change is made to one of its clients and you wanted to push that change to existing installations. In our example, suppose we may have fixed some bug or added a feature to the OptionsClient.dll assembly. So now OptionsClient.dll is compiled against the new version of OptionsLib, the version with the optional parameter change. In the existing installations however, the OptionsLib does not have the optional parameter we added.

For the most part placing the new OptionsClient.dll assembly in existing installations will be OK. It will find its referenced assemblies in the existing installations and everything seems to work fine. Until it starts calling the method DoSomeWork which in the new version has an optional parameter but not in the existing version. So in reality the new OptionsClient call of DoSomeWork looks like:
...DoSomeWork(true); // my understanding is that the compiler passes true for you                                               // because it's optional and the default is true
When the above call is made the runtime will complain because there is no method named DoSomeWork in v1.0.0.0 of OptionsLib that takes a boolean; there is one with no parameters at all but it's not what was called. The runtime then throws the System.MissingMethodException exception. So you'll realize that you may need to also recompile and ship the OptionsLib v1.0.0.1 the one with optional parameter

I Learned

Optional parameters are useful but sometimes adding them to a library can break dependents assemblies on this the changed library when the dependent assemblies are deployed alone without the changed library. I think I'd prefer method overloading when re-factoring.

http://msdn.microsoft.com/en-us/library/dd264739.aspx optional parameters
http://msdn.microsoft.com/en-us/library/zk1a255s(v=vs.80).aspx MissingMethodException

 

Sunday, June 2, 2013

Entity Framework Code First Does Not Create Database

Where is the Database?

I spent more time than I should have trying to troubleshoot why my database not being created. My DbContext-based class looked like:

    public class TakeNoteContext : DbContext
    {
        public TakeNoteContext()
            : base("name=TakeNote")
        {
            
        }
        public DbSet Posts ;
        public DbSet Users;
        public DbSet PostTypes;
        public DbSet SourceTypes;

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //base.OnModelCreating(modelBuilder);
            //an alternative to using attributes
            modelBuilder.Configurations.Add(new PostConfiguration());
        }
    }

Everything looked right to me, initially. And later I noticed that I was using fields and properties for my DbSet data members.

The correct way:

    public class TakeNoteContext : DbContext
    {
        public TakeNoteContext()
            : base("name=TakeNote")
        {
            
        }
        public DbSet Posts { get; set; }
        public DbSet Users { get; set; }
        public DbSet PostTypes { get; set; }
        public DbSet SourceTypes { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //base.OnModelCreating(modelBuilder);
            //an alternative to using attributes
            modelBuilder.Configurations.Add(new PostConfiguration());
        }
    }

The interesting thing is that the database can be created if I call ctx.Database.CreateIfNotExists(); directly even if I used fields. There might other reasons why your database is not created. My sure your connection is correct, for example.

Monday, May 27, 2013

WordPress Links not Working after Site Move

Reset Permlinks

I helped moving a wordpress blog from one directory to another (from a directory to its parent) and after the move, all links stopped working and returned a 500 Internal Server Error. Notice it was not a 404 file not found error.

After some search, it was suggested on a forum (sorry I don't have the link) that reset permlinks fixes the issue. This is important if the site url and home changes. Basically from Settings -> Permlinks , hit Save. This will cause all permlinks to reflect the new url.

Having all links broken was scary. I hope this tip helps someone.


Thursday, May 2, 2013

Architecting .NET Applications for the Enterprise

Microsoft® .NET: Architecting Applications for the Enterprise (amazon)


A great book, I think, on software architecture using the .NET framework


The first part of the book is on Principles of software architecture. The seconds part is on the "Design of the System". This second part is then divided into a number of chapter. Each chapter is dedicated to one layer of the system. Business layer, Service layer, Data Access Layer etc.

My notes here are on the design of the business layer. The authors presented a number of patterns starting with the simplest and progressing to the most complex one that's suited to applications where the business logic involves much more that data insertion and retrieval.

BLL Patterns

Transaction Script Pattern

Think of an ASP.NET page with controls whose events are handled by code-behind (or MVC actions) code. The code then interacts with data store according following a script of known steps. This is a very simple pattern with no object-oriented design.

Command Pattern

The authors then talk about the command pattern as one step above the TS pattern. Each action that the system does is incapsulated in a class with a common interface. What's interesting here is that since actions are represented as classes, actions or a series of them that participating in a transaction, can be serialized.

Table Module Pattern

What's interesting about this pattern is that the BLL logic is grouped into components each of which deal with one entity. The component or class does not represent the entity but rather serves as a gateway to the table holding the instances of that entity in the database. Code following this pattern tends to be heavy on DataSet or similar data container but not a generic .NET container. DataSets are awful. 

Table Data Gateway Pattern

In this pattern, another layer is added between the BLL logic and the code directly talks to the database, hence Gateway.

Active Record Pattern

Each data entity is represented by class. Unlike the TM pattern, what is represented here is the individual rows and not the entire table. This allows for use of .NET generic containers. 

A class represents a row and all the logic that can be done on that data. The data handling (read,write, update and deleted) can be done either with this class or in separate DAL specific class.

The simplicity of this pattern, its cleanliness and its strongly-typed nature of representing entities make it a good choice for applications that are not very complex. Have said that however, I recommend taking a look at http://misko.hevery.com/2009/06/29/active-record-hard-to-test/.

Interestingly, the authors talk about LINQ-to-SQL and how it can be considered an Active Record pattern implementation.

Domain Model Pattern

When the complexity of a system grows and business logic involves operations that far exceed interactions with the database, the DM pattern is ideal. The focus here is on modeling the domain problem into a set of interconnected objects. The focus is also on the logic and interactions between these objects with no regard (at least at the BLL) to how data is persisted. 

Summary

A few patterns caught my interest while reading the Microsoft® .NET: Architecting Applications for the Enterprise. These patterns are primarily used when designing the business logic layer. Patterns discuss include, Transaction Script, Table Module, Active Record and Domain Model.