Friday 8 August 2014

Crud in wpf with C# and XML

 public  class Movies
    {
        public string Name { get; set; }
        public string Genre { get; set; }
        public string Cast { get; set; }
        public string Year { get; set; }
    }


 <Grid>
        <Grid.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FF7C51E1" Offset="1"/>
                <GradientStop Color="White"/>
            </LinearGradientBrush>
        </Grid.Background>

        <TabControl Background="{x:Null}">
            <TabItem Header="View All">
               
                <Grid>
                    <DataGrid x:Name="ViewDataGrid" IsReadOnly="True" GridLinesVisibility="Horizontal"
                                     AutoGenerateColumns="False"  Background="{x:Null}">
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="Movie Name" Binding="{Binding Path=Name}"/>
                            <DataGridTextColumn Header="Year" Binding="{Binding Path=Year}"/>
                            <DataGridTextColumn Header="Genre" Binding="{Binding Path=Genre}"/>
                            <DataGridTextColumn Header="Cast" Binding="{Binding Path=Cast}"/>
                        </DataGrid.Columns>
                    </DataGrid>
                    <!--<Custom:DataGrid x:Name="ViewDataGrid" IsReadOnly="True" GridLinesVisibility="Horizontal"
                                     AutoGenerateColumns="False" d:LayoutOverrides="Width, Height" Background="{x:Null}">
                        <Custom:DataGrid.Columns>
                            <Custom:DataGridTextColumn Header="Movie Name" Binding="{Binding Path=Name}"/>
                            <Custom:DataGridTextColumn Header="Year" Binding="{Binding Path=Year}"/>
                            <Custom:DataGridTextColumn Header="Genre" Binding="{Binding Path=Genre}"/>
                            <Custom:DataGridTextColumn Header="Cast" Binding="{Binding Path=Cast}"/>
                        </Custom:DataGrid.Columns>
                    </Custom:DataGrid>-->
                </Grid>
            </TabItem>
            <TabItem Header="Add New">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.217*"/>
                        <ColumnDefinition Width="0.783*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="0.083*"/>
                        <RowDefinition Height="0.086*"/>
                        <RowDefinition Height="0.147*"/>
                        <RowDefinition Height="0.146*"/>
                        <RowDefinition Height="0.09*"/>
                        <RowDefinition Height="0.095*"/>
                        <RowDefinition Height="0.353*"/>
                    </Grid.RowDefinitions>
                    <TextBlock HorizontalAlignment="Right" VerticalAlignment="Center" Text="Name :" TextWrapping="Wrap" Margin="0,0,5,0" Grid.Row="1"/>
                    <TextBlock HorizontalAlignment="Right" Margin="0,0,5,0" VerticalAlignment="Center" Text="Genre :" TextWrapping="Wrap" Grid.Row="2"/>
                    <TextBlock HorizontalAlignment="Right" Margin="0,0,5,0" VerticalAlignment="Center" Grid.Row="3" Text="Cast :" TextWrapping="Wrap"/>
                    <TextBlock HorizontalAlignment="Right" Margin="0,0,5,0" VerticalAlignment="Center" Text="Year :" TextWrapping="Wrap" Grid.Row="4"/>
                    <TextBox x:Name="txtName" Margin="0,0,5,0" Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" Height="23"/>
                    <TextBox x:Name="txtGenre" Margin="0,1,5,1" Grid.Column="1" Grid.Row="2" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
                    <TextBox x:Name="txtCast" Margin="0,1,5,1" Grid.Column="1" Grid.Row="3" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
                    <ComboBox x:Name="cmbYear" Margin="0" HorizontalAlignment="Left" Width="75" Grid.Column="1" Grid.Row="4" Height="20" VerticalAlignment="Center"/>
                    <Button x:Name="btnAdd" Click="btnAdd_Click"
                            HorizontalAlignment="Left" Margin="0" VerticalAlignment="Center" Width="100" Height="25" Content="Add New" Grid.Column="1" Grid.Row="5"/>
                </Grid>
            </TabItem>
            <TabItem Header="Update">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.283*"/>
                        <ColumnDefinition Width="0.078*"/>
                        <ColumnDefinition Width="0.639*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="0.083*"/>
                        <RowDefinition Height="0.086*"/>
                        <RowDefinition Height="0.147*"/>
                        <RowDefinition Height="0.146*"/>
                        <RowDefinition Height="0.09*"/>
                        <RowDefinition Height="0.095*"/>
                        <RowDefinition Height="0.353*"/>
                    </Grid.RowDefinitions>
                    <TextBlock Margin="5.711,0,5,0" VerticalAlignment="Center" Grid.Row="1" Text="Name :" TextWrapping="Wrap" Grid.Column="1" />
                    <TextBlock Margin="4.834,0,5,0" VerticalAlignment="Center" Text="Genre :" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1"/>
                    <TextBlock Margin="12.884,0,5,0" VerticalAlignment="Center" Grid.Row="3" Text="Cast :" TextWrapping="Wrap" Grid.Column="1"/>
                    <TextBlock Margin="11.991,0,5,0" VerticalAlignment="Center" Text="Year :" TextWrapping="Wrap" Grid.Row="4" Grid.Column="1"/>
                    <TextBox x:Name="txtNameUpdate" Margin="0,0,5,0" VerticalAlignment="Center" Height="23" Grid.Column="2" Grid.Row="1"/>
                    <TextBox x:Name="txtGenreUpdate" Margin="0,1,5,1" Grid.Column="2" Grid.Row="2" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
                    <TextBox x:Name="txtCastUpdate" Margin="0,1,5,1" Grid.Column="2" Grid.Row="3" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
                    <ComboBox x:Name="cmbYearUpdate" HorizontalAlignment="Left" Margin="0" VerticalAlignment="Center" Width="75" Height="20" Grid.Column="2" Grid.Row="4"/>
                    <Button x:Name="btnUpdate" Click="btnUpdate_Click"
                            HorizontalAlignment="Left" Margin="0" VerticalAlignment="Center" Width="100" Height="25" Content="Update" Grid.Column="2" Grid.Row="5"/>
                    <Button x:Name="btnDelete" Click="btnDelete_Click"
                            Margin="108,0,188.819,0" VerticalAlignment="Center" Height="25" Content="Delete" Grid.Column="2" Grid.Row="5" Width="100"/>
                    <ListBox x:Name="lbMovies" SelectionChanged="lbMovies_SelectionChanged"
                             Margin="0,8" Grid.RowSpan="7">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Name}"/>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </Grid>
            </TabItem>
        </TabControl>
    </Grid>




namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for CrudXML.xaml
    /// </summary>
    public partial class CrudXML : Window
    {
        ObservableCollection<Movies> selectedList = new ObservableCollection<Movies>();
        List<Movies> movieList;
        List<string> yearList;
        Movies moviesDel;

        public CrudXML()
        {
            InitializeComponent();
            btnUpdate.IsEnabled = false;
            btnDelete.IsEnabled = false;
            yearList = new List<string> { "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003" };
            cmbYear.ItemsSource = yearList;
            cmbYearUpdate.ItemsSource = yearList;
            LoadData();
        }

        #region Load Data
        void LoadData()
        {
            XDocument doc = XDocument.Load(@"D:\MovieDB.xml");
            movieList = (from movie in doc.Descendants("Movie")
                         orderby movie.Element("Name").Value
                         select new Movies
                         {
                             Name = movie.Element("Name").Value,
                             Genre = movie.Element("Genre").Value,
                             Year = movie.Element("Year").Value,
                             Cast = movie.Element("Cast").Value,
                         }).ToList();

            lbMovies.ItemsSource = movieList;
            ViewDataGrid.ItemsSource = movieList;
        }
        #endregion

        #region Add Operation
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            string name = txtName.Text.Trim();
            string year;
            if (cmbYear.SelectedIndex != -1)
            {
                year = cmbYear.SelectedValue.ToString();
            }
            else
            {
                year = "2009";
            }
            string genre = txtGenre.Text.Trim();
            string cast = txtCast.Text.Trim();

            bool isUpdate = false;

            if (name.Equals(string.Empty))
                name = "Un Named Movie";
            if (year.Equals(string.Empty))
                year = "2009";
            if (genre.Equals(string.Empty))
                genre = "No Genre";
            if (cast.Equals(string.Empty))
                cast = "No Cast";

            Movies newMovie = new Movies
            {
                Name = name,
                Year = year,
                Genre = genre,
                Cast = cast,
            };

            WriteToXmlFile(newMovie, isUpdate);
            txtName.Text = string.Empty;
            txtGenre.Text = string.Empty;
            txtCast.Text = string.Empty;
            cmbYear.SelectedIndex = -1;
            LoadData();
        }
        #endregion

        #region Update
        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            if (lbMovies.SelectedIndex != -1)
            {
                string name = txtNameUpdate.Text;
                string year = cmbYearUpdate.SelectedValue.ToString();
                string genre = txtGenreUpdate.Text;
                string cast = txtCastUpdate.Text;

                bool isUpdate = true;

                if (name.Equals(string.Empty))
                    name = "Un Named Movie";
                if (year.Equals(string.Empty))
                    year = "2009";
                if (genre.Equals(string.Empty))
                    genre = "No Genre";
                if (cast.Equals(string.Empty))
                    cast = "No Cast";

                Movies updateMovie = new Movies
                {
                    Name = name,
                    Year = year,
                    Genre = genre,
                    Cast = cast,
                };

                WriteToXmlFile(updateMovie, isUpdate);
                lbMovies.SelectedIndex = -1;
                btnUpdate.IsEnabled = false;
                btnDelete.IsEnabled = false;
                LoadData();
            }
        }
        #endregion

        #region WriteToXmlFile
        void WriteToXmlFile(Movies movies, bool isUpdate)
        {
            #region Add New
            if (!isUpdate)
            {
                FileStream fs = new FileStream(@"D:\MovieDB.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fs);
                fs.Close();

                XmlElement newMovie = xmlDoc.CreateElement("Movie");
                XmlElement name = xmlDoc.CreateElement("Name");
                name.InnerText = movies.Name;
                newMovie.AppendChild(name);

                XmlElement genre = xmlDoc.CreateElement("Genre");
                genre.InnerText = movies.Genre;
                newMovie.AppendChild(genre);

                XmlElement year = xmlDoc.CreateElement("Year");
                year.InnerText = movies.Year;
                newMovie.AppendChild(year);

                XmlElement cast = xmlDoc.CreateElement("Cast");
                cast.InnerText = movies.Cast;
                newMovie.AppendChild(cast);

                xmlDoc.DocumentElement.InsertAfter(newMovie,
                xmlDoc.DocumentElement.LastChild);

                FileStream fsxml = new FileStream(@"D:\MovieDB.xml", FileMode.Truncate,
                                      FileAccess.Write,
                                      FileShare.ReadWrite);

                xmlDoc.Save(fsxml);
                fsxml.Close();
            }
            #endregion

            #region Update
            else
            {
                XDocument doc = XDocument.Load(@"D:\MovieDB.xml");

                foreach (var item in doc.Descendants("Movie"))
                {
                    if (item.Element("Name").Value == moviesDel.Name)
                    {
                        item.Element("Name").SetValue(movies.Name);
                        item.Element("Genre").SetValue(movies.Genre);
                        item.Element("Year").SetValue(movies.Year);
                        item.Element("Cast").SetValue(movies.Cast);
                        doc.Save(@"D:\MovieDB.xml");
                        break;
                    }
                }
            }
            #endregion
        }
        #endregion

        #region Delete Operation
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (moviesDel != null)
            {
                if (System.Windows.MessageBox.Show("Do you Really Want To Delete This Movie ?", "Delete Confirmation", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    XDocument doc = XDocument.Load(@"D:\MovieDB.xml");

                    foreach (var item in doc.Descendants("Movie"))
                    {
                        if (item.Element("Name").Value == moviesDel.Name)
                        {
                            ((XElement)item.Element("Name")).Parent.Remove();
                            doc.Save(@"D:\MovieDB.xml");
                            break;
                        }
                    }
                    LoadData();
                    moviesDel = null;
                    lbMovies.SelectedIndex = -1;
                    btnDelete.IsEnabled = false;
                }
                else
                {
                    moviesDel = null;
                    lbMovies.SelectedIndex = -1;
                    btnDelete.IsEnabled = false;
                }
            }
        }
        #endregion

        #region ListBox Selection Changed
        private void lbMovies_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedList.Clear();
            if (this.lbMovies.SelectedItem is Movies)
            {
                selectedList.Add(((Movies)this.lbMovies.SelectedItem));
                moviesDel = (Movies)this.lbMovies.SelectedItem;
            }
            foreach (var item in selectedList)
            {
                txtNameUpdate.Text = item.Name;
                cmbYearUpdate.SelectedValue = item.Year;
                txtGenreUpdate.Text = item.Genre;
                txtCastUpdate.Text = item.Cast;
            }
            btnUpdate.IsEnabled = true;
            btnDelete.IsEnabled = true;
        }
        #endregion
    }
}


<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Movies>
  <Movie>
    <Name>A Mighty Heart</Name>
    <Year>2009</Year>
    <Genre>No Genre</Genre>
    <Cast>Shriyas, Nikita</Cast>
  </Movie>
  <Movie>
    <Name>A Scanner Darkly</Name>
    <Year>2009</Year>
    <Genre>Drama, Crime, Animation</Genre>
    <Cast>Keanu Reeves</Cast>
  </Movie>
  <Movie>
    <Name>Afro Samurai: Resurrection</Name>
    <Year>2009</Year>
    <Genre>Animation, Action</Genre>
    <Cast>No Cast</Cast>
  </Movie>
  <Movie>
    <Name>Batman: Gotham Knight</Name>
    <Year>2009</Year>
    <Genre>Animation, Action</Genre>
    <Cast>Batman</Cast>
  </Movie>
  <Movie>
    <Name>Bedazzled</Name>
    <Year>2009</Year>
    <Genre>Thriller, Comedy</Genre>
    <Cast>Brendan Fraser, Elizabeth Hurley</Cast>
  </Movie>
  <Movie>
    <Name>Bedtime Stories</Name>
    <Year>2009</Year>
    <Genre>Drama, Comedy</Genre>
    <Cast>Adam Sanders, Courtney Cox</Cast>
  </Movie>
  <Movie>
    <Name>KKKG</Name>
    <Genre>SRK</Genre>
    <Year>2003</Year>
    <Cast>MMM</Cast>
  </Movie>
  <Movie>
    <Name>HHH</Name>
    <Genre>cdfcf</Genre>
    <Year>2009</Year>
    <Cast>cvvb</Cast>
  </Movie>
</Movies>






















No comments:

Post a Comment