Blog Archives

The Scourge of the Google Coder

This above all””: to thine own self be true, and it must follow, as the night the day, though canst not then be false to any man.

William Shakespeare, Hamlet

There is much the internet has given us but one area which many people seem to lose site of, as its integration with the every day seems so entrenched that one doesn’t know life without it.  Why did I quote Shakespeare and then talk about the internet?  I will get there.

But first, the title.  The Google Coder and I am not referring to the person who does development work at Google.  I am talking about a person so adept at finding any piece of code on the internet and using it within their application.  What is wrong with this?  Lots.

See the code below.

Module Main

    Private Const DO_NOT_EXCEED As Integer = 4000000
    Sub Main()
        Dim firstNumber As Integer = 1
        Dim secondNumber As Integer = 2
        Dim newNumber As Integer = 0
        Dim evenSum As Integer = 2

        'Display the first number numbers
        Console.WriteLine(firstNumber.ToString())
        Console.WriteLine(secondNumber.ToString())

        'While the new calculated number does not exceed the max amount
        While newNumber < DO_NOT_EXCEED
            'Calculate the next number in the sequence
            newNumber = firstNumber + secondNumber

            'ouput the new number
            Console.WriteLine(newNumber.ToString())

            'Flip the values around for calculation
            firstNumber = secondNumber
            secondNumber = newNumber

            'Check to see if the number is an even one
            If newNumber Mod 2 = 0 Then
                'Check to seed if the number does not exceed our max
                If newNumber > DO_NOT_EXCEED Then
                    'if it does, exit the loop
                    Exit While
                End If

                'add the number as it is an even number.
                evenSum += newNumber
            End If

        End While

        'output the answer
        Console.WriteLine()
        Console.WriteLine(String.Format("The sum of the even numbers in a fibonacci sequence that do no exceed {0}", DO_NOT_EXCEED.ToString()))
        Console.WriteLine(evenSum.ToString())
    End Sub

End Module

This is a solution to a problem posed;

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

This is my code, hand written without help from anyone.  The problem also comes from a site called Project Euler which sets out problems that is to be solved using a computer language.  The number of languages used is staggering for many they would be querying why are there so many languages when they all function to do the same thing, enable a computer to solve a problem.

But the purpose of it is to enable you as the developer to solve the problem using all your bags of tricks.  The problems are designed in a manner that often a large number are involved and often workout out problems based on these large numbers and working things out repetitively, the purpose built domain of the computer.  I might hear some people say, “why?”, “Why bother doing all that work, for nothing or doing all that work when you can easily look up the answer on Google?”.  True.

Why would I want to work out something on my own?  Why would I like to press submit on the answer screen and get a correct status up knowing that I did it, all by myself without any help and I got it right the first time.  I might not have been the first to do it, or written the prettiest code, the fastest code.  But to me, it isn’t the purpose.  When at work and I am writing code what is my objective with that specific problem.  Well to get the desire outcome.  It is a key for any developer to know the problem and understand it, then using the tools develop the solution.  Now often the problems are far more complex than determine the sum of the even Fibonacci numbers that is not greater than 4 million.

What would searching the answer or code to get the answer do for me?  Speed.  Nothing else, it doesn’t teach me anything, in fact I can go as far as saying many tutorials set up are great but don’t do much to aide in the learning process to enable proper retention, but that is something else.  I remember a while ago I competed in a coding competition which pitted developers against developers, with nothing but a barebones Windows PC and Visual Studio, no internet, no phones a pen and paper next to the PC.  We had to solve a problem, in a given timeframe.  I got into the top 10 but my time ran out.  But it was interesting to see that there were about 60% who dropped away after the first couple of problems, mutterings of it being impossible, anyone who solved it must have been cheating etc… I put these people into the Google coding camp, they were unable look for the solution on the internet and therefore they couldn’t work it out.

Is this detrimental to the overall coding quality?  Who knows?  I have seen some terribly written code in the years, not saying mine are works of art.  In fact the most efficient code is possibly not the easiest to maintain.  But it comes to this saying;

Only write the code that only you can write.

This comes back to the quote from Hamlet about being true to yourself.  In coding, one might think something like this

int myNumber = 10;
myNumber++;

is the only way to increment 10 by one.  But what about the following;

int myNumber = 10;
myNumber += 1;

Or;

