WPF project connection to sqlserver

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anindya004
    New Member
    • Mar 2010
    • 7

    WPF project connection to sqlserver

    Members I have a question how to connect to sql server tables of a database with this proect's data.
    Can you suggest .

    Members you can see that inside the bin\debug\Conta ctManager.state now in this ContactManager. state is the file where the data is getting stored when I am running the proj.

    There is a _stateFile in the ContactReposito ry.cs where the values are getting stotred.This variable is later on used for all the operations.
    My question is how to connect to sql server instead to this ContactManager. state file

    now inside contactreposito ry.cs file

    <code>
    Code:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace ContactManager.Model
    {
        public class ContactRepository
        {
            private List<Contact> _contactStore;
            private readonly string _stateFile;
    
            public ContactRepository()
            {
                _stateFile = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    "ContactManager.state"
                    );
    
                Deserialize();
            }
    
            public void Save(Contact contact)
            {
                if (contact.Id == Guid.Empty)
                    contact.Id = Guid.NewGuid();
    
                if (!_contactStore.Contains(contact))
                    _contactStore.Add(contact);
    
                Serialize();
            }
    
            public void Delete(Contact contact)
            {
                _contactStore.Remove(contact);
                Serialize();
            }
    
            public List<Contact> FindByLookup(string lookupName)
            {
                IEnumerable<Contact> found =
                    from c in _contactStore
                    where c.LookupName.StartsWith(
                        lookupName,
                        StringComparison.OrdinalIgnoreCase
                        )
                    select c;
    
                return found.ToList();
            }
    
            public List<Contact> FindAll()
            {
                return new List<Contact>(_contactStore);
            }
    
            private void Serialize()
            {
                using (FileStream stream =
                    File.Open(_stateFile, FileMode.OpenOrCreate))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, _contactStore);
                }
            }
    
            private void Deserialize()
            {
                if (File.Exists(_stateFile))
                {
                    using (FileStream stream =
                        File.Open(_stateFile, FileMode.Open))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
    
                        _contactStore =
                            (List<Contact>)formatter.Deserialize(stream);
                    }
                }
                else _contactStore = new List<Contact>();
            }
        }
    }
    .
    </code>

    now in this file you can see that

    Code:
    _stateFile = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    "ContactManager.state"
    is there .
    Now to connect it to the sqlserver what I have to do is instead of the binary file "ContactManager .state " ....I want a it to be connected to a *.mdf .

    How to do this please suggest me .
    This is an open source project.
    for the detail explanation please see the two attached files with this question which have attached with this question.

    The code can be downloaded from the website:
    1. Go to www.informit.com/title/9780672329715.
    2. Click Downloads.
    3. Click one of links that appear, and the download should start automatically.
    Attached Files
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.

    The tag is [code] not <code>

    Comment

    • tlhintoq
      Recognized Expert Specialist
      • Mar 2008
      • 3532

      #3
      My question is how to connect to sql server instead to this ContactManager. state file
      now inside contactreposito ry.cs file
      Until someone with more experience can offer more targeted advice I can point you toward these:

      Database How-to parts 1 and 2
      Database tutorial Part 1
      Database tutorial Part 2

      Comment

      • anindya004
        New Member
        • Mar 2010
        • 7

        #4
        I know the sql data connection to the windows forms.
        Like the following
        <code>
        private void button1_Click(o bject sender, EventArgs e)
        {
        SqlConnection con = new SqlConnection(" Data Source=STUDENT-1D40FC5\\SQLEXP RESS; Initial Catalog=Library Mgnt;Integrated Security=SSPI") ;
        string query = "insert into BookDetails(Tit le,Author,Publi sher,Subject,No _Of_Copies)valu es('" + title.Text + "','" + author.Text + "','" + textBox3.Text + "','" + subject.Text + "','" + no.Text + "')";
        SqlCommand cmd = new SqlCommand(quer y, con);
        con.Open();
        SqlDataReader reader = cmd.ExecuteRead er();
        MessageBox.Show ("The Book Details are saved.");
        while (reader.Read())
        {
        }
        reader.Close();

        }
        </code>

        I want to know how to insert to the _stateFile in the code.
        As if you see the full project and download it then you will see that it is using a binary file for the purpose of database connection and insert,update,d elete.

        So in place
        <code>
        _stateFile = Path.Combine(
        AppDomain.Curre ntDomain.BaseDi rectory,
        "ContactManager .state"
        </code>
        how to connect to the sql database or .mdf file rather than a binary file.

        Comment

        • anindya004
          New Member
          • Mar 2010
          • 7

          #5
          WPF project connection to sql server

          Experts I have a question---how to connect the following project to sql server and user insert/edit/update queries to the database-

          1.Please open the page http://www.informit.com/store/produc...sbn=0672329859
          2.click on Downloads
          3.Please download the Contact Manager

          4.Unzip ContactManager. zip
          5.Please open ContactReposito ry.cs file
          6.There you will find the following code

          Code:
          using System;
          using System.Collections.Generic;
          using System.IO;
          using System.Linq;
          using System.Runtime.Serialization.Formatters.Binary;
          
          namespace ContactManager.Model
          {
              public class ContactRepository
              {
                  private List<Contact> _contactStore;
                  private readonly string _stateFile;
          
                  public ContactRepository()
                  {
                      _stateFile = Path.Combine(
                          AppDomain.CurrentDomain.BaseDirectory,
                          "ContactManager.state"
                          );
          
                      Deserialize();
                  }
          
                  public void Save(Contact contact)
                  {
                      if (contact.Id == Guid.Empty)
                          contact.Id = Guid.NewGuid();
          
                      if (!_contactStore.Contains(contact))
                          _contactStore.Add(contact);
          
                      Serialize();
                  }
          
                  public void Delete(Contact contact)
                  {
                      _contactStore.Remove(contact);
                      Serialize();
                  }
          
                  public List<Contact> FindByLookup(string lookupName)
                  {
                      IEnumerable<Contact> found =
                          from c in _contactStore
                          where c.LookupName.StartsWith(
                              lookupName,
                              StringComparison.OrdinalIgnoreCase
                              )
                          select c;
          
                      return found.ToList();
                  }
          
                  public List<Contact> FindAll()
                  {
                      return new List<Contact>(_contactStore);
                  }
          
                  private void Serialize()
                  {
                      using (FileStream stream =
                          File.Open(_stateFile, FileMode.OpenOrCreate))
                      {
                          BinaryFormatter formatter = new BinaryFormatter();
                          formatter.Serialize(stream, _contactStore);
                      }
                  }
          
                  private void Deserialize()
                  {
                      if (File.Exists(_stateFile))
                      {
                          using (FileStream stream =
                              File.Open(_stateFile, FileMode.Open))
                          {
                              BinaryFormatter formatter = new BinaryFormatter();
          
                              _contactStore =
                                  (List<Contact>)formatter.Deserialize(stream);
                          }
                      }
                      else _contactStore = new List<Contact>();
                  }
              }
          }
          7.Now here you are seeing the following
          <code>
          Code:
          _stateFile = Path.Combine(
                          AppDomain.CurrentDomain.BaseDirectory,
                          "ContactManager.state"
          </code>

          8.What this project is doing is it is storing the data in a binary data file ContactManager. state
          9.Then passing those values to the variable _stateFile
          10. Now my question is how to connect this project to the sql server and in place of the binary data file I want a table to be user in sqlserver .
          11.How that is to be done I do not know.
          12.I know the basic data connection to the winform application and insert/update/delete operation
          as followes

          <code>

          Code:
          private void button1_Click(object sender, EventArgs e)
                  {
                      SqlConnection con = new SqlConnection("Data Source=STUDENT-1D40FC5\\SQLEXPRESS; Initial Catalog=LibraryMgnt;Integrated Security=SSPI");
                      string query = "insert into BookDetails(Title,Author,Publisher,Subject,No_Of_Copies)values('" + title.Text + "','" + author.Text + "','" + textBox3.Text + "','" + subject.Text + "','" + no.Text + "')";
                      SqlCommand cmd = new SqlCommand(query, con);
                      con.Open();
                      SqlDataReader reader = cmd.ExecuteReader();
                      MessageBox.Show("The Book Details are saved.");
                      while (reader.Read())
                      {
                      }
                      reader.Close();
          
                  }
          </code>

          13.But in this project how that connection is to be established I do not know and also how insert/update/delete queries are to be used .

          14.Experts I thought that ContactReposito ry.cs file only is responsible for the data connection if I am wrong then please see the whole project where the required changes are to be made.That is the main reason I have send the url of the code project .

          I am totally new to WPF please explain step by step

          Comment

          • tlhintoq
            Recognized Expert Specialist
            • Mar 2008
            • 3532

            #6
            TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.

            I know I have said this in a few of your posts now.
            The tag for code is [code] not <code>
            Stop making other people do this for you. It's lazy.

            Comment

            • tlhintoq
              Recognized Expert Specialist
              • Mar 2008
              • 3532

              #7
              I have to say, you are asking an aweful lot of people just to answer
              How to connect the following project to sql server and user insert/edit/update queries to the database
              There really isn't a need to download your entire project etc. to tell you how to connect to a database and use insert/edit/update queries.

              Database How-to parts 1 and 2
              Database tutorial Part 1
              Database tutorial Part 2

              Comment

              • tlhintoq
                Recognized Expert Specialist
                • Mar 2008
                • 3532

                #8
                Please don't double-post your questions. It divides attempts to help you in an organized and cohesive manner. Your threads have been merged

                Comment

                • anindya004
                  New Member
                  • Mar 2010
                  • 7

                  #9
                  can you please suggest me how to replace the binary data file and what to do there as here binary data file is used

                  Comment

                  • tlhintoq
                    Recognized Expert Specialist
                    • Mar 2008
                    • 3532

                    #10
                    What do you mean by "replace"?
                    Update the value in the database?
                    Or replace the use of a binary file with some other kind of data: Something different than binary file?

                    If you mean 'update the database'... That is very well covered in the tutorials. Did you *do* the tutorials?

                    Comment

                    • anindya004
                      New Member
                      • Mar 2010
                      • 7

                      #11
                      tlhintoq ,
                      You have got it .In the project they have used the binary data file .
                      I want to use the sql server and a table to store all the data .
                      tlhintoq the queries of all the insert/update/delete are to be operated on that table.
                      I know the queries.
                      Database connection also i know .
                      But the problem is if you see in Address.cs there are
                      private string _city;
                      private string _country;
                      private string _line1;
                      private string _line2;
                      private string _state;
                      private string _zip;
                      these properties.
                      Also in Contact.cs there are these following properties
                      private Address _address = new Address();
                      private string _cellPhone;
                      private string _firstName;
                      private string _homePhone;
                      private Guid _id = Guid.Empty;
                      private string _imagePath;
                      private string _jobTitle;
                      private string _lastName;
                      private string _officePhone;
                      private string _organization;
                      private string _primaryEmail;
                      private string _secondaryEmail ;

                      Now I have to pass them to the table sql server.
                      In the file ContactReposito ry.cs
                      there is
                      private List<Contact> _contactStore;
                      private readonly string _stateFile;

                      So that means that in the list _contactStore the all properties of contact are passed

                      And in the following code
                      public ContactReposito ry()
                      {
                      _stateFile = Path.Combine(
                      AppDomain.Curre ntDomain.BaseDi rectory,
                      "ContactManager .state"
                      );

                      Deserialize();
                      }

                      The binary file is getting the values.
                      Now what I have to do ...Please tell me.
                      Please do not get angry if I am asking some silly questions(It is because I am fresher)

                      Please help

                      Comment

                      • tlhintoq
                        Recognized Expert Specialist
                        • Mar 2008
                        • 3532

                        #12
                        I will ask you again... Did you bother to walk through the two tutorials?
                        Just do the tutorials from start to finish. Don't try to apply them to your problem right now. First learn on a small scale how to interact with a database. Learn how to update small projects, small tables. Learn how to do the queries.

                        *THEN* take that new understanding and try to apply it to your larger project.

                        First you asked for help on how to do an update. Then you responded that you know how to update/query/connect/etc.
                        I know the queries.
                        Database connection also i know.
                        Then you say the problem is that you have properties. Why are properties such as a name or address a problem? Isn't that the sort of data you are wanting update?

                        Without asking others to download your entire project and do all your work for you... what exactly is the problem? Do you need help updating a database? Do you need help serializing a class?

                        Comment

                        • sjranjanast
                          New Member
                          • Mar 2010
                          • 1

                          #13
                          Hello Experts,

                          i m also a part in this project ...

                          Here is the proper question .... i hope you guys can help us in this issue ...

                          The actual WPF project code that we have using this concept :

                          Taking data from a binary file and utilizing it in project .

                          What we want to do is ... instead of this binary file we want to take data from MSSQL database .


                          Here i m able to do mssql connection and i get my database values in to this application .

                          The Problem was , the data has to be formatted in a list type of way , so that we can utilize ...

                          See the following code ...
                          Code:
                              private void Deserialize()
                                  {
                                      if (File.Exists(_stateFile))
                                      {
                                          using (FileStream stream =
                                              File.Open(_stateFile, FileMode.Open))
                                          {
                                              BinaryFormatter formatter = new BinaryFormatter();
                          
                                              _contactStore =
                                                  (List<Contact>)formatter.Deserialize(stream);
                                          }
                                      }
                                      else _contactStore = new List<Contact>();
                                  }
                          this is the function which takes binary data from file and passing it to application ...

                          this is the following line doing that specific operation on above function ...
                          Code:
                          _contactStore =
                                                  (List<Contact>)formatter.Deserialize(stream);

                          so i have to alter this piece of code to replace my mssql data instead of this binary data .

                          i get my mssql data in some string type variables . now i have to store those values to _contactStore object , so that application can use that . Here comes the problem . this _contact Store object requires list type of input . so i assembled my mssql values into list type and i tried to pass there ... but it is not accepting that .....

                          this is the actual problem what we are having .... can any one help us on this ...

                          Comment

                          • tlhintoq
                            Recognized Expert Specialist
                            • Mar 2008
                            • 3532

                            #14
                            this _contact Store object requires list type of input .
                            Does it? _contactstore is a List<> of Contact objects.
                            Code:
                            private List<Contact> _contactStore;
                            There is nothing here that tells us what data is *in* a Contact. Maybe it also contains one or more List<> variables. Maybe it doesn't. If you say a Contact object requires a List<> type as its input then we have to beleive you, but its seems unlikely. I would expect a Contact object to have a lot of properties such as
                            • _FirstName
                            • _LastName
                            • _StreetAddress
                            • _City
                            and so on.

                            Regardless what it contains you need to make a new Contact object and .Add it to the List<>

                            Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

                            Comment

                            • anindya004
                              New Member
                              • Mar 2010
                              • 7

                              #15
                              Sir I think you have not yet seen the project.I am sure if you see it once you can give the exact solution. ---It is my earnest request to you if you download the project from http://www.informit.com/store/produc...sbn=0672329859
                              I know you are too busy , but it will be your kind benevolence if you once glance upon it . It won't take more than 2 sec to download sir.

                              Sir the Contact.cs is as follows
                              Code:
                              using System;
                              
                              namespace ContactManager.Model
                              {
                                  [Serializable]
                                  public class Contact : Notifier
                                  {
                                      private Address _address = new Address();
                                      private string _cellPhone;
                                      private string _firstName;
                                      private string _homePhone;
                                      private Guid _id = Guid.Empty;
                                      private string _imagePath;
                                      private string _jobTitle;
                                      private string _lastName;
                                      private string _officePhone;
                                      private string _organization;
                                      private string _primaryEmail;
                                      private string _secondaryEmail;
                              
                                      public Guid Id
                                      {
                                          get { return _id; }
                                          set
                                          {
                                              _id = value;
                                              OnPropertyChanged("Id");
                                          }
                                      }
                              
                                      public string ImagePath
                                      {
                                          get { return _imagePath; }
                                          set
                                          {
                                              _imagePath = value;
                                              OnPropertyChanged("ImagePath");
                                          }
                                      }
                              
                                      public string FirstName
                                      {
                                          get { return _firstName; }
                                          set
                                          {
                                              _firstName = value;
                                              OnPropertyChanged("FirstName");
                                              OnPropertyChanged("LookupName");
                                          }
                                      }
                              
                                      public string LastName
                                      {
                                          get { return _lastName; }
                                          set
                                          {
                                              _lastName = value;
                                              OnPropertyChanged("LastName");
                                              OnPropertyChanged("LookupName");
                                          }
                                      }
                              
                                      public string Organization
                                      {
                                          get { return _organization; }
                                          set
                                          {
                                              _organization = value;
                                              OnPropertyChanged("Organization");
                                          }
                                      }
                              
                                      public string JobTitle
                                      {
                                          get { return _jobTitle; }
                                          set
                                          {
                                              _jobTitle = value;
                                              OnPropertyChanged("JobTitle");
                                          }
                                      }
                              
                                      public string OfficePhone
                                      {
                                          get { return _officePhone; }
                                          set
                                          {
                                              _officePhone = value;
                                              OnPropertyChanged("OfficePhone");
                                          }
                                      }
                              
                                      public string CellPhone
                                      {
                                          get { return _cellPhone; }
                                          set
                                          {
                                              _cellPhone = value;
                                              OnPropertyChanged("CellPhone");
                                          }
                                      }
                              
                                      public string HomePhone
                                      {
                                          get { return _homePhone; }
                                          set
                                          {
                                              _homePhone = value;
                                              OnPropertyChanged("HomePhone");
                                          }
                                      }
                              
                                      public string PrimaryEmail
                                      {
                                          get { return _primaryEmail; }
                                          set
                                          {
                                              _primaryEmail = value;
                                              OnPropertyChanged("PrimaryEmail");
                                          }
                                      }
                              
                                      public string SecondaryEmail
                                      {
                                          get { return _secondaryEmail; }
                                          set
                                          {
                                              _secondaryEmail = value;
                                              OnPropertyChanged("SecondaryEmail");
                                          }
                                      }
                              
                                      public Address Address
                                      {
                                          get { return _address; }
                                          set
                                          {
                                              _address = value;
                                              OnPropertyChanged("Address");
                                          }
                                      }
                              
                                      public string LookupName
                                      {
                                          get { return string.Format("{0}, {1}", _lastName, _firstName); }
                                      }
                              
                                      public override string ToString()
                                      {
                                          return LookupName;
                                      }
                              
                                      public override bool Equals(object obj)
                                      {
                                          Contact other = obj as Contact;
                                          return other != null && other.Id == Id;
                                      }
                                  }
                              }
                              And the Address.cs is as followes--
                              Code:
                              using System;
                              
                              namespace ContactManager.Model
                              {
                                  [Serializable]
                                  public class Address : Notifier
                                  {
                                      private string _city;
                                      private string _country;
                                      private string _line1;
                                      private string _line2;
                                      private string _state;
                                      private string _zip;
                              
                                      public string City
                                      {
                                          get { return _city; }
                                          set
                                          {
                                              _city = value;
                                              OnPropertyChanged("City");
                                          }
                                      }
                              
                                      public string Country
                                      {
                                          get { return _country; }
                                          set
                                          {
                                              _country = value;
                                              OnPropertyChanged("Country");
                                          }
                                      }
                              
                                      public string Line1
                                      {
                                          get { return _line1; }
                                          set
                                          {
                                              _line1 = value;
                                              OnPropertyChanged("Line1");
                                          }
                                      }
                              
                                      public string Line2
                                      {
                                          get { return _line2; }
                                          set
                                          {
                                              _line2 = value;
                                              OnPropertyChanged("Line2");
                                          }
                                      }
                              
                                      public string State
                                      {
                                          get { return _state; }
                                          set
                                          {
                                              _state = value;
                                              OnPropertyChanged("State");
                                          }
                                      }
                              
                                      public string Zip
                                      {
                                          get { return _zip; }
                                          set
                                          {
                                              _zip = value;
                                              OnPropertyChanged("Zip");
                                          }
                                      }
                                  }
                              }

                              Comment

                              Working...