views:

139

answers:

2

I have a datagrid with 4 columns. Build Defintion, command, arguments, and a delete button. I am building a ObservableCollection of a class called monitor which is the dynamicresource for the datagrid. The monitor contains the build definition, command, and arguments. All are string types. The command and arguments are simple as they are just whatever the user enters as text. The problem lies in the build definition. I am trying to get a combobox as the object that binds to a list. The list would be in the code behind and would be added to when I query the database on window load.

So I need to be able to link the list and also be able to convert the selecteditem to a string for the edit and enter events.

Thanks in advance!

Here is the Xaml:

<Window
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:Custom="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 xmlns:bm="clr-namespace:BuildMonitor"
 x:Class="BuildMonitor.MainWindow"
 x:Name="Window"
 Title="MainWindow"
 Width="640" Height="480" mc:Ignorable="d" Loaded="Window_Loaded">
 <Window.Resources>
  <bm:Monitors x:Key="_monitors"/>
  <bm:BuildDefinitions x:Key="_buildDefinitions"/>
 </Window.Resources>
 <StackPanel x:Name="LayoutRoot">
  <Expander x:Name="ServiceConfig" Header="Service Config" IsExpanded="True">
   <Grid Height="181.96">
    <TextBox x:Name="textUsername" HorizontalAlignment="Left" Margin="119.66,6.8,0,0" VerticalAlignment="Top" Width="131.553" Height="24"/>
    <Label HorizontalAlignment="Left" Margin="4.363,5,0,0" VerticalAlignment="Top" Height="24" Content="Username"/>
    <Label HorizontalAlignment="Left" Margin="4.363,33,0,0" VerticalAlignment="Top" Height="24" Content="Password"/>
    <TextBox x:Name="textDomain" HorizontalAlignment="Left" Margin="119.66,59.8,0,0" VerticalAlignment="Top" Height="24" Width="131.553"/>
    <Label HorizontalAlignment="Left" Margin="4.363,61,0,0" VerticalAlignment="Top" Height="24" Content="Domain"/>
    <TextBox x:Name="textUrl" HorizontalAlignment="Left" Margin="119.66,87.8,0,70.16" Width="131.553"/>
    <Label HorizontalAlignment="Left" Margin="4.363,89,0,68.96" Content="URL" ToolTip="The default is &quot;http://tfsapp-in01:8080&amp;quot;"/&gt;
    <PasswordBox x:Name="textPassword" HorizontalAlignment="Left" Margin="119.66,35.8,0,0" VerticalAlignment="Top" Width="131.553" Height="24"/>
    <TextBox x:Name="textPolling" HorizontalAlignment="Left" Margin="119.66,0,0,39.16" VerticalAlignment="Bottom" Height="24" Width="131.553"/>
    <Label HorizontalAlignment="Left" Margin="4.363,0,0,37.96" Content="Polling Period" ToolTip="Value in Seconds" VerticalAlignment="Bottom" Height="27"/>
    <Button x:Name="controlApply" HorizontalAlignment="Left" Margin="147.936,0,0,8" VerticalAlignment="Bottom" Width="75" Content="Apply" Click="controlApply_Click"/>
    <TextBox x:Name="textLoggingPath" HorizontalAlignment="Left" Margin="456.66,35.8,0,0" Width="131.553" VerticalAlignment="Top" Height="24" IsEnabled="False"/>
    <Label HorizontalAlignment="Left" Margin="347.66,31.8,0,0" VerticalAlignment="Top" Height="28" Content="Logging Path"/>
    <CheckBox x:Name="checkLogging" HorizontalAlignment="Left" Margin="350.66,8,0,0" VerticalAlignment="Top" Content="Logging Enabled" Checked="checkLogging_Checked" />
    <StatusBar HorizontalAlignment="Left" Margin="456.66,0,0,44.96" Width="131.553" VerticalAlignment="Bottom">
     <StatusBarItem Name="statusitemService" Content="Not Available"/>
    </StatusBar>
    <Label HorizontalAlignment="Left" Margin="345.127,0,0,40.96" Content="Service Status" VerticalAlignment="Bottom" Height="28"/>
    <Button x:Name="controlStart" HorizontalAlignment="Left" Margin="456.66,0,0,8" VerticalAlignment="Bottom" Width="75" Content="Start" IsEnabled="False" Click="controlStart_Clicked"/>
    <Button x:Name="controlStop" HorizontalAlignment="Left" Margin="535.66,0,0,8" VerticalAlignment="Bottom" Width="75" Content="Stop" IsEnabled="False" Click="controlStop_Click"/>
   </Grid>
  </Expander>
  <Expander x:Name="Monitors" Header="Monitors" Height="216.96" Expanded="Monitors_Expanded" Collapsed="Monitors_Collapsed">  
  <Grid>
   <Custom:DataGrid x:Name="dataMonitors" ItemsSource="{DynamicResource _monitors}" Margin="8,8,8,34.04" AutoGenerateColumns="False" RowDetailsVisibilityMode="Visible">
    <Custom:DataGrid.Columns>            
     <Custom:DataGridTemplateColumn x:Name="BuildDefinition" Header="Build Definition" Width="150">
      <Custom:DataGridTemplateColumn.CellTemplate>
       <DataTemplate>
        <ComboBox ItemsSource="{DynamicResource _buildDefinitions}"></ComboBox>
       </DataTemplate>
      </Custom:DataGridTemplateColumn.CellTemplate>
     </Custom:DataGridTemplateColumn>
     <Custom:DataGridTextColumn x:Name="Command" Binding="{Binding Path=Command}" Header="Command" Width="100"/>
     <Custom:DataGridTextColumn x:Name="Arguments" Binding="{Binding Path=Arguments}" Header="Arguments" IsReadOnly="False" Width="*"/> 
     <Custom:DataGridTemplateColumn x:Name="Delete" Width="50">
      <Custom:DataGridTemplateColumn.CellTemplate>
       <DataTemplate>
        <Button Click="Delete_Click" Content="Delete"></Button>
       </DataTemplate>
      </Custom:DataGridTemplateColumn.CellTemplate>
     </Custom:DataGridTemplateColumn>    
    </Custom:DataGrid.Columns>   
   </Custom:DataGrid>
   <Button Margin="270.5,0,0,8.08" VerticalAlignment="Bottom" Content="Apply Changes" Click="ApplyChanges_Click" HorizontalAlignment="Left" Width="89"/>
   </Grid>
  </Expander>
 </StackPanel>
</Window>

Here is the code behind:

public partial class MainWindow : Window
{
      private ServiceController _sc = new ServiceController("BuildLauncher");
      private string _pathtoconfigfile = string.Empty;
      private PropertyContainer _serviceproperties;
      private DispatcherTimer _servicestatus;
      private Cryptor cryptor = new Cryptor();

      public BuildDefinitions _buildDefinitions = null;
      public Monitors _monitors = null;      

  public MainWindow()
  {
   InitializeComponent();
   // Insert code required on object creation below this point.

         _monitors = (Monitors)FindResource("_monitors");

         ServiceConfig.Expanded += new RoutedEventHandler(ServiceConfig_Expanded);
         ServiceConfig.Collapsed += new RoutedEventHandler(ServiceConfig_Collapsed);
         Monitors.Expanded += new RoutedEventHandler(Monitors_Expanded);
  }

      private void GetServiceConfigProps(string pathtoconfigfile)
      {
         try
         {
            using (TextReader reader = new StreamReader(pathtoconfigfile))
            {
               XmlSerializer sr = new XmlSerializer(typeof(PropertyContainer));

               _serviceproperties = (PropertyContainer)sr.Deserialize(reader);

               reader.Close();
            }       

            textUsername.Text = _serviceproperties.GetProperty("tfsuser").ToString();

            textPassword.Password = cryptor.Decrypt(_serviceproperties.GetProperty("tfspassword").ToString());

            textDomain.Text = _serviceproperties.GetProperty("tfsdomain").ToString();

            textPolling.Text = _serviceproperties.GetProperty("pollperiod").ToString();

            textUrl.Text = _serviceproperties.GetProperty("tfsurl").ToString();

            textLoggingPath.Text = _serviceproperties.GetProperty("logfile").ToString();

            checkLogging.IsChecked = (bool)_serviceproperties.GetProperty("enabledLogging");

            List<PropertyContainer> monitors = (List<PropertyContainer>)_serviceproperties.GetProperty("monitors");

            foreach (PropertyContainer pc in monitors)
            {
               _monitors.Add(new Monitor()
               {
                  Arguments = pc.GetProperty("arguments").ToString(),
                  BuildDefinition = pc.GetProperty("definition").ToString(),
                  Command = pc.GetProperty("command").ToString()
               });
            }

            dataMonitors.Items.Refresh();

         }
         catch (Exception e)
         {
            Console.WriteLine("exception: {0}", e.Message);
         }
      }

      private void Window_Loaded(object sender, RoutedEventArgs e)
      {
         try
         {         
            _pathtoconfigfile = ((TextBlock)App.Current.Properties["1"]).Text;

            if (File.Exists(_pathtoconfigfile))
            {
               GetServiceConfigProps(_pathtoconfigfile);

               try
               {
                  UpdateStatusUI();
               }
               catch (InvalidOperationException ioe)
               {
                  if (ioe.InnerException.Message.Contains("does not exist"))
                     InstallBuildLauncher();                  
               }
            }
            else
            {
               InstallBuildLauncher();

               GetServiceConfigProps(_pathtoconfigfile);
            }

            _sc.Refresh();

            UpdateStatusUI();

            if (_sc.Status == ServiceControllerStatus.Stopped)
               controlStart.IsEnabled = true;
            else if (_sc.Status == ServiceControllerStatus.Running)
               controlStop.IsEnabled = true;

            _servicestatus = new DispatcherTimer();

            _servicestatus.Interval = new TimeSpan(5000);

            _servicestatus.Tick += new EventHandler(_servicestatus_Tick);

            _servicestatus.Start();
         }
         catch (Exception exp)
         {
            Console.WriteLine("exception: {0}", exp.Message);
         }
      }

      private void UpdateStatusUI()
      {
         lock (statusitemService)
            statusitemService.Content = _sc.Status;
      }

      private void _servicestatus_Tick(object sender, EventArgs e)
      {
         ServiceControllerStatus last = _sc.Status;

         lock (_sc)
            _sc.Refresh();

         if (last != _sc.Status)
         {
            UpdateStatusUI();

            lock (controlStop)
            {
               lock (controlStart)
               {
                  if (_sc.Status == ServiceControllerStatus.Running)
                  {
                     controlStart.IsEnabled = false;
                     controlStop.IsEnabled = true;
                  }
                  else if (_sc.Status == ServiceControllerStatus.Stopped)
                  {
                     controlStart.IsEnabled = true;
                     controlStop.IsEnabled = false;
                  }
                  else
                  {
                     controlStart.IsEnabled = false;
                     controlStop.IsEnabled = false;
                  }
               }
            }
         }
      }

      private void InstallBuildLauncher()
      {
         Process bl = Process.Start("sc",string.Format("create buildlauncher binpath= \"{0}\\BuildLauncher.exe\"",Environment.CurrentDirectory));

         while (!bl.HasExited)
         {
            System.Threading.Thread.Sleep(2000);
         }
      }

      private void checkLogging_Checked(object sender, RoutedEventArgs e)
      {
         textLoggingPath.IsEnabled = (bool)checkLogging.IsChecked;
      }

      private void controlStart_Clicked(object sender, System.Windows.RoutedEventArgs e)
      {
         lock (_sc)
            _sc.Start();
      }

      private void controlStop_Click(object sender, System.Windows.RoutedEventArgs e)
      {
         lock (_sc)
            _sc.Stop();
      }

      private void controlApply_Click(object sender, System.Windows.RoutedEventArgs e)
      {
         try
         {
            lock (_sc)
            {
               _sc.Refresh();

               if (_sc.Status == ServiceControllerStatus.Running)
               {
                  _sc.Stop();

                  _sc.Refresh();

                  UpdateStatusUI();
               }

               _serviceproperties.SetProperty("tfsuser", textUsername.Text);

               _serviceproperties.SetProperty("tfspassword", cryptor.Encrypt(textPassword.Password));

               _serviceproperties.SetProperty("tfsdomain", textDomain.Text);

               _serviceproperties.SetProperty("tfsurl", textUrl.Text);

               _serviceproperties.SetProperty("pollperiod", Int32.Parse(textPolling.Text));

               _serviceproperties.SetProperty("logfile", textLoggingPath.Text);

               _serviceproperties.SetProperty("enabledLogging", checkLogging.IsChecked.Value);

               WriteChanges();

               _sc.Start();
            }
         }
         catch (Exception exp)
         {
            Console.WriteLine("exception: {0}", exp.Message);
         }
      }

      private void ServiceConfig_Collapsed(object sender, System.Windows.RoutedEventArgs e)
      {
         _servicestatus.Stop();
      }

      private void ServiceConfig_Expanded(object sender, System.Windows.RoutedEventArgs e)
      {        
         _servicestatus.Start();
         Monitors.IsExpanded = false;
      }

      private void Monitors_Expanded(object sender, System.Windows.RoutedEventArgs e)
      {
         if ((ServiceControllerStatus)statusitemService.Content == ServiceControllerStatus.Running)
            ServiceConfig.IsExpanded = false;
         else
         {
            if (Monitors.IsExpanded)
            {
               Monitors.IsExpanded = false;
               MessageBox.Show("Cannot add monitors until service is in a running state");
            }
         }
      }

      private void Delete_Click(object sender, RoutedEventArgs e)
      {
         if (dataMonitors.SelectedItem != CollectionView.NewItemPlaceholder)
            ((Monitors)dataMonitors.ItemsSource).Remove((Monitor)dataMonitors.SelectedItem);
      }

      private void ApplyChanges_Click(object sender, System.Windows.RoutedEventArgs e)
      {
         if (MessageBox.Show("Apply monitors changes?", "Monitors", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
         {
            List<PropertyContainer> pcs = new List<PropertyContainer>();

            foreach (Monitor m in _monitors)
            {
               PropertyContainer pc = new PropertyContainer();
               pc.SetProperty("Command",m.Command);
               pc.SetProperty("Definition",m.BuildDefinition);
               pc.SetProperty("Arguments",m.Arguments);

               pcs.Add(pc);
            }
            _serviceproperties.SetProperty("monitors", pcs);

            WriteChanges();
         }
      }

      private void WriteChanges()
      {
         using (TextWriter writer = new StreamWriter(_pathtoconfigfile))
         {
            XmlSerializer sr = new XmlSerializer(typeof(PropertyContainer));

            sr.Serialize(writer, _serviceproperties);

            writer.Close();
         }
      }

      private void Monitors_Collapsed(object sender, System.Windows.RoutedEventArgs e)
      {
       // TODO: Add event handler implementation here.
      }
 }

   public class Monitor
   {
      public string Command { get; set; }
      public string Arguments { get; set; }
      public string BuildDefinition { get; set; }
   }

   public class Monitors : ObservableCollection<Monitor>
   {
      public Monitors() { }
   }

   public class BuildDefinitions : ObservableCollection<string>
   {
      public BuildDefinitions() { }
   }
}
A: 

Use ICollectionView. This way you have a better handle on the selected item...

Gustavo Cavalcanti
Actually found the answer I was looking for here...http://www.experts-exchange.com/Microsoft/Development/Microsoft_Programming/WPF_and_Silverlight/Q_26338250.html
Csharpfunbag