Академический Документы
Профессиональный Документы
Культура Документы
Preparado para
Mobile .Net Users Group
Preparado por:
Joaquin Raya Barberis
joaquin.raya@gmail.com
ADO.NET Sync Services con VS 2008
INDICE
1. Introducción ......................................................................................................................... 4
3. Epilogo: ............................................................................................................................... 36
www.mobilenug.com Pág. 2 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 3 de 36
ADO.NET Sync Services con VS 2008
1. Introducción
Microsoft Sync Framwork es la respuesta de Microsoft a los escenarios ocasionalmente
conectados. MSF 1.0 es la primera versión de un marco de desarrollo que permite el
desarrollo de cualquier tipo de solución que requiera de algún tipo de sincronización
en escenarios off-line de cualquier tipo de origen de datos sobre cualquier protocolo o
tipo de red y exponerlos como servicios WCF. Se distribuye con SQL Server 2008
debido a su afinidad en contextos de sincronización de datos y con Visual Studio 2008
.NET SP1.
www.mobilenug.com Pág. 4 de 36
ADO.NET Sync Services con VS 2008
http://msdn.microsoft.com/en-us/sync/default.aspx
2.1. Prerrequisitos
- VS 2008 SP1
- SQL Server, u otro servidor de BD con conectores para ADO.net y sobre la que
podamos hacer todo tipo de modificaciones
- Microsoft Synchronization Services for ADO.NET v1 SP1 (Devices)
- Microsoft SQL Server Compact 3.5 Service Pack 1 for Windows Mobile
www.mobilenug.com Pág. 5 de 36
ADO.NET Sync Services con VS 2008
Para este tutorial usaremos la BD Northwind, de los samples de MS SQL Server 2000. Si
no están instalados, los debes descargar de la MSDN en:
http://www.microsoft.com/Downloads/details.aspx?FamilyID=06616212-0356-46a0-
8da2-eebc53a68034&displaylang=en
www.mobilenug.com Pág. 6 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 7 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 8 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 9 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 10 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 11 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 12 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 13 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 14 de 36
ADO.NET Sync Services con VS 2008
Después, seleccionad el botón Add para seleccionar las tablas que participarán en la
sincronización, en este caso solamente Customers. Dejad todos los valores por
defecto, esto hará que el diseñador modifique el esquema de la base de datos
añadiendo las tablas, columnas y triggers que necesita para operar.
www.mobilenug.com Pág. 15 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 16 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 17 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 18 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 19 de 36
ADO.NET Sync Services con VS 2008
[WebMethod]
public Microsoft.Synchronization.Data.SyncContext
ApplyChanges(Microsoft.Synchronization.Data.SyncGroupMetadata groupMetadata,
System.Data.DataSet dataSet, Microsoft.Synchronization.Data.SyncSession syncSession)
{
throw new NotImplementedException();
}
[WebMethod]
public Microsoft.Synchronization.Data.SyncContext
GetChanges(Microsoft.Synchronization.Data.SyncGroupMetadata groupMetadata,
Microsoft.Synchronization.Data.SyncSession syncSession)
{
throw new NotImplementedException();
}
[WebMethod]
public Microsoft.Synchronization.Data.SyncSchema
GetSchema(System.Collections.ObjectModel.Collection<string> tableNames,
Microsoft.Synchronization.Data.SyncSession syncSession)
{
throw new NotImplementedException();
}
[WebMethod]
public Microsoft.Synchronization.Data.SyncServerInfo
GetServerInfo(Microsoft.Synchronization.Data.SyncSession syncSession)
{
throw new NotImplementedException();
}
www.mobilenug.com Pág. 20 de 36
ADO.NET Sync Services con VS 2008
[WebMethod]
public Microsoft.Synchronization.Data.SyncContext
ApplyChanges(Microsoft.Synchronization.Data.SyncGroupMetadata groupMetadata,
System.Data.DataSet dataSet, Microsoft.Synchronization.Data.SyncSession syncSession)
{
ServerSyncLibrary.NorthWindDataCacheServerSyncProvider ServerProvider = new
ServerSyncLibrary.NorthWindDataCacheServerSyncProvider();
return ServerProvider.GetServerInfo(syncSession);
}
www.mobilenug.com Pág. 21 de 36
ADO.NET Sync Services con VS 2008
Ahora vamos a configurar el WS para que se instale sobre el IIS local, para que el
cliente PDA pueda verlo. Vamos a Propiedades del proyecto, y seleccionamos la
pestaña Web. Aquí en Servers seleccionamos “Use local IIS Web Server”
www.mobilenug.com Pág. 22 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 23 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 24 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 25 de 36
ADO.NET Sync Services con VS 2008
Este proceso generará una clase Proxy para el servicio web. El problema es que genera
clases nuevas incluso para clases que ya tenemos definidas en nuestro proyecto, así
que hay que limpiar el código generado. Para esto, hacemos clic en el icono de
“Mostrar archivos ocultos del explorador de soluciones y desplegamos la
referencia web hasta ver el archivo Reference.cs
La directiva using:
using Microsoft.Synchronization.Data;
//--------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3053
//
// Changes to this file may cause incorrect behavior and will be
// lost if
// the code is regenerated.
// </auto-generated>
//--------------------------------------------------------------------
//
www.mobilenug.com Pág. 26 de 36
ADO.NET Sync Services con VS 2008
/// <remarks/>
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="SyncServiceSoap"
, Namespace="http://tempuri.org/")]
public partial class SyncService :
System.Web.Services.Protocols.SoapHttpClientProtocol {
/// <remarks/>
public SyncService() {
this.Url =
"http://10.49.66.41/WSServerProvider/SyncService.asmx";
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tem
puri.org/ApplyChanges", RequestNamespace="http://tempuri.org/",
ResponseNamespace="http://tempuri.org/",
Use=System.Web.Services.Description.SoapBindingUse.Literal,
ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrappe
d)]
public SyncContext ApplyChanges(SyncGroupMetadata
groupMetadata, System.Data.DataSet dataSet, SyncSession syncSession) {
object[] results = this.Invoke("ApplyChanges", new
object[] {
groupMetadata,
dataSet,
syncSession});
return ((SyncContext)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginApplyChanges(SyncGroupMetadata
groupMetadata, System.Data.DataSet dataSet, SyncSession syncSession,
System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("ApplyChanges", new object[] {
groupMetadata,
dataSet,
syncSession}, callback, asyncState);
}
/// <remarks/>
www.mobilenug.com Pág. 27 de 36
ADO.NET Sync Services con VS 2008
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tem
puri.org/GetChanges", RequestNamespace="http://tempuri.org/",
ResponseNamespace="http://tempuri.org/",
Use=System.Web.Services.Description.SoapBindingUse.Literal,
ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrappe
d)]
public SyncContext GetChanges(SyncGroupMetadata groupMetadata,
SyncSession syncSession) {
object[] results = this.Invoke("GetChanges", new object[]
{
groupMetadata,
syncSession});
return ((SyncContext)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetChanges(SyncGroupMetadata
groupMetadata, SyncSession syncSession, System.AsyncCallback callback,
object asyncState) {
return this.BeginInvoke("GetChanges", new object[] {
groupMetadata,
syncSession}, callback, asyncState);
}
/// <remarks/>
public SyncContext EndGetChanges(System.IAsyncResult
asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((SyncContext)(results[0]));
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tem
puri.org/GetSchema", RequestNamespace="http://tempuri.org/",
ResponseNamespace="http://tempuri.org/",
Use=System.Web.Services.Description.SoapBindingUse.Literal,
ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrappe
d)]
public SyncSchema GetSchema(string[] tableNames, SyncSession
syncSession) {
object[] results = this.Invoke("GetSchema", new object[] {
tableNames,
syncSession});
return ((SyncSchema)(results[0]));
}
/// <remarks/>
www.mobilenug.com Pág. 28 de 36
ADO.NET Sync Services con VS 2008
/// <remarks/>
public SyncSchema EndGetSchema(System.IAsyncResult
asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((SyncSchema)(results[0]));
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tem
puri.org/GetServerInfo", RequestNamespace="http://tempuri.org/",
ResponseNamespace="http://tempuri.org/",
Use=System.Web.Services.Description.SoapBindingUse.Literal,
ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrappe
d)]
public SyncServerInfo GetServerInfo(SyncSession syncSession) {
object[] results = this.Invoke("GetServerInfo", new
object[] {
syncSession});
return ((SyncServerInfo)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetServerInfo(SyncSession
syncSession, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetServerInfo", new object[] {
syncSession}, callback, asyncState);
}
/// <remarks/>
public SyncServerInfo EndGetServerInfo(System.IAsyncResult
asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((SyncServerInfo)(results[0]));
}
}
}
Debemos repetir este proceso cada vez que se actualice la definición del WS, pero eso no
debería ser muy frecuente.
www.mobilenug.com Pág. 29 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 30 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 31 de 36
ADO.NET Sync Services con VS 2008
www.mobilenug.com Pág. 32 de 36
ADO.NET Sync Services con VS 2008
Ahora añadimos cinco botones: Insert, Update, Delete, Sync y Load. Los tres primeros
harán operaciones de ejemplo y las guardarán en la BD, con el siguiente código:
dt[0].CompanyName = "UPD";
this.customersTableAdapter1.Update(this.northwindDataSet1);
}
dt[0].Delete();
this.customersTableAdapter1.Update(this.northwindDataSet1);
}
El botón Load se ocupará de cargar la grid con los datos de la BD, con el siguiente código:
Y por último, el más importante: el botón Sync, que iniciará la sincronización con el
servidor con el siguiente código:
Agent.LocalProvider = ClientProvider;
Agent.RemoteProvider = ServerProvider;
www.mobilenug.com Pág. 33 de 36
ADO.NET Sync Services con VS 2008
Agent.Customers.SyncDirection = Microsoft.Synchronization.Data.SyncDirection.Bidirectional;
Microsoft.Synchronization.Data.SyncStatistics s;
s = Agent.Synchronize();
if (s.UploadChangesFailed > 0)
{
MessageBox.Show("Han habido fallos en la sincronización de subida");
}
Cursor.Current = Cursors.Default;
}
www.mobilenug.com Pág. 34 de 36
ADO.NET Sync Services con VS 2008
Ya tenemos una aplicación que sincroniza. Por defecto, en caso de conflicto de datos
entre el cliente y el servidor, gana el servidor, y si es entre clientes gana el último en
enviar. Pero es probable que queramos modificar esta situación por defecto, para
hacer que gane siempre el cliente, o quizás para tomar la decisión en base a una lógica
de negocio (ej. las actualizaciones del jefe ganan a las del subordinado, o viceversa)
El código de ejemplo fuerza a que en caso de conflicto el último cambio en llegar gane,
pero con los datos que devuelve ApplyChangeFailedEventArgs podemos implementar
lógica de cualquier tipo.
www.mobilenug.com Pág. 35 de 36
ADO.NET Sync Services con VS 2008
3. Epilogo:
Con esta “pequeña” guía Joaquin nos muestra lo sencillo que es trabajar con ADO.NET
Sync Services para Mobile y la potencia que podemos desplegar gracias a esta
tecnológia.
Desde MobileNug le damos las gracias a Joaquin por esta valiosa aportación.
http://www.mobilenug.com/descargas/Descarga%20de%20soluciones/HOWTO-
SyncFrameworkMobile.rar
Saludos
www.mobilenug.com Pág. 36 de 36