Value is not valid for OracleType when setting to 0 in .NET…..

So you thought you could do a an easy new OracleParameter(“p_id”, 0) and have it work, right? Well, that would be too easy.

If you do that, you get a nice nastygram from the class:.

'new OracleParameter("p_id", 0)' threw an exception of type 'System.ArgumentOutOfRangeException'
 base {System.ArgumentException}: {"Value is not valid for OracleType: 0.rnParameter name: oracleType"}
 ActualValue: null
Message: "Value is not valid for OracleType: 0.rnParameter name: oracleType"

So, how do you fix this? Easy enough, but goofy.

int zero = 0;
var param= new OracleParameter("p_ID",zero);

This works quite well. Oh yeah, casting 0 to int doesn’t work either. I know you were thinking about it. (int)0.

WCF Service failing with “The server has rejected the client credentials”. Why doesn’t the server like me?

I spent the past couple of days dealing with faultexceptions being thrown by our WCF service that was being consumed by our Indian team. It worked for all the US teams, but for some reason the Indian team kept getting faultexceptions on the service. The proxy seemed to disguise the error and was throwing an error about the channel being in a faulted state.

So down the rabbit hole I go. I created all sorts of test rigs; to no avail. I finally get a developer to build a debug version so we can drop right into the code. He is able to find an inner exception saying, hey, I don’t like your credentials. The service didn’t have any authentication on, so I thought.

Well, lesson to be learned is the TCP services seem to default to windows security mode. Yes, surprising as it is, if you don’t set the security configuration you get windows authentication. What does this mean? As soon as a person outside of your domain tries to invoke the service, they get their butts handed to them. No service for you!

So, how  do you fix this? Easy, simple config change. Not one piece of source code needs to change.
Remember, you must change the binding on the SERVER and the CLIENT.

<system.serviceModel>

    <client>

      <endpoint address               = "net.tcp://localhost/MyService"

                binding               = "netTcpBinding"

                name                  = "MyService"

                bindingConfiguration  = "myBinding"

                contract              = "IMyContract" />

    </client>

    <bindings>

      <netTcpBinding>

        <binding name="tcp_ myBinding ">

          <security mode="None"></security>

        </binding>

      </netTcpBinding>

    </bindings>

  </system.serviceModel>

So if you look at the config above, the key is the Security Mode tag. You need to go to your client and server bindings and set this to None.

<security mode="None"></security>

Once you have that set, ON BOTH SIDES, your non-domain users can actually start calling your WCF service. Remember to restart the service after you make the configuration file changes!

EntityDataSource and Relationships, why oh why did you not bring along my relationship?

I spent about 3 hours cursing up a storm over some data binding I was doing using the EntityDataSource against my Entity Framework context. I was feeling lazy and using the declarative data sources to bind against my grid for some automatic operations.  So, should be easy right? Slap on the data source, bind to the grid, add the other data source for the lookups and bind that to the column.

So why was my column always showing the wrong value? Hmm….It was always the first value in the list? hmm…So I thought my grid was defective and went down the route of beating it up. The kicker was I could edit the record, and the newly set value would go into the database. It would never reflect on the grid though. This was rediculously annoying.

I finally gave up and created a new data source and ran my own Linq on the context to pull the objects. Thats when the Ah HA! moment came. I typed my INCLUDE off the context to pull the relationships in.

WAIT! You tell me. Wasn’t that on the data source setup wizard screen when you said pick all the properties? NO. No it isn’t. All the relationships are missing as selectable items on that screen. I guess the EntityDataSource is not usable in these scenarios then, right?

Wrong. After banging your head on the wall a few more times, you gingerly go to the properties window of the EntityDataSource object you created. You delicately go to the Include property and type in the name of the property.

What a pile of crap! I spend 3 hours and multiple rewrites to figure out I could have typed the 8 characters in on the property window and been good to go.

Well, it all works now. I just wish that option would have been in the wizard. If I am going the lazy route with declarative bindings, I want to be able to go full lazy.

What is the Visual Studio 2008 resolve using hotkey/shortcut..

I hate manually typing the using statements at the top of my classes so I invariable just type the class/object name for the type I want to use then use the Visual Studio resolve function. Right click -> Resolve.

Well, its a real pain to move to the mouse to resolve when I am typing away. So I finally got off my laurels and looked up the keyboard shortcut.

Here is the magic: CTRL + .

That’s right, CONTROL PERIOD. <insert female joke here ;)>

Hope this saves you a few clicks.

How to view an exception that wasn’t explicitly caught in C#?

So, you decided to do that catch statement without actually declaring the Exception err variable. Sure, code analysis said you weren’t using it. You didn’t want to log it, and you just thought you wanted to swallow the error whole and never see it again. Until…..

Wow, it keeps crashing in the Try block and you have no access to the error when it hits the catch now. What to do? Never fear.

Open your immediate window. Debug->Immediate.
Type $exception then hit enter.
Yep, there is your exception staring at you in all its glory.

Enjoy!

Entity Framework and Views.. Too many keys on the keychain…

I am currently working pretty heavily with the Microsoft Entity Framework for .NET. I just ran into a nice quirk in the Model Wizard for Views.

