Can Of Code

Category Archives: c#

C# Quick LINQ example

Recently I’ve been working with LINQ so I thought i’d do a quick post to share the two basic LINQ approaches.

First up is an example of a query that returns a collection of objects. In this case they are RouteItem objects.

 

// The LINQ Query
var routesInDB = from RouteItem route in DB.routeItems select route;

// Populate a ObservableCollection with the query results.
routeItems = new ObservableCollection<RouteItem>(routesInDB);

 

The second example is for when you want to get one item from a query similar to “SELECT TOP 1” or  “SELECT … Limit 1” in SQL.

 

 // The LINQ Query
IQueryable<setting> cityQuery = from c in DB.setting where c.ID == 1 select c;

// populate the setting object with the query result.
setting sett = cityQuery.FirstOrDefault();

 

The example above shows the returning of a single setting object instead of a collection.

The final example shows how to get the number of results. This may be useful if you wanted to see if an item was already present in the collection.

 

// The LINQ Query
var query = from c in routeItems where c.routeName == "home" select c;

// get the size of the returned result set.
int size = new ObservableCollection<RouteItem>(query).Count;

 

This example shows a query to count how many RouteItems have the name “home”. We place the result into an int variable.

 

Posted in c#, WPF | Tagged , , , | Leave a comment

C# Modifying a Application Settings Connection String

On the application I have currently been working on I discovered a small issue. The connection string was stored as a Application setting which meant it was read-only. Its important to set the connection string as a ConnectionString type within the Application settings so that its secure.

But what happens if the connection string changes? This isn’t so bad in a internal application as you can just rollout a new build, but what if each user is likely to have a different connection string.

To change the connection string, help (as usual) came from stack overflow Programmatically change connection string.

That was all fine and dandy but when I went to go and use the application setting by going:

Properties.Settings.Default.ConString;

It returned the old unchanged connection string. the simple way round it was instead of getting the connection string using the code above I had to do this:

System.Configuration.Configuration config2 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 pconnectionString = config2.ConnectionStrings.ConnectionStrings["ConString"].ToString();

Bingo! that worked!

 

 

Posted in c#, Software | Tagged , , | Leave a comment

Some Simple WPF Tips and Tricks

Today its been raining all day, so its been the perfect excuse to do some more WPF practice. Below i compiled a small list of rather useful snippets of WPF related code which have helped me out.

1. Closing all other WPF Windows when closing a main window

Normally in an application your have a main WPF window that does some essential functionality. An example could be your web browser. The browser window is the main window and you may have an extra window which you can manage your bookmarks.

A quick and easy way i found to do this was create an event handler for the “Closing” event for the main window:

Closing="Window_Closing"

 

In the event handler we do this:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
       foreach (Window win in App.Current.Windows)
       {
            if (win != this)
            {
                 win.Close();
            }
       }
}

 

The real gem here is the App.Current.Windows collection, which does what it says on the tin and has a collection of all the windows that have been created in your application. An important part of the snippet above is that we make sure to not close the Window that the code belongs to otherwise you get an Exception, trust me i tried it!

2.  Open an Existing instance of a WPF Window instead of a new Instance

Picture the scene, your creating an address book application and to add a new contact you have set it to bring up a new Add Contact Window. Once you finish you WPF application and release it out in the wild you get a angry email from Timmy, a frustrated user. For some reason hes got 53 instances of the Add Contact Window open!

Now to keep poor Timmy happy what you need to do is before opening a new instance of your WPF Window you want to make sure that none are already open.

And using the same magic as above you do the following:

foreach(Window win in App.Current.Windows)
{
    if (win.GetType() == typeof(propertiesWindow))
    {
        win.Show();
        win.Focus();
        return;
    }
}

 

What we are doing is looping through the collection of WPF Windows within your application and then checking if any of the windows are of the type we are wanting to open. If it does find one with the same type it will show the Window to the screen, if not it will do nothing.

To quote “Simples”.

3. WPF Visibility Property

Before i started learning the wonders of WPF, i worked with WinForms. With WinForms, life was simple, a Form or Component was either Visible = true or Visible = false. Along comes WPF stomping all over WinForms and worst of all forcing its three states of visibility on us!

After i found out what that third state was, i was willing to forgive WPF because its pretty handy. the third state is:

usrAddBtn.Visibility = System.Windows.Visibility.Collapsed;

 

Collapsed makes the WPF Element not only invisible but doesn’t reserve the space within the Parent Element. What does this mean in the real world? well it means that you could collapse a Panel and place a new Panel in its placed. This means that instead of creating new WPF Windows for settings pages for example,  you can reuse the space of your main Window.

Posted in c#, Software, WPF | Tagged , , , , | 1 Comment