int myNumber = 10;
myNumber = myNumber + 1;

Or

int myNumber = 10;
int i = 1;
myNumber = myNumber + i;

This is the issue as well.  Each of these do the right thing, they increment 10 by 1, but they use different methods to do this.  You might argue that the first version was the correct version.  But the others are also correct, they do the job, and if it is different to what you do, is it wrong no, it is an opinion.   But is that a problem for today where so many people believe their opinion is the right one and fail to understand that they have their opinion as well as I have mine and everyone else’s has theirs.

So, I guess what I am getting to is, write code, your way, the way you want to.  This might go against some other posts where I have spoken about terrible coding, but when you go to Google you aren’t writing your code.  By all means use it as a resource, find out the interface to the API workout what to put in, but don’t just copy and paste it as you will learn nothing.  Plagiarism is a problem with this world as we expand our use of the internet in all walks off life, it happened in University where there were always someone wanting to take the easy path, copy the code, rename the variables and move a few things around and boom, it is now yours.  But like all things it isn’t you if you do that, your techniques, approaches to development aren’t prevalent and if there is anyone who knows you will find that out.

Use the internet, but don’t rely on the internet and as technology becomes an ever increasing crutch the world relies on we will become more and more reliant on it being the correct answer to everything which puts Google (only because they are the dominant player in searching) in a position to fulfil any chosen agenda they wish and they are doing so, more than anyone knows.

The Patterns in a Practical Position

thc1bl12enPatterns, software development and the last 5-8 years have been pushing patterns.  Like Agile and SCRUMM (I know they are different), the new wave of development is the implementation of patterns into applications (they aren’t new, they are old but as we are developing more and more cross platform application across multiple devices it becomes more and more important to use familiar logic to hook our applications together with).

My biggest issue is not the use of them, they are great, they offer a wonderful reusable way of implementing common functionality throughout you application and then future applications with minimum fuss.  The best one recently I can think of is the MVVM/MVC and its purpose is to decouple the interface from the application, the purpose of this is to have a single backend code and the front end can be across multiple platforms and be native as they are all using the MVVM/MVC pattern.  But why am I?

Also note, MVC isn’t new (Circa. 1970s), but it has become an important part of mobile application development as you can’t always determine how you will connect to a backend and therefore keeping the UI separate means you, as the UI developer, only need to hook in the view to see it working and not concern yourself with calling specific methods, API calls or other more complex ways to get data in and out of an application.

So like Model View View-Model (Model View Controller) other pattern creep in and provide a mechanism to help make life easier for the developer, but there is one thing that irks me about new patterns.  Details, details and I will also say details.  It is all well and good to show me code, this is the way to implement the Snake Pattern; implement this interface, inherit these classes, create concrete classes from the interface, charm a snake and then, you will have your application.  Why?  Why am I doing this?  What purpose is the pattern in solving a problem, can this pattern be used on all applications across all platforms. 

I see code, it shows me how the person implemented this pattern.  I started by doing this, next I added this and this to implement this.  Next I, blah, blah and blah.  That is fine, following word for word code is fine, at the end I hit F5 and everything works, but why?    The one I see and it might be me and not understanding the purposes for such but a pattern was shown to me as a way of decoupling a class’s implementation from it’s abstraction enabling the two to vary from one another.  I understand abstraction, being a core component of object oriented programming, but the decoupling of it, my nature of the abstraction means no implementation of the class is in the definition of the abstraction (please tell me if I am wrong, I would like to know). 

But the remaining part of this article tells me how they did it, using a metaphor that isn’t common in the development of examples.  New technologies and learning new techniques and methodologies is difficult enough and keeping on top of them in an ever changing world is even more so.  So, telling me about useful patterns, Bridge, Adapter, MVC, whatever it might be is good, telling me it is for this, but tell me why, show me why, don’t make me just copy verbatim the code you have provided to make it work.  This means I won’t learn anything.

It has been a bug bear of mine over the many years of learning languages and learning how to program in those languages and it is the examples and the nature of telling me how to do this and that. 

When learning the basics, it is fine to say this is how you create variables

int varable = 1;

But when it comes to things more complex, give me more useful examples.  But it is a gripe and nothing to much other than this is the way I learn new things. 

The SWTOR Helper

swtor-logo-256x2561As many of you who read my blog might know, I am an ardent player of SWTOR.  I am also a software engineer/software developer/computer programmer or anything else that has to do with making bespoke software.  For ages I have been looking into ways to help the SWTOR community, more often myself get better use out of the game.  I have come up with, an idea for a helper.

Now, SWTOR doesn’t enable extensions to the game, they have done this possibly for the reason of preventing exploits.  When you open up your API for others to use, they will not always use it for purposes of good.  Which is OK, there is much that I am sure many people would like to do, but we are restricted.

That said, I feel that we can have a helper which I will be working on.  One such helper application is the SWTOR Unleashed (exca, 2012)application, this enables the moving of some files into a RAM Disk to help increase the performance of loading some areas. It works BUT has consequences when updating the files on patches.  So, I have decided, so sometimes to think of a way.  But I have had mixed success as it seems to stick out.

Upon looking into WPF the other way, I have found a way to help make this look like it is part of the in game experience but it is not.  This is my initial test, I will be adding more into it to make things better, I will put down information I will be planning on expanding on as well.

image

Well this is it for now.  What is the purpose of it.  Well right now it is very much a test for me to add more and more things.  It shows the current server time (this is based on the last played server, which while playing will be the current server).  It will also have a latest news link to the SWTOR site, which updates to the latest item on the news feed.

image

Well this doesn’t sound like much of a helper, and I guess in the current context it isn’t, but it has enabled me to look at the timers and use in WPF, knowing that the UI and application components are on different threads in some contexts.  It got me reading URLs to read some data and then also learning WPF which is the most important aspect of it.

So what are my plans?

I want this to be a helper.  Sure the latest news is handy but I want to monitor the SWTOR twitter feed to get updates there, especially around the maintenance patches.  I want to show the server status of your last server, which will get this from the SWTOR site. 

Include a timer/alarm which can notify players, who are grouped (which I need to look at as well, similar to the way the parsers work with raids).  But it can enable the setting of a guild alarm, E.g.  Raid at 2pm Server Time, or UTC.  Have the clock convert between all server times, East, West, England, West Europe and UTC.    This way it will prevent the constant questions, “is there a raid tonight?”

Number of Kills.  This is just informative.  Throughout all of your characters, how many have you killed?  Well I will include that, and the idea is to have that Tally as a scoreboard, see who has killed the most and even break it down into All, Elite, Champion, Boss and so on.

Links to the tips.  This means I am going to link to walkthroughs and videos of the major fights, World Bosses, Ops Bosses, Flashpoints and so on.

Guilds this is something that will get there, I am wanting to eventually put down a list of all guilds, link them in for their sites or Facebook pages and/or twitter accounts.  Provide people with in game contacts based on the server you are on, including the recruitment restrictions and so on.

Short cuts to DirectX Diagnostic Tool, Trace Route application, things that might be handy when having issues with the game.  But these will also include some checks to make sure you have the right versions of DirectX and provide a link to install them

The idea behind all of this is a genuine helper.  Since we can’t hook into the game, make it so there is more than enough reason to have people want to use, avoid the need to search for these tips or information only to be bombarded with all manner of information of which much of it might be useless.  Or have people in general chat tell you see Dulfy’s site, unsure why, since as thorough as this information is, it is still not that helpful, why should I stack this over this, rotations, why, do I just step 1, 2, 3, 4 and repeat in the fight.  There might be other tips that can help, I will hopefully be able to find all I need to and link it in.

But I will be adding in a few more elements and I will provide updates on it too.  But this is a work in progress and it is something I am hoping people will use or find useful.  But the first element I want to include is that scheduling, since in my guild, we are often seeing people ask, do we have a raid, when are the ops.  So, stay tuned.

References

exca. (2012, 07 09). SWTOR Unleashed (game files in RAM to improve performance). Retrieved 05 05, 2014, from http://www.swtor.com/community/showthread.php?t=529567

Windows Live Writer Reference Plug-in

image

You might think that I have been busy of late but in reality I have been really just cleaning some things up.  But that said, I now present the Windows Live Writer Reference Plug-in.  There are some small things that I need to include with it but it can look up a word you type in there, provide the term, part of speech, the definition and any examples it may have.

The reference plug-in will also take a selected word from the document and find the definition for that.

This has been a feature I have liked in Microsoft Word and there has been many instances where I have to open a new browser window and type in the search, this will help, especially if I am trying to find the specific word from my post.

Currently it uses the Stand4 web API.  So my goal is to enable further integration of this API to include translations, then to also enable the pasting back of that translated text into the blog post if required.

There is also a desire to add more APIs as I get more, currently I am able to use this API without many problems and it was by far the most simple one to implement without the need of jumping through copious hoops.

Before anyone can ask me about providing them with a copy of this plug-in I will need to fix a link onto the form to make sure that it works because currently it isn’t working.

If there are additional features you might want to see in this, please let me know and I will see what I can do about it.  Once I have fixed the link I will provide an updated post about this and then enable you to ask for it.

Windows Live Writer Timer Plug-in

This is the new plug-in I have for Windows Live Writer.  I made it as I was on the thought process of doing my NaNoWriMo novel, on my blog.  Interesting task to say the least and it would also mean perhaps those who occasion my blog might spur me on, spurn my efforts. 

image

It is a simple plug-in, and is one of my more complex plug-ins.  Wait a moment, how is it a simple plugin, yet a complex one.  Well it is complex from the programming stand point.  I chose to you what is a server timer within .NET.  This operates in a similar but a different manner to the traditional control (UI) timer and the difference in their operation is in the way the instances are created.

A UI timer, runs on the UI thread, typically meant for single threaded applications, but the problem with controls on UI threads is that can cause the UI to stop updating if a process takes a long time to process.  A server timer is typically a more reliable timer, it is on a separate thread to the UI Thread and therefore it will not cause issues with the UI updating.

Now, the side that makes it more complex is the cross threaded communication, where the event is raised on one thread but details need to be sent to another thread to perform the update, mainly that of the UI.  Controls aren’t thread safe, therefore care should be taken to determine if you should be updating a control from another thread.

Suffice to say, I know, my controls are all updated from places where I know, therefore I can update the controls safely knowing that I am not going to be causing issues.

Another element that makes this more difficult is the fact that there is also another timer which control the alarm, so 2 threads, different threads need to update controls, or monitor controls on a different thread process.

  • Shows the current time open (which is in case editing time)
  • Shows the TOTAL time editing, which is saved, when you start a new session it will show the total time incrementing as well.
  • Alarm, set this to be an amount of time and the alarm will go off.  There is a stop button that stops the ding sound from running when the alarm goes off. 
  • Will support a maximum of 4,294,967,295 days (that is 11,767,033, yes 11 million years), so making sure that you don’t leave the timer open that long, then things should be OK.

This is just an initial version and I have plans as well for this.

  • Include a recurring alarm which will make the alarm go over every x minutes, seconds and so on.
  • Alarm validation, this is a basic one and I haven’t put it in yet but will be top of my list, so entry can be a little more straight forward and enable the user to know if they can enter that information.
  • Ability to pause/resume the timers and also to stop and reset them.

As with all my plugins, please let me know if you wish to use them and I can then send you the plugin and information on how to install it.  Also if you have any ideas and wish to share them on simple plugins that would make your blogging life easier, let me know and I will see how I can work on it.

No Love for Live Writer

imageMicrosoft released Windows Live Writer back in 2008 and to say it wasn’t a hit off the bat would be overselling things a little.  They acquired Onfolio Writer and made a few changes to their product and released it as Live Writer.  It is a stable platform with which to compose blogs on, it is free which is a massive selling point and it was with MOST blogs, certainly the more popular ones like WordPress, Blogger and others if they support a specific  RSD.

Microsoft have another great blogging tool, which I am unsure how many people know that Microsoft Word would connect and publish to blogging sites.   The problem with Word is, it isn’t just for blogging, it is a fully featured word processing application that can do so much more than any blog can support and specifically when you select New Blog Post the ribbon changes to provide only a subset of what the full Word supports and is missing some very minor things, I am sure that this is the direction Microsoft is trying to go, get people to BUY Word so they can continue using a rich editor to use.

There are a couple of things that Word as a blogging software doesn’t support that Live Writer does, a publish date, but I am sketchy as to what of these features is supported by the blogs, perhaps in their GUI but from Live Writer am unsure.  But Plugins is another big item.

Word has VBA (fully feature to almost all degrees Visual Basic behind) but to what extent does this enable extension, the document with the code will need to be the template that is used for each blog post and dependant on the PC, VBA code might be disabled due to security reasons (SOEs in corporate networks).  But Live Writer provided the Live.Writer.Api assemblies and enabled a way to create Plug-ins.

I have started writing some plug-ins for Live Writer.

Audio Plug-in (for WordPress, it might work for others but I have not tested it on other blogs).  Which provides a link to add MP3s or other support types as a player into the post.  Handy for podcasts.

Date Plug-in, which is as simple as that, it is like the Microsoft Word Insert Date function, which inserts the date as text in the format selected.

imageIn development I have the Reference Plugin which enables searching for words and their various definitions.  Can take a selected word on the page or type a word in.  This is still in development at this stage and when I get the time I will expand on it.

There is also a Table of Contents plug-in that someone has asked me to write, but it is taking me a LOT longer than I thought as it is a two stage plug-in.  Where you add your headings as your contents (so far only one level) and then another plug-in will take that data and insert a header that will include the links to the bookmarks in the page.  I have done a successful post with one problem, the link that I am using, which is a simple #Bookmark type designator for the anchor tag.  Which caused it to do funny things upon resolution when being posted.

I do not have a screenshot of it at this stage.

So, what is Microsoft going to do with Live Writer.  We have seen the Messenger functionality go to Skype.  There are a few more items that do not have a viable alternative at this stage in other product made by Microsoft but Live Writer has Microsoft Word, will they phase this great editor out to make way for a push for us lovers of the product to use Word.

There is a blog from a fellow fan of Live Writer LEHSYS Side Notes.  Check it out useful information.  So I will also put out a call to other Live Writer fans out there.  If there is a plug-in that you think might be useful that may help extend the functionality of the application which will make your life and the lives of other user better while using the application, then please let me know and I will see fi I can work on it.  I am working on the Reference and Table of Contents plug-in with an idea for a publishing one (need to know a little more about running the processes in the background and what further extensibility I can do to the application).

I hope we can make this application better even though MS might not be giving it any love, perhaps we can show them that the community still loves it, certainly enough for it to be maintained.

NOTE:  Microsoft released an update to Live Writer not that long ago, May 14, 2013.  Check out the MS13-045, which has information on this.  What it shows is it is still on their support list, even through it isn’t getting functionality updates. 

Coding What The…. Moments

From my Superfluous Code and Readability post where I was relaying information that I have seen recently with regards to my work.  Well there is a wonderful one that I am seeing right now, and my words were “What The”.

I was wondering WHY  yes emphasis on that, why date and time field in a data set were being reset to NULL and then when I am saving the data I am getting a, Start Date of NULL needs to be before the current End Date of [DATE].  I am going through my code, making sure I am setting it properly that it is only my code that is being changed and I am not overwriting the values being set for other conditions, but this one took the cask for me.

Private _DateTimeField As DateTime

Public WriteOnly Property DateTimeField() As DateTime
    Set (value As DateTime)
        _DateTimeField = value
    End Set
End Property

Pirvate Function StoreData()
    '...Various Code
    Database.Table.DateTimeField = DateTimeField
    
    '....More various Code
End Function

This on its own SHOULD cause a compile error only IF Option Explicit is turned on.  But it is turned of.  They have also turned off a lot of other compile options that would normally throw errors at compile time but now they are just warnings.

I am not really sure, WHY one would create a public write only properly.  I am sure it is there to bring the code more inline with C# and C++ which has you setting what the property does when you’re coding it.

So, yes this is the cause for a few days of drama thinking it was my code in someway causing this or not causing it as I was not setting the values.  Why was this happening…

I would recommend in this, do not turn off Option Explicit.  It is there to help strongly type the variables you use.  It has come from the early days of VB when putting Option Explicit at the top of each form, module, class, etc… meant that the variable needed to be declared before you could use it.   You could in all intents and purposes declare it as VB would if Option Explicit wasn’t used;

Dim x As Variant
Dim y As Object

One of these will be declared based on the language version used.  It is better to declare ALL variables before you use them, it is a matter of efficiency than anything. 

“The server my application is running on has 32GB of RAM why would I care about a measly x bytes of data saving for all the variables I use.”

Well, you could declare everything as object, garner the overhead of having objects everywhere, performing conversions to perform comparisons (This might explain a lot of the CTypes I have seen before in this same code).  But since all data types in .NET have inherited the Object class then isn’t there a benefit, not really. It is more efficient in any scenario to use the intrinsic data type than needing to perform conversions (or allow implicit conversions if that is turned on). 

My recommendation is, declare your variable, do not turn off Option Explicit to get around any errors at compile time you have because there might be hundreds of variables not declared.  Not only will you be doing the same thing that native language programmers have done, even C# you NEED to declare all variables before you use them but you will be making your code smaller in memory without the need for overhead to cater for any object that might populate that variable.

Hidden Gems

There are some things in life that are so wonderful they must be shared with the world.  This is one of them.  The problem is, I have only just found this particular item and I am wondering how I managed to get by without it for so long.

This little gem was released in the .NET Framework 2.0 (yes, about 2005) and it is SqlConnectionStringBuilder Class, yep, that is right.  Sounds simple, but the way I use it is simply to use an existing connection string, and create a new instance of the class and then use the components within.

Since I am working with SMO, I have come to need the components of the connection string, since I have the connection string, I was merely doing the following.

SqlConnection connection = new SqlConnection(connectionString);
Dim connection As SqlConnection = New SqlConnection(connectionString)

Yeah, just a string.  But the thing came when I started using the SMO.  I had this connection string but needed the server, database and user id and password if they were there.

SecureString securedPassword = new SecureString();
string server;
string database;
string username;
string password;

//Get the server and database information
server = txtDestinationConnectionString.Text.Split(';')[0].Split('=')[1];
database = txtDestinationConnectionString.Text.Split(';')[1].Split('=')[1];
username = txtDestinationConnectionString.Text.Split(';')[2].Split('=')[1];
if (!username.ToUpper().Contains("TRUE"))
{
	//A password has been supplied 
   password = txtDestinationConnectionString.Text.Split(';')[3].Split('=')[1];
   Char[] secPassword = password.ToCharArray();

   foreach(char character in secPassword)
   {
   		securedPassword.AppendChar(character);
   }
}
else
{
	password = string.Empty;
}

So as you can see, I am splitting and pulling the elements apart.  This is fine in reality, since I am sure that behind the scenes the SqlConnectionStringBuilder Class is doing just that, possibly with a little more grace, looking for words etc…

But, using the class I can now do this.

string server;
string database;
string userId;
string password;

SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder(connectionString);
server = connection.DataSource;
database = connection.InitialCatalog;
userId = connection.UserId;
password = connection.Password;

Yes, this is it.  Sure in the previous example I used a SecureString, but you can easily change that into a character array and then assign this to a SecureString.  But you get my point.

What is the point in all of this?

Good question, it is about often using the resources you have at hand than the need to re-invent the wheel each time.  The time it took me to write the code for the extracting of the components from the string, I could have used better, more wisely.  But, it wasn’t a difficult task to perform, but there are others, which are out there which DO take a LONG time to implement and chances are someone else has already done the hard yards.

But I figured I would share this to those out there who do NOT know of this class’ existence. 

The SQL SMO Solution

SMO, DMO, who knows right?  Well, they are from a concept stand point the same thing.  They provide the ability programmatically manage SQL Server instances.  It is the way they do it that has changed.  SMO is a set of .NET assemblies and can be used via PowerShell, the DMO is not the DMO is also depreciated and is not available with SQL Server 2012 or greater, so they new way forward is the SMO (SQL Management Objects).

What can you do with the SMO?

Simple, SQL Server Management Studio uses these objects to aid in the management of any SQL Server instance.  If you have permissions to do so, then you can connect to it using the SMO.

Try this, Open a new project in Visual Studio, Include the following references into your project.  A new console project is fine for this.

  • Microsoft.SqlServer.ConnectionInfo
  • Microsoft.SqlServer.ConnectionInfoExtended
  • Microsoft.SqlServer.Management.Sdk.Sfc
  • Microsoft.SqlServer.Smo
  • Microsoft.SqlServer.SmoExtended
  • Microsoft.SqlServer.SqlEnum

Not all of these are used for this example but I have included so they are there in case you do with to expand on it.

using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Management.Smo;

Include those references into the code.  With these now in the code, we can now connect to the server and display the list of databases as a simple example.

Server server;
server = new Server(new ServerConnection("(local)");

//Connect to the server and use a secure login
server.ConnectionContext.LoginSecure = true;
server.ConnectionContext.Connect();

This is connecting to a local SQL Server instance but this can be a remote database if you can connect to it then you can through the SMO.

The SecureLogin property specifies if it is using Windows Authentication or SQL Server Authentication.  Since I am not providing a username or password I am using Windows Authentication to log into this server.

NOTE:

The Server object doesn’t support the System.IDisposable interface.  Why?  Not sure.  Since it is best practice to manage the scope of objects by implementing the using Statement (not the directive).  But you will see an error stating that the Server object can’t be converted to the System.IDisposable interface, which means it doesn’t implement it.

But when the variable goes out of scope it is automatically disconnected from the server.  But this is by no means a get out of jail free card for writing code that doesn’t clean up after itself.  To assume that the guys who developed the SMO got all of their stuff right is too much. 

Now we are connected to the database, we can now look at it like we can with any other object in code. 

foreach (Database tempDB in server.Databases)
{
	Console.WriteLine(tempDB.Name);
}

//Disconnect from the server
server.Disconnect();

Press CTRL+F5 to compile without debugging and you will see a list of the databases on your local system.

image

The blurred out ones are specific to work I do.

That is a simple as it gets really.  If you start looking at then the specific database object you will find Stored Procedures and Tables, Views, etc…  each collection enables enumeration through to get specific objects.

I will post more about the SMO as I delve into it more.  Before using the DMO, I would use SQL queries to get back data about the database.

SELECT * FROM sys.Tables

As an example certainly but there is many more ways to skin that cat.

Versions

This is just a quick note on version information for use of the SMO.  The version I have used is .NET 4.5 for my examples I have written in code, the samples above are version agnostic.  But the SMO was built using .NET 4.0.  This doesn’t mean you can’t use it with older versions of .NET.  I have tried it with a project that is written with .NET 3.5.  and it works.  They should work in most circumstances, but I have seen instances where using .NET 2.0 runtime will cause issues with the resolving of namespaces.  So if you are going to target a version make sure it is the latest version.

Also, the SMO can be used to manage SQL Server 2005 or greater, which is all currently supported versions of SQL Server, but service packs might also be required to make sure that they work.

But a note, when you add the references, you will get a dialog informing you that the runtime is not correct.

image

This dialog will show for all references that do not match the target framework version specified.  Though I do note that it doesn’t provide a version number in there.  But when I added this and then changed the Target framework version to be .NET Framework 4 this dialog did not display.

But I have tested it in .NET Framework 3.0 and there are namespace issues, .NET Framework 3.5 worked.  .NET Framework 4 works as did .NET Framework 4.5.

It was something that I wanted to bring to your attention.  So running the SMO using Visual Studio 2008 or better should be fine as this support the .NET Framework 3.5. 

To implement the SMO with older versions of .NET then older versions of the SMO will need to be obtained and you can get these from Microsoft.

Key Locks – Why is it not there?

Just about every computer sold has a keyboard, even touch screens devices have keyboards, albeit virtual ones. I recently started a new job, and like most jobs I start, the keyboard is often terrible, due to their purchasing of lots from one place or using an older one. So I went down to the shop got myself a new keyboard. It is a nice keyboard.

This is a nice keyboard, it sounds nice, has a good wrist rest, the mouse is solid and easy to move. This is the first full wireless desktop keyboard solution I have. There is ONE issue.

There are no lights to indicate if Caps Lock, Num Lock or Scroll Lock. Nor, is there any mechanism to tell me if I have turned it on. Not big in some manner, but often, especially with the Caps lock I will accidently hit it with the Shift key and it comes on.

So, due to this I needed to give me some visual indicator. So I wrote one.

It is something to behold this version 1 of my Lock Keys application. It will turn green when the key comes on. I have improved this greatly since the original version, reduced the resources it used and the amount of processing power it consuming. I have an x86 and x64 version available, I am hoping to have it improved, putting the names over the image to help reduce it.

I am also looking at adding a positional save, but so far it saves but not the proper position.

Double click the form, and it will hide the border, double click again and it will show.

The above is the form with the border. I will be releasing it very soon; I will include another post with the information. It will be released once I am happy with it. I guess I like I have written this but I am very confused as to why this keyboard does not have the lights to indicate the various lock keys.

The application is using Microsoft .NET Framework 4.5, no reason other than I can but I will release a version that is made for a previous version of the .NET Framework, possibly 2.0.