Well, it seems the model wizard is not able to intelligently determine the primary keys for a view so it resorts to deciding that any NON NULLABLE field must be a primary key. Retarded…yes.

So how to fix this? Well, as long as you don’t mind never using the wizard again you can go in and remove the entity key flag off the conceptual model fields and then delete the key references on the storage model. This all in the XML editor naturally, because of course you can’t do anything useful int the modeler.

Note: Once you fix your keys, if you rerun the Model Wizard to import/refresh tables, you will have the pleasure of hand editing the file again for all your views.

Will this be fixed in 4.0? We will wait and see

Where did that Visual Studio 2008 menu go….

So I was working in Visual Studio had a hankering for debugging an already running process. Easy right? Debug -> Attach to Process. Well, it’s not so easy to do when the menu option dissapears. I pulled up my Debug menu and it had 4 options. Windows, Start,Step Over, Step Into. Hmmm.. missing something there right.

Well, after pulling a few hairs out I figured out how to get my Attach to Process option back.

Its painful but effective. Tools -> Import and Export Settings. Reset to Visual Studio default. Pick the best generic settings and finish the wizard.

All your menus will be back to normal. You just lose all of your keyboard shortcuts and custom settings you painstakingly setup.

.NET Illuminator v1 Alpha Released to the wild

So….I finally decided to release my alpha version to all you hooligans who want to see whats under the hood of fellow .NET’ers applications. You can use .NET Illuminator to see all the UI objects in another .NET application and even manipulate them. Yes, pretend like you are in Visual Studios Form Designer and just start viewing and changing properties.

You can also view all connection strings the application has used to any SQL  servers.

I will post more when I add more.  Happy hacking!

Click here for .NET Illuminator Page

Let’s all jump into the pool..The SQL Connection pool that is..

I was out swimming in the data pool and I started thinking to myself, how many people are sharing the same pool without me even knowing they are there? How did I even get into the pool? And why is the water so cold?

Well, if you are using ADO.NET with SqlConnection , you are playing in the pool to. ADO.NET is a pretty smart animal. It realizes that if you are going to be connecting to a database a lot, then its probably a good idea to keep the connection to the database server open awhile. It does this behind the scenes, so when you create multiple data connections, it only really grabs one from the available pool of connections and uses those.

So….with that in mind, I started thinking about how I can tell what data connections an application has used and who is swimming in my pool. Coupling that with the brainstorming involved in .NET Illuminator, I came up with a very nice and simple piece of code that grabs all the connection strings from the Pool and throws them in rafts for you to see.

Why might this be handy for .NET Illuminator, well…Its always interesting to see what data connections an app has made and what the connection string is for them 🙂

Here is my simplistic example of using C# with .NET to walk the SQL pooled connections and return their connection strings.

         /// <summary>
        /// Loads all pooled connection strings.
        /// </summary>
        /// <returns></returns>
        public static List<string> LoadAllPooledConnectionStrings()
        {
            try
            {
                SqlConnection connection = new SqlConnection();

                FieldInfo connectionFactory = connection.GetType().GetField("_connectionFactory", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Static);

                object cFactory = connectionFactory.GetValue(connection);
                FieldInfo connectionPoolDictionary = connectionFactory.FieldType.GetField("_connectionPoolGroups", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);

                object dictPools = connectionPoolDictionary.GetValue(cFactory);

                Type poolDictionaryType = dictPools.GetType();
                PropertyInfo pooledKeys = poolDictionaryType.GetProperty("Keys", BindingFlags.Public | BindingFlags.Instance);

                object keys = pooledKeys.GetValue(dictPools, null);

                List<string> allKeys = new List<string>();
                foreach (object key in (IEnumerable)keys)
                    allKeys.Add(key.ToString());
                return allKeys;
            }catch(Exception err)
            {
                throw err;
            }
        }

So…What did we learn? Just because you don’t see the pool….smell the chlorine…or even get wet, you open a data connection and you have jumped all the way in.. and left your stench behind in the water..

Happy swimming!

System.Diagnostics.Stopwatch is no longer my friend….

So..I have been thinking for quite some time, “Gee, wouldn’t it be nice to have a nice and easy to use timer class built right into the framework?”. I decided to go and use the lovely Stopwatch class to start building a lot of timing routines into my applications for debugging and logging purposes. The syntax was so easy and beautiful.


var sw = new System.Diagnostics.Stopwatch()
sw.Start();
DoWork();
sw.Stop();

Can’t get much simpler than that, right? Well…..that is if the stopwatch returned reliable results….

It seems on one our computers we run this code and a 23 second process returns 10.5 seconds…Yeah, same thing I thought.. What a bunch of crap!

So, I read something about Processor Affinity and CPU clock stepping that may be causing the issue. Either way, I don’t want to have to set the threads processor affinity or try and manage the CPU’s frequency just to take a simple time measurement……Back to the old


DateTime start = DateTime.Now();
DoWork();
TimeSpan elapsed = DateTime.Now() - start;

I know…not much difference, but didn’t the Stopwatch look so much cooler?