New to LINQ?

Just found this really useful collection of byte sized tidbits to improve the performance of your usage of the data context.  Takes less that 5 mins to read some of these things and they will definitely improve your knowledge and use of LINQ to SQL.  Read it here.

Share

LINQ SQL Compact – DatabaseExists()

If like me you are trying to use this really handy method and are having problems, it’s not your code … There is a bug with this method if you are using the, also very handy, |DataDirectory| macro in your application settings. Basically, using this macro (with SQL Compact 3.5) in your connection string, then instantiating a new LINQ data context with your nice friendly application connection string this method will always return false. Meaning your application will throw an exception. Your code may look something like:
[source:c-sharp] DContext datacontext = new DContext(Properties.Settings.Default.DBConnection);

if (!datacontext.DatabaseExists())
{
datacontext.CreateDatabase();
}
[/source] However, there is a simple workaround to get this method working as you would like. Simply build the connection string manually replacing the |DataDirectory| with an explicit path to your database. If you create your context this way in your class all will be well. Its not so much of a problem as a niggle since this sort of functionality will be in a utility class in your application and your most likely to be doing real database work elsewhere. To do this you can:
[source:c-sharp] AppPath = AppDomain.CurrentDomain.BaseDirectory;
DatabaseDir = Path.Combine(AppPath, “Database”);

datacontext = new DContext(“Data Source=” + DatabaseDir + “\Database.sdf;Password=**************;Persist Security Info=True”);
if (!Directory.Exists(DatabaseDir))
{
DirectoryExisted = false;
Directory.CreateDirectory(DatabaseDir);
DirectoryCreated = true;
DatabaseExists = false;
datacontext.CreateDatabase();
datacontext.Dispose();
}
else
{
if (!datacontext.DatabaseExists())
{
datacontext.CreateDatabase();
}
}
[/source] And hey presto, your back on the road to productivness rather than bug finding!

Share

WPF Single Instance Application

UPDATED

After a lot of poking around on this subject I found a rather neat way of enforcing an application to behave in a single instance manner. I’ve only just started looking at this issue so I can’t vouch for its security at the moment but in light of a few examples I found this seems like a very simple solution.

A few of the examples included a fair amount of coding to achieve the Single Instance behaviour, including removing the App.xaml file altogether, I tried various things but some of the bindings I had setup really didn’t enjoy life after the App.xaml was taken from them.

[source:c-sharp] public partial class App : Application
{
public App() : base()
{
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
if (process.Length > 1)
{
MessageBox.Show(“MyApplication is already running …”, “MyApplication Launch”, MessageBoxButton.OK, MessageBoxImage.Information);
this.Shutdown();
}
}
}
[/source]

That is one way of achieving a single instance application.  However a far better solution is one that makes use of a Mutex.  This is far more robust and definitely the recommended approach for the majority of applications.  The code below is a static Main() method inside a WPF App class:

[source:c-sharp] private static bool isNew;

[System.STAThreadAttribute()] public static void Main()
{
using (Mutex m = new Mutex(true, “ThisIsTheStringMutexValueThatMustBeUnique”, out isNew))
{
if (isNew)
{
MyWPFApplication.App app = new MyWPFApplication.App();
app.InitializeComponent();
app.Run();
}
else
{
MessageBox.Show(“MyWPFApplication is already running!”, “MyWPFApplication”, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
}
}
}
[/source]
Share

Empty if(){} …

I spent far too long today thinking about ways to code what at first appears to be a simple C# statement regarding file recursion. I’m building a new class based on code that has been tried and tested, the only difference was that in some scenarios I wish to ignore the root C: drive. In C# the DriveInfo class builds an array … minus any .Remove() or .RemoveAt() methods. I had a nice tidy method that was about as short as it could be but shoehorning this new bit of functionality inside the same method proved more awkward than I had imagined. After poking and prodding this method (and the next method in the recursion chain) I did this …

[source:c-sharp] public static void GetMachinesDirectoryList(bool ignoreC)
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (drive.DriveType == DriveType.Fixed && drive.IsReady == true)
{
if (ignoreC == true && drive.Name.StartsWith(“C”) )
{
}
else
{
ScanDir(drive.ToString());
}
}
}
}
[/source]

A kind of ‘do nothing’ statement, It works!! Although I’m really unsure just how ‘safe’ this code is. I’m having a read up on it and the potential pitfalls. I’m guesing that it will be safe as there is nothing in there to throw any exceptions!!!! (famous last words!).

Share

Using MediaElement

I’ve just put together a really dirty and VERY simple app that uses the MediaElement class in .NET 3.5 as an example for someone on CodeProject so I thought I’d post it here as it’s lying around on my web server.

Here is the class:

    public partial class Window1 : Window
    {
        ObservableCollection _filestoplay = new ObservableCollection();

        public Window1()
        {
            this.InitializeComponent();
            this.lstFilesToPlay.SelectionChanged += new SelectionChangedEventHandler(lstFilesToPlay_SelectionChanged);

            DirectoryInfo dirinfo = new DirectoryInfo(@"G:general storagefilms");
            FileInfo[] _files = dirinfo.GetFiles("*.avi");
            foreach (FileInfo file in _files)
            {
                _filestplay.Add(file.FullName.ToString());
            }
            lstFilesToPlay.ItemsSource = _filestoplay;
        }

        void lstFilesToPlay_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string _filetoplay = lstFilesToPlay.SelectedItem.ToString();
            MediaElement mediaElementPlayer = new MediaElement();
            mediaElementPlayer.LoadedBehavior = MediaState.Manual;
            mediaElementPlayer.Width = 200;
            mediaElementPlayer.Height = 200;
            mediaElementPlayer.Source = new Uri(_filetoplay, UriKind.RelativeOrAbsolute);
            mediaElementPlayer.Play();
            LayoutRoot.Children.Add(mediaElementPlayer);
        }
    }

You can download the solution file here.

Share

NDepend Initial Review

The other week I was amazingly fortunate to receive an email from Patrick Smacchia – the lead developer working on NDepend. In order that I may review it here on my blog he provided a full featured pro version. In short … amazing. Both the generosity and the software.

I duly pointed FireFox at the NDepend site and downloaded the software. Within a handful of minutes I was looking at an NDepend report of my current Project SampleSort. I don’t think I’ve ever ‘looked’ at code in quite the same way before. One of the really great NDpend features is a graphical representation of your code structure, at first glance it could easily be some graphical representation of complex chemicals in a chemistry textbook, that is until you start mousing around it and having a peer into what its actually representing.

This graphical representation can be used as a navigator around each method, within each class, in each namespace within your .NET assembly files. When clicking on one of these ‘bubbles’ the class browser will fly to the relevant item, right clicking then displays a context menu with a plethora of options for you to choose from including finding out dependencies and how it generally integrates with other parts of the code base. You can also launch the dependencies viewer from this menu. One really neat feature of this view is that using the metrics combo box allows you to select the metric this graphical view represents and the application then re-draws the bubbles based on the results of the analysis. Really cool indeed.

You can also double click in the visual representation window to view the actual code, a really neat feature. One thing I would love to see in this view is syntax highlighting. Presently the code opens in the standard  Windows notepad text viewer but I have Notepad++ installed which already has syntax highlighting built in, maybe the NDepend development team could allow the user to configure this as the default code viewer in order to leverage these features ‘for free’. When you have selected an element in the tree view class browser another pane below the class browser shows more detailed information about the element. This information is very detailed, it includes:

  • Return Type
  • IL Instruction Count
  • LOC (line of code)
  • Lines of Comment
  • Percentage Comment
  • Cyclomatic Complexity
  • IL Nested Depth
  • Parameters
  • Variable
  • Method Level
  • Efferent coupling
  • Afferent coupling
  • Method Rank

This list of metrics obviously varies depending on what is selected. Also for really powerful use of these metrics each analysis of a project is recorded and can be compared meaning you can get a real feel for how the complete picture of the code base is changing through the development process over multiple iterations of the same application. Not only that but in a large development project utilising many developers NDepend will integrate into the CI process and provide a means of reporting issues as part of the build process.

Basically this is a fantastic tool that has already provided me with information I need in order to improve the robustness of my code, if you were using this tool to interrogate a code base your not familiar with it would be completely invaluable.

CQL

Code Query Language = Genius in my opinion. It borrows from standard SQL syntax in order to provide a really innovative way of exploring your code. It comes with a bundle of useful pre-built statements which are a great starting block for building your own queries. There is also a facility that allows you to build custom queries using the query builder or to embed custom queries (and constraints) into the actual source code itself. The real beauty is that once you have performed an analysis of your code base building a query presents you with the results as your building the query. Brilliant! An example of the syntax is:

[source:c-sharp] SELECT TOP 2 TYPES FROM NAMESPACES WHERE CouldBeInternal
[/source]

Ok, that will do for starters, more to follow on this tool as I use it and explore it some more … go and grab a a trial version, you’ll be looking at your code with fresh eyes.

Share