views:

161

answers:

3

I'm going to do a wpf application using MVVM(It based on http://www.codeproject.com/KB/WPF/MVVMQuickTutorial.aspx ).

This application will be connecting with webservice one per month.

On webservice I have contract

public class Student
{
        public string Name {get; set;}
        public int Score {get; set;}
        public DateTime TimeAdded {get; set;}
        public string Comment {get; set;}
}

In WPF application Adding, and removing students will be saving to xml file.

So at wpf application Student would be something like :

public class Student
{
    public string Name {get; set;}
    public int Score {get; set;}
    public DateTime TimeAdded {get; set;}
    public string Comment {get; set;}

    public Student(string Name, int Score,
        DateTime TimeAdded, string Comment) {
        this.Name = Name;
        this.Score = Score;
        this.TimeAdded = TimeAdded;
        this.Comment = Comment;
    }
}

public class StudentsModel: ObservableCollection<Student>
{
    private static object _threadLock = new Object();
    private static StudentsModel current = null;

    public static StudentsModel Current {
        get {
            lock (_threadLock)
            if (current == null)
                current = new StudentsModel();

            return current;
        }
    }

    private StudentsModel() 
    {

        // Getting student s from xml
        }
    }

    public void AddAStudent(String Name,
        int Score, DateTime TimeAdded, string Comment) {
        Student aNewStudent = new Student(Name, Score,
            TimeAdded, Comment);
        Add(aNewStudent);
    }
}

How connect this two classes ?

The worst think I guess is that contract Student from webservice would be use in this wpf application to get students from xml, in other application collection of studetns would be getting from database.

I'm newbie in design patterns so it is very hard for me :/

Example: I click AddUser, and in application A it calls webservice method which adding user to database, in application B it adds user to XML file, and In application. Base class are contracts at webservice.

Next explanation:

First application uses webservice to save data at database. Second application never save data in xmls and one perm month send this xmls to webservice and convert their to intances of students and save it at database

A: 

You can use the following architecture.

1) WPF Application (Application A & B) with a app.config which contains either Web Service URL or XML file path

2) Business/Data Layer Create a proxy class for the Web service URL and create the Student Model class which you mentioned in your post. Modify your Add method to support both functionalities. Call Add method in Webservice if app.config has webservice url (App A) or call add to XML method if appsetting has XML filepath(App B)

Ragunathan
A: 

Fortunately, the classes are already "linked", at least in form: because the ViewModel is just a bunch of Models.

In the MVVM pattern, you'll want to handle your data-binding functions in the ViewModel. This includes the following:

  • The StudentModel constructor (private StudentsModel() { ...) should load itself with all the Student instances. (Alternately, you could use a separate Load() function--which seems most logical if you have a Save() method as well.) Here, you would presumably read the XML file, use an XmlSerializer to deserialize the XML data into a collection of students (probably List), then add them to itself using either the base constructor (for the whole list) or the Add() method (one at a time, e.g. in a loop).
  • You would need functions to add Students to the collection, as in the tutorial example. On the desktop app, here is where you want to call the Add function on the web service, and if it's successful you add it to your own collection in memory. You then have to decide if you want to immediately save the (serialized) data into the XML file, or do it all together later (for example, when unloading the object or calling a Save() method).
  • You probably want to include a method to remove Student objects from the collection, too. The public methods of the ObservableCollection will be some help here, but you may want/need more logic than that in choosing which object(s) to remove. And again, here you must notify the web service about the deleted items, and know whether you're going to save changes right away or wait for a separate event.
  • Inheriting from the ObservableCollection is wise, as that gets you a lot of the magic that makes the binding dynamic--I mean, where the UI is updated as the data changes. As long as your using the base methods of Add() and Remove() etc. you are getting the benefits of IEnumerable, INotifyPropertyChanged, and INotifyCollectionChanged.

You may notice I mostly mentioned XML serialization in the explanation above, but for making a web service with similar functionality, you'll swap out ideas like "serialize the XML and save into a file" for "save changes into your database". The pattern is the same, it's just the actual actions (implementation) is different.

In short, the ViewModel here is where you want to implement all the stuff that loads & handles the data in memory and saves it out to the file, database, or web service.

ewall
+1  A: 

It is very unclear from your question what the actual problem is. But, I guess I could address a few and show you a way to solve them.

1) The main problem I see in your project is you have two definitions of Student class. You can easily merge them into a single definition. (I will just show you how...)

2) It is very unclear whether you want your WPF client to save data to a Data Source (XML?) or your Web Service should do it. And if the WPF client is supposed to save the Students then what is the Web Service for?

3) You don't have a ViewModel defined anywhere for the Student class which in this case is Model.

I have created an example with 3 projects.

1) WebService - A WCF Service Project

2) StudentLib - A Class Library Project (where Student class is defined)

3) DesktopClient - A WPF Application Project

Here is the source code :

WebService.IStudentService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using StudentLib;

namespace WebService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IStudentService" in both code and config file together.
    [ServiceContract]
    public interface IStudentService
    {
        [OperationContract]
        StudentLib.Student GetStudentById(Int32 id);

        [OperationContract]
        void AddStudent(StudentLib.Student student);
    }
}

WebService.StudentService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using StudentLib;

namespace WebService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "StudentService" in code, svc and config file together.
    public class StudentService : IStudentService
    {
        public StudentLib.Student GetStudentById(int id)
        {
            return new StudentLib.Student() { Name = "John Doe", Score = 80, TimeAdded = DateTime.Now, Comment = "Average" };
        }

        public void AddStudent(StudentLib.Student student)
        {
            // Code to add student
        }
    }
}

WebService's Web.Config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <bindings />
    <client />
    <services>
      <service name="WebService.StudentService" behaviorConfiguration="metaDataBehavior">
        <endpoint address="basic" binding="basicHttpBinding" contract="WebService.IStudentService" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metaDataBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

StudentLib.Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;

namespace StudentLib
{
    [DataContract]
    public class Student
    {
        [DataMember]
        public String Name { get; set; }

        [DataMember]
        public Int32 Score { get; set; }

        [DataMember]
        public DateTime TimeAdded { get; set; }

        [DataMember]
        public String Comment { get; set; }
    }
}

DesktopClient.StudentViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesktopClient
{
    class StudentViewModel
    {
        protected StudentLib.Student Student { get; set; }

        public StudentViewModel(StudentLib.Student student)
        {
            this.Student = student;
        }

        public String Name { get { return Student.Name; } }
        public Int32 Score { get { return Student.Score; } }
        public DateTime TimeAdded { get { return Student.TimeAdded; } }
        public String Comment { get { return Student.Comment; } }
    }
}

DesktopClient.MainWindow.xaml

<Window x:Class="DesktopClient.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="400"
        Height="300"
        Loaded="Window_Loaded">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0"
                   Grid.Row="0">Name :</TextBlock>
        <TextBlock Grid.Column="1"
                   Grid.Row="0"
                   Text="{Binding Name}"></TextBlock>
        <TextBlock Grid.Column="0"
                   Grid.Row="1">Score :</TextBlock>
        <TextBlock Grid.Column="1"
                   Grid.Row="1"
                   Text="{Binding Score}"></TextBlock>
        <TextBlock Grid.Column="0"
                   Grid.Row="2">Time Added :</TextBlock>
        <TextBlock Grid.Column="1"
                   Grid.Row="2"
                   Text="{Binding TimeAdded}"></TextBlock>
        <TextBlock Grid.Column="0"
                   Grid.Row="3">Comment :</TextBlock>
        <TextBlock Grid.Column="1"
                   Grid.Row="3"
                   Text="{Binding Comment}"></TextBlock>
    </Grid>
</Window>

DesktopClient.MainWindow.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DesktopClient.StudentService;
using StudentLib;

namespace DesktopClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            IStudentService client = new StudentServiceClient();

            Student student = client.GetStudentById(1);
            DataContext = new StudentViewModel(student);

            client.AddStudent(new StudentLib.Student() { Name = "Jane Doe", Score = 70, TimeAdded = DateTime.Now, Comment = "Average" });
        }
    }
}

Here all the above mentioned problems are resolved :

1) The Student class is defined in a common assembly (StudentLib) referenced by both WebService project and DesktopClient project. So, while adding a Service Reference, that class is reused by the code generator.

2) I recommend all the storage related operations be in the Web Service and the Client app should just use Web Service to store data.

3) StudentViewModel class is used instead of Student class to display data in MainWindow.

decyclone
First application uses webservice to save data at database. Second application never save data in xmls and one perm month send this xmls to webservice and convert their to intances of students and save it at database
Ok, I got that. And what exactly do you mean by `How connect this two classes ?`?
decyclone