internal static void PlainCopy(Serializer context, ISerializableObject from, ISerializableObject to, FieldLock fieldLock, bool forceForeignKeyCopy) { AttributeWorker w = AttributeWorker.GetInstance(context.Target); FieldInfo[] fis = AttributeWorker.RetrieveAllFields(from.GetType()); foreach (FieldInfo fi in fis) { if (fieldLock.IsLocked(fi)) continue; if (AttributeWorker.IsRelationField(fi)) continue; if (w.IsAutoincID(fi)) continue; if (!w.IsPersistentField(fi)) continue; if (AttributeWorker.IsRowGuid(fi)) continue; if (w.IsForeignKey(context, fi) && !forceForeignKeyCopy) { DirectSyncAttribute a = (DirectSyncAttribute)Attribute.GetCustomAttribute(fi, typeof(DirectSyncAttribute)); if (a == null) continue; } Object val = fi.GetValue(from); fi.SetValue(to, val); } }
private WeakReference GetManagedMetaDataKey(ISerializableObject obj) { WeakReference tmp = null; List<WeakReference> obsoleteKeys = new List<WeakReference>(); foreach (WeakReference r in _managedMetaDataKeys) { if (r.Target == obj) { tmp = r; } //speichere obsolete keys if (!r.IsAlive) { obsoleteKeys.Add(r); } } //entferne alle obsoleten keys foreach (WeakReference r in obsoleteKeys) { _managedMetaDataKeys.Remove(r); _managedMetaData.Remove(r); } //Wenn der Metadaten schlüssel nicht vorhanden ist, dann erzeuge einen neuen if (tmp == null) { tmp = new WeakReference(obj); _managedMetaDataKeys.Add(tmp); } return tmp; }
private void Deserialize(XElement XElement, ISerializableObject SerializableObject) { System.Runtime.Serialization.SerializationInfo si = new System.Runtime.Serialization.SerializationInfo(SerializableObject.GetType(), new System.Runtime.Serialization.FormatterConverter()); if (XElement != null) { foreach (XElement xelem in XElement.Elements()) { if (!xelem.HasElements && !string.IsNullOrEmpty(xelem.Value)) { si.AddValue(xelem.Name.LocalName, xelem.Value); } } if (SerializableObject.ChildrenSerializable != null) { foreach (ISerializableObject childSerializable in SerializableObject.ChildrenSerializable.Where(p=> p!=null && !p.SerializationTag.IsEmpty)) { XElement xelem = XElement.Elements(). Where(p => p.Name == childSerializable.SerializationTag.Type). Where(p => XmlLinq.GetAttribute(p, "name") == childSerializable.SerializationTag.Name).FirstOrDefault(); Deserialize(xelem, childSerializable); } } } SerializableObject.Deserialize(si); }
private void Serialize(XElement XElement, ISerializableObject SerializableObject) { System.Runtime.Serialization.SerializationInfo si = new System.Runtime.Serialization.SerializationInfo(SerializableObject.GetType(), new System.Runtime.Serialization.FormatterConverter()); SerializableObject.Serialize(si); XElement elem = new XElement(SerializableObject.SerializationTag.Type); elem.Add(new XAttribute("name", SerializableObject.SerializationTag.Name)); foreach (System.Runtime.Serialization.SerializationEntry entry in si) { elem.Add(new XElement(entry.Name, entry.Value)); } if (SerializableObject.ChildrenSerializable != null) { foreach (ISerializableObject childSerializable in SerializableObject.ChildrenSerializable.Where(p=>p != null)) { Serialize(elem, childSerializable); } } if (!elem.IsEmpty) XElement.Add(elem); }
public static void Serialize(ISerializableObject SerializableObject, string Tag) { System.IO.Stream stream = SerailizationStream.GetStream(Tag, false); SerializationFormatter.Serialize(stream, SerializableObject); stream.Close(); }
public CsvPimaryKey(ISerializableObject iso, String target) { _type = iso.GetType(); IDictionary<String, FieldInfo> ids = AttributeWorker.GetInstance(target).GetPrimaryKeyFields(iso.GetType()); List<String> tmpList = new List<String>(ids.Count); StringBuilder csvKey = new StringBuilder(); String tmp; foreach (String id in ids.Keys) { StringBuilder tmpBuilder = new StringBuilder(); _fields.Add(ids[id]); _values.Add(ids[id].GetValue(iso)); try { //if (ids[id].GetValue(iso) is DateTime) //{ // DateTime dt = (DateTime)ids[id].GetValue(iso); // tmp = SqlUtil.SqlConvert(dt); //} //else // tmp = ids[id].GetValue(iso).ToString(); tmp = SqlUtil.SqlConvert(ids[id].GetValue(iso)).ToString(); } catch(NullReferenceException ex) { throw new KeyNotFoundException("", ex); } //Maskierung der Kommata tmp = tmp.Replace("/", "//"); tmp = tmp.Replace(";", "/;"); tmp = tmp.Replace("=", "/="); tmpBuilder.Append(id).Append("="); tmpBuilder.Append(tmp); tmpList.Add(tmpBuilder.ToString()); } tmpList.Sort(); bool initial = true; foreach (String s in tmpList) { if (!initial) { csvKey.Append(";"); } initial = false; csvKey.Append(s); } _csvKey = csvKey.ToString(); }
//public SyncItem SyncItem //{ // get { return _SyncItem; } // set { _SyncItem = value; } //} public void ComputeFieldState(FieldInfo fi, ISerializableObject iso) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); FieldName = fi.Name; StringBuilder b = new StringBuilder(); b.Append(fi.GetValue(iso)); Byte[] tmp = encoding.GetBytes(b.ToString()); HashCode = BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(tmp)).Replace("-", "").ToLower(); }
public SelectionContainer(ISerializableObject iso, bool truncate) { owner = iso; relatedObjects = new List<ISerializableObject>(); this.truncate = truncate; if (truncate == false) topDown(owner, relatedObjects); relatedObjects.Add(owner); bottomUp(owner, relatedObjects); }
public static void Deserialize(ISerializableObject SerializableObject, string Tag) { System.IO.Stream stream = SerailizationStream.GetStream(Tag, true); if (stream != null) { SerializationFormatter.Deserialize(stream, SerializableObject); stream.Close(); } }
public ConflictHandling(ISerializableObject o1, ISerializableObject o2) { if (o1 == null || o2 == null) throw new Exception("Objects may not be null"); if(o1.GetType()!=o2.GetType()) throw new Exception("You can only compare objects of the same type."); this.ownerType = o1.GetType(); this.object1 = o1; this.object2 = o2; this.conflicts = new List<Conflict>(); }
public static DeserializationQueryStrategy CreateStrategy(ISerializableObject data) { switch (data.DeserializationStrategy) { case ALL_AND: return new AllAndDeserializationQueryCreationStrategy(data); case ALL_AND_IS_LIKE: return new AllAndIsLikeDeserializationQueryCreationStrategy(data); case ALL_OR_IS_LIKE: return new AllOrIsLikeDeserializationQueryCreationStrategy(data); } throw new StrategyNotFoundException("Deserialization strategy \"" + data.DeserializationStrategy + "\" not found"); }
public void Serialize(System.IO.Stream Stream, ISerializableObject SerializableObject) { XDocument xdoc = new XDocument(); xdoc.Add(new XElement("Root")); Serialize(xdoc.Root, SerializableObject); System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(Stream, new System.Xml.XmlWriterSettings() { Indent = true }); xdoc.WriteTo(xmlWriter); xmlWriter.Close(); }
public void Deserialize(System.IO.Stream Stream, ISerializableObject SerializableObject) { if (Stream.Length != 0) { XDocument xdoc = new XDocument(); System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(Stream, new System.Xml.XmlReaderSettings() { IgnoreWhitespace = true }); xdoc = XDocument.Load(xmlReader); xmlReader.Close(); Deserialize((XElement)xdoc.Root.FirstNode, SerializableObject); } }
internal ISOViewModelBase(ISerializableObject thisObj, ISOViewModelContainer container) { _obj = thisObj; _container = container; Name = getName(); Icon = getIcon(); if (!isRoot()) { var pVM = _container.getViewModelForISO(Parent); pVM.injectChild(this); } fillProperties(); }
/// <summary> /// Gets the AutoIncPrimaryKey setter. /// </summary> /// <param name="data">The ISerializableObject object.</param> /// <returns>MethodInfo</returns> public static MethodInfo GetAutoIncPrimaryKeySetter(ISerializableObject data) { PropertyInfo[] properties = data.GetType().GetProperties(); foreach (PropertyInfo p in properties) { ColumnAttribute attribute = GetColumnAttribute(p); if (attribute != null && attribute is AutoIncPrimaryKeyAttribute) { return p.GetSetMethod(); } } return null; }
/// <summary> /// Determines whether the ISerializableObject object contains an AutoIncPrimaryKey. /// </summary> /// <param name="data">The ISerializableObject object.</param> /// <returns> /// <c>true</c> if the ISerializableObject object contains an AutoIncPrimaryKey; otherwise, <c>false</c>. /// </returns> public static bool ContainsAutoIncPrimaryKey(ISerializableObject data) { PropertyInfo[] properties = data.GetType().GetProperties(); foreach (PropertyInfo p in properties) { ColumnAttribute attribute = GetColumnAttribute(p); if (attribute != null && attribute is AutoIncPrimaryKeyAttribute) { return true; } } return false; }
internal static void ForeignKeyCopy(Serializer context, ISerializableObject from, ISerializableObject to, FieldLock fieldLock) { AttributeWorker w = AttributeWorker.GetInstance(context.Target); FieldInfo[] fis = AttributeWorker.RetrieveAllFields(from.GetType()); foreach (FieldInfo fi in fis) { if (fieldLock.IsLocked(fi)) continue; if (!w.IsForeignKey(context, fi)) continue; Object val = fi.GetValue(from); fi.SetValue(to, val); } }
public static SerializationQueryStrategy CreateStrategy(ISerializableObject data, SerializationMetaData metaData) { switch (data.SerializationStrategy) { case DEFAULT: return new UpdateIfDeserializedSerializationQueryStrategy(data, metaData); case UPDATE_BY_PRIMARYKEY: return new UpdateByPrimaryKeySerializationQueryStrategy(data); case INSERT: return new InsertSerializationQueryStrategy(data); case REMOVE: return new RemoveSerializationQueryStrategy(data); } throw new StrategyNotFoundException("Serialization strategy \""+data.SerializationStrategy+"\" not found"); }
internal SerializationMetaData GetSerializationMetaData(ISerializableObject obj) { //hole den Schlüssel für die Metadaten WeakReference key = GetManagedMetaDataKey(obj); SerializationMetaData res; //Wenn es bereits Metadaten gibt, dann gebe diese zurück if (_managedMetaData.TryGetValue(key, out res)) { return res; } //Ansonsten neue Metadaten anlegen und zurückgeben else { res = new SerializationMetaData(); _managedMetaData.Add(key, res); return res; } }
public AnalyzeForm(SyncContainer cont) { InitializeComponent(); sourceObject = cont.SourceObject; sinkObject = cont.SinkObject; if(sourceObject.GetType() != sinkObject.GetType()) { MessageBox.Show("Incompatible Types!"); this.Close(); } propertyGridRepository.SelectedObject = sourceObject; propertyGridMobileDB.SelectedObject = sinkObject; objectType =sourceObject.GetType(); readType(objectType); editObject= (ISerializableObject) objectType.GetConstructor(new Type[] {}).Invoke(new object[] {});//Konstruktor für unbekanntes Objektt propertyGridEdit.SelectedObject = editObject; }
public TreeViewModelTest() { //Mock ISO rootISOMock = new Mock<ISerializableObject>(); rootISOMock.Setup(o=>o.Rowguid).Returns(Guid.NewGuid()); _rootISO = rootISOMock.Object; //VM returned for the above ISO rootVMMock = new Mock<IISOViewModel>(); rootVMMock.Setup(o => o.Parent).Returns(()=>null); rootVMMock.Setup(o => o.Name).Returns(_rootISOName).Verifiable(); rootVMMock.Setup(o => o.Icon).Returns(ISOIcon.Agent).Verifiable(); rootVMMock.Setup(o => o.Rowguid).Returns(_rootISO.Rowguid); storeMock = new Mock<IISOViewModelStore>(); storeMock.Setup(s => s.addOrRetrieveVMForISO(_rootISO)).Returns(rootVMMock.Object).Verifiable(); _store = storeMock.Object; _tree = new TreeViewModel(_store); }
public static bool isRoot(ISerializableObject iso) { if (iso != null) { if (iso.GetType().Equals(typeof(CollectionEventSeries))) return true; else if (iso.GetType().Equals(typeof(CollectionEvent))) { CollectionEvent ce = (CollectionEvent)iso; if (ce.SeriesID == null) return true; } else if (iso.GetType().Equals(typeof(CollectionSpecimen))) { CollectionSpecimen spec = (CollectionSpecimen)iso; if (spec.CollectionEventID == null) return true; } } return false; }
public override void CopySpecific(ISerializableObject serializableObject) { NotificationConfiguration c = serializableObject as NotificationConfiguration; if (c != null) { this.SmtpAddress = c.SmtpAddress; this.SmtpUserName = c.SmtpUserName; this.SmtpPassword = c.SmtpPassword; this.FromAddress = c.FromAddress; this.NotifyToEmail = c.NotifyToEmail; this.NotifyOnComment = c.NotifyOnComment; this.NotifyOnFormResponse = c.NotifyOnFormResponse; } }
public void MergeFrom(ISerializableObject so) { throw new NotImplementedException(); }
public static void Save(ISerializableObject res, string filepath) { var resFile = new ResourceFile(res); resFile.Save(filepath); }
public bool HasChanged(String target, ISerializableObject iso) { String hc = ComputeHashCode(target, iso); return(hc.Equals(_Hashcode)); }
public int GenerateId(ISerializableObject ser, ref BitArray32 updateAttr) { updateAttr[Constants.updateAttrCreated] = true; SetChanged(); return(idGenerator.GetId(ser.ClassId)); }
public static IISOViewModel fromISO(ISerializableObject obj) { if (obj != null) { if (obj is CollectionAgent) return new AgentVM(obj as CollectionAgent); if (obj is CollectionEventLocalisation) return new EventLocalisationVM(obj as CollectionEventLocalisation); if (obj is CollectionEventProperty) return new EventPropertyVM(obj as CollectionEventProperty); if (obj is CollectionEventSeries) return new EventSeriesVM(obj as CollectionEventSeries); if (obj is CollectionEvent) return new EventVM(obj as CollectionEvent); if (obj is IdentificationUnitAnalysis) return new IUAnalysisVM(obj as IdentificationUnitAnalysis); if (obj is IdentificationUnitGeoAnalysis) return new IUGeoAnalysisVM(obj as IdentificationUnitGeoAnalysis); if (obj is IdentificationUnit) return new IdentificationUnitVM(obj as IdentificationUnit); if (obj is CollectionSpecimen) return new SpecimenVM(obj as CollectionSpecimen); return new DefaultVM(obj); } return null; }
/// <summary> /// Returns the table name for the passed object. /// </summary> /// <param name="data">The ISerializableObject object.</param> /// <returns>string</returns> public static string GetTableMapping(ISerializableObject data) { Attribute a = Attribute.GetCustomAttribute(data.GetType(), typeof(TableAttribute)); string ret = null; if (a != null) ret = ((TableAttribute)a).TableMapping; if (ret == null) ret = data.GetType().Name; return ret; }
private string formatType(int index, ISerializableObject serializableObject) { return(string.Format("newGameObject{0}.Type = '{1}'\n", index, serializableObject.GetObjectInformation().GetObjectType())); }
public System.Object GetValue(string key, Type type, System.Object defaultValue = null) { //Segment --- Should be identical to a segment in GetUnityReferenceValue/GetValue if (!MoveToVariableAnchor(key)) { Debug.Log("Couldn't find key '" + key + "' in the data, returning default (" + (defaultValue == null ? "null" : defaultValue.ToString()) + ")"); return(defaultValue == null?GetDefaultValue(type) : defaultValue); } BinaryReader stream = readerStream; int magicNumber = (int)stream.ReadByte(); if (magicNumber == 0) { return(defaultValue == null?GetDefaultValue(type) : defaultValue); //Null reference usually } else if (magicNumber == 2) { Debug.Log("The variable '" + key + "' was not serialized correctly and can therefore not be deserialized"); return(defaultValue == null?GetDefaultValue(type) : defaultValue); } //Else - magic number is 1 - indicating correctly serialized data //Segment --- End System.Object ob = null; if (type == typeof(int)) { ob = stream.ReadInt32(); } else if (type == typeof(string)) { ob = stream.ReadString(); } else if (type == typeof(float)) { ob = stream.ReadSingle(); } else if (type == typeof(bool)) { ob = stream.ReadBoolean(); } else if (type == typeof(Vector3)) { ob = new Vector3(stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle()); } else if (type == typeof(Vector2)) { ob = new Vector2(stream.ReadSingle(), stream.ReadSingle()); } else if (type == typeof(Matrix4x4)) { Matrix4x4 m = new Matrix4x4(); for (int i = 0; i < 16; i++) { m[i] = stream.ReadSingle(); } ob = m; } else if (type == typeof(Bounds)) { Bounds b = new Bounds(); b.center = new Vector3(stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle()); b.extents = new Vector3(stream.ReadSingle(), stream.ReadSingle(), stream.ReadSingle()); ob = b; } else { if (type.GetConstructor(Type.EmptyTypes) != null) { System.Object testOb = Activator.CreateInstance(type); ISerializableObject sOb = (ISerializableObject)testOb; if (sOb != null) { string prePrefix = sPrefix; //Add to the prefix to avoid name collisions sPrefix += key + "."; sOb.DeSerializeSettings(this); ob = sOb; sPrefix = prePrefix; } } if (ob == null) { Debug.LogError("Can't deSerialize type '" + type.Name + "'"); ob = defaultValue == null?GetDefaultValue(type) : defaultValue; } } return(ob); }
/// <summary> /// Write an instance of <see cref="ISerializableObject"/> in the stream /// </summary> /// <param name="value"><see cref="ISerializableObject"/> to serialize</param> /// <returns>Returns the current instance</returns> public BasicWriter SetSerializableObject(ISerializableObject value) { value.Serialize(this); return(this); }
public static Guid RowGuid(ISerializableObject iso) { return((Guid)RowGuid(iso.GetType()).GetValue(iso)); }
public static void RowGuid(ISerializableObject iso, Guid value) { RowGuid(iso.GetType()).SetValue(iso, value); }
internal static void ForeignKeyCopy(Serializer context, ISerializableObject from, ISerializableObject to, FieldLock fieldLock) { AttributeWorker w = AttributeWorker.GetInstance(context.Target); FieldInfo[] fis = AttributeWorker.RetrieveAllFields(from.GetType()); foreach (FieldInfo fi in fis) { if (fieldLock.IsLocked(fi)) { continue; } if (!w.IsForeignKey(context, fi)) { continue; } Object val = fi.GetValue(from); fi.SetValue(to, val); } }
public void InsertObject(ISerializableObject iso, DbConnection connection, ISerializerTransaction transaction, string table) { AttributeWorker w = AttributeWorker.GetInstance(Target); DbCommand com = connection.CreateCommand(); com.CommandText = _owner.SerializeInsert(iso, table); transaction.Guard(com); //Console.WriteLine(com.CommandText); try { //Console.WriteLine(com.ExecuteNonQuery()); com.ExecuteNonQuery(); } catch (Exception ex) { throw new SerializerException("insert failed", ex); } FieldInfo autoincField; Guid g = AttributeWorker.RowGuid(iso); if ((autoincField = w.GetAutoincField(iso.GetType())) != null) { StringBuilder b = new StringBuilder(); b.Append("SELECT * FROM ").Append(w.GetTableMapping(iso.GetType(), _owner.Praefix)).Append(" WHERE "); b.Append(w.GetColumnMapping(AttributeWorker.RowGuid(iso.GetType()))).Append("='"); b.Append(g.ToString()).Append("'"); com.CommandText = b.ToString(); DbDataReader r = com.ExecuteReader(); if (r.Read()) { Object o = r[w.GetColumnMapping(w.GetAutoincField(iso.GetType()))]; autoincField.SetValue(iso, o); } else { r.Close(); throw new SerializerException("Insert core method failed! error unknown..."); } r.Close(); /*com.CommandText = "SELECT @@IDENTITY"; * Object o = com.ExecuteScalar(); * Console.WriteLine("---->"+o); * if (o is DBNull) * { * throw new SerializerException(); * } * * autoincField.SetValue(iso, Decimal.ToInt32((Decimal)o)); */ } GenericWeakReference <ISerializableObject> tmp = new GenericWeakReference <ISerializableObject>(iso); _persistentObjects[g] = tmp; MemoriseKeys(iso, w, tmp); }
public DefaultVM(ISerializableObject iso) : base(iso) { }
public void AddValue(string key, System.Object value) { //Segment --- Should be identical to a segment in AddUnityReferenceValue/AddValue BinaryWriter stream = writerStream; AddVariableAnchor(key); if (value == null) { stream.Write((byte)0); //Magic number indicating a null reference return; } //Magic number indicating that the data is written and not null stream.Write((byte)1); //Segment --- End Type type = value.GetType(); //stream.Write (type.Name); if (type == typeof(int)) { stream.Write((int)value); } else if (type == typeof(string)) { string st = (string)value; stream.Write(st); } else if (type == typeof(float)) { stream.Write((float)value); } else if (type == typeof(bool)) { stream.Write((bool)value); } else if (type == typeof(Vector3)) { Vector3 d = (Vector3)value; stream.Write(d.x); stream.Write(d.y); stream.Write(d.z); } else if (type == typeof(Vector2)) { Vector2 d = (Vector2)value; stream.Write(d.x); stream.Write(d.y); } else if (type == typeof(Matrix4x4)) { Matrix4x4 m = (Matrix4x4)value; for (int i = 0; i < 16; i++) { stream.Write(m[i]); } } else if (type == typeof(Bounds)) { Bounds b = (Bounds)value; stream.Write(b.center.x); stream.Write(b.center.y); stream.Write(b.center.z); stream.Write(b.extents.x); stream.Write(b.extents.y); stream.Write(b.extents.z); } else { ISerializableObject sOb = value as ISerializableObject; if (sOb != null) { string prePrefix = sPrefix; //Add to the prefix to avoid name collisions sPrefix += key + "."; sOb.SerializeSettings(this); sPrefix = prePrefix; } else { UnityEngine.Object ueOb = value as UnityEngine.Object; if (ueOb != null) { Debug.LogWarning("Unity Object References should be added using AddUnityReferenceValue"); WriteError(); stream.BaseStream.Position -= 1; //Overwrite the previous magic number stream.Write((byte)2); //Magic number indicating an error while serializing } else { Debug.LogError("Can't serialize type '" + type.Name + "'"); WriteError(); stream.BaseStream.Position -= 1; //Overwrite the previous magic number stream.Write((byte)2); //Magic number indicating an error while serializing } } } }
public abstract Object LoadOneToMany(ISerializableObject owner, Type storedType, Serializer serializer);
private void insertPicture(ISerializableObject manipulatedObject) { this.pictrans.transferPicture(manipulatedObject); }
public void Add(ISerializableObject iso) { this._pool.AddISerializableObject(iso); }
//public IDirectAccessIterator<FieldState> FieldStates //{ // get { return _FieldStates; } // set { _FieldStates = value; } //} //public bool HasChanged(String target, ISerializableObject iso) //{ // String hc = ComputeHashCode(target, iso); // return hc.Equals(_Hashcode); //} public bool HasChanged(ISerializableObject iso) { return(iso.LogTime > _SyncTime); }
protected QueryStrategy(ISerializableObject data) { this.data = data; table = AttributeUtilities.GetTableMapping(data); properties = data.GetType().GetProperties(); }
public void transferPicture(ISerializableObject iso) { resetInformation(); _service = new DiversityMediaServiceClient(); if (_service.State != System.ServiceModel.CommunicationState.Opened) { try { _service.Open(); } catch (Exception e) { StringBuilder sb = new StringBuilder("Cant Open Connection: ").Append(e.Message); if (e.InnerException != null) { sb.Append(","); sb.Append(e.InnerException.Message); } throw new Exception(sb.ToString()); } } _author = this._userName; _projectId = this._project; //Fallunterscheidung nach ImageTypeClasse um benötigte informationen zu bekommen try { if (iso is CollectionEventImage) { CollectionEventImage cei = (CollectionEventImage)iso; _rowGuid = cei.Rowguid.ToString(); string pureFileName = System.IO.Path.GetFileName(cei.URI); string path = System.IO.Directory.GetCurrentDirectory(); StringBuilder sb = new StringBuilder(_pictureDirectory); sb.Append("\\"); sb.Append(pureFileName); _pathName = sb.ToString(); _type = cei.ImageType; IRestriction re = RestrictionFactory.Eq(typeof(CollectionEvent), "_CollectionEventID", cei.CollectionEventID); CollectionEvent ce = _sourceSerializer.Connector.Load<CollectionEvent>(re); IRestriction r1 = RestrictionFactory.Eq(typeof(CollectionEventLocalisation), "_CollectionEventID", cei.CollectionEventID); IRestriction r2 = RestrictionFactory.Eq(typeof(CollectionEventLocalisation), "_LocalisationSystemID", 8); IRestriction r = RestrictionFactory.And().Add(r1).Add(r2); CollectionEventLocalisation cel = _sourceSerializer.Connector.Load<CollectionEventLocalisation>(r); if (cel != null) { if (cel.AverageAltitudeCache != null) _longitude = (float)cel.AverageLongitudeCache; if (cel.AverageLatitudeCache != null) _latitude = (float)cel.AverageLatitudeCache; if (cel.AverageLongitudeCache != null) _altitude = (float)cel.AverageAltitudeCache; } _timestamp = cei.LogTime.ToString(); } else if (iso.GetType().Equals(typeof(CollectionSpecimenImage))) { CollectionSpecimenImage csi = (CollectionSpecimenImage)iso; _rowGuid = csi.Rowguid.ToString(); string pureFileName = System.IO.Path.GetFileName(csi.URI); string path = System.IO.Directory.GetCurrentDirectory(); StringBuilder sb = new StringBuilder(_pictureDirectory); sb.Append("\\"); sb.Append(pureFileName); _pathName = sb.ToString(); _type = csi.ImageType; IRestriction re = RestrictionFactory.Eq(typeof(CollectionSpecimen), "_CollectionSpecimenID", csi.CollectionSpecimenID); CollectionSpecimen cs = _sourceSerializer.Connector.Load<CollectionSpecimen>(re); CollectionEvent ce = cs.CollectionEvent; IRestriction r1 = RestrictionFactory.Eq(typeof(CollectionEventLocalisation), "_CollectionEventID", ce.CollectionEventID); IRestriction r2 = RestrictionFactory.Eq(typeof(CollectionEventLocalisation), "_LocalisationSystemID", 8); IRestriction r = RestrictionFactory.And().Add(r1).Add(r2); CollectionEventLocalisation cel = _sourceSerializer.Connector.Load<CollectionEventLocalisation>(r); if (cel != null) { if (cel.AverageAltitudeCache != null) _longitude = (float)cel.AverageLongitudeCache; else _longitude = 0; if (cel.AverageLatitudeCache != null) _latitude = (float)cel.AverageLatitudeCache; else _latitude = 0; if (cel.AverageLongitudeCache != null) _altitude = (float)cel.AverageAltitudeCache; else _altitude = 0; } else { _latitude = _longitude = _altitude = 0; } _timestamp = csi.LogTime.ToString(); } else { throw new TransferException("ImageClass not Supported"); } } catch (Exception e) { StringBuilder sb = new StringBuilder("Corresponding data not found: ").Append(e.Message); if (e.InnerException != null) { sb.Append(","); sb.Append(e.InnerException.Message); } throw new Exception(sb.ToString()); } FileStream fileStrm = null; BinaryReader rdr = null; byte[] data = null; DateTime start = DateTime.Now; String retString = String.Empty; try { // Create stream and reader for file data fileStrm = new FileStream(_pathName, FileMode.Open, FileAccess.Read); rdr = new BinaryReader(fileStrm); } catch(Exception e) { StringBuilder sb = new StringBuilder("Picture not found: ").Append(e.Message); if (e.InnerException != null) { sb.Append(","); sb.Append(e.InnerException.Message); } if (rdr != null) rdr.Close(); throw new Exception(sb.ToString()); } try { // Number of bytes to be transferred long numBytes = fileStrm.Length; // Package counter int count = 0; // Return string _fileName = Path.GetFileName(_pathName); if (numBytes > 0) { data = rdr.ReadBytes((int)numBytes); count++; //retString = f.ReadFileAndTransfer(pathName); retString = _service.Submit(_fileName, _fileName, _type, _latitude, _longitude, _altitude, _author, _timestamp, _projectId, data); // IDs 372, 373, 374 } TimeSpan dif = DateTime.Now - start; if (retString.StartsWith("http")) { MessageBox.Show(retString); MessageBox.Show(dif.ToString() + " msec - " + count.ToString() + " packets transmitted"); } else { MessageBox.Show("ERROR: " + retString); } // Close reader and stream rdr.Close(); fileStrm.Close(); } catch (Exception e) { StringBuilder sb = new StringBuilder("Transfer Error: ").Append(e.Message); if (e.InnerException != null) { sb.Append(","); sb.Append(e.InnerException.Message); } if (rdr != null) rdr.Close(); if (fileStrm != null) fileStrm.Close(); throw new Exception(sb.ToString()); } finally { // Abort faulted proxy if (_service.State == System.ServiceModel.CommunicationState.Faulted) { // Webservice method call // proxy.Rollback(); _service.Abort(); } // Close proxy else if (_service.State == System.ServiceModel.CommunicationState.Opened) { _service.Close(); } } if (iso.GetType().Equals(typeof(CollectionEventImage))) { CollectionEventImage cei = (CollectionEventImage)iso; cei.URI = retString; } if (iso.GetType().Equals(typeof(CollectionSpecimenImage))) { CollectionSpecimenImage csi = (CollectionSpecimenImage)iso; csi.URI = retString; } // Close reader and stream rdr.Close(); fileStrm.Close(); }
public override void CopySpecific(ISerializableObject serializableObject) { Gallery c = serializableObject as Gallery; if (c != null) { this.Url = c.Url; this.Title = c.Title; this.Navigation = c.Navigation; this.Description = c.Description; if (c.photos != null) { // add photos foreach (string photo in c.photos) { this.photos.Add(photo); } } } }
public sealed override void Resolve(ISerializableObject resolved) { throw new InvalidOperationException(); }
public ResourceFile(ISerializableObject resource) { Resource = resource; }
public abstract void Resolve(ISerializableObject resolved);
public void Deserialize(ISerializableObject so) { throw new NotImplementedException(); }
public ConflictResolvedState(SyncContainer owner, ISerializableObject resolved, SyncItem sourceSyncItem) : base(owner, sourceSyncItem) { _resolved = resolved; }
public void Register(ISerializableObject iso) { AttributeWorker.RowGuid(iso, Guid.NewGuid()); }
internal ConflictResolvedState(SyncContainer owner, ISerializableObject resolved, SyncItem sourceSyncItem, SyncState previous) : base(owner, sourceSyncItem, previous) { _resolved = resolved; }
public override void CopySpecific(ISerializableObject serialzableObject) { Template template = serialzableObject as Template; if (template != null) { this.Name = template.Name; this.IsActivated = template.IsActivated; this.MasterFileName = template.MasterFileName; this.TemplatePath = template.TemplatePath; this.UrlPath = template.UrlPath; } }
public override void Resolve(ISerializableObject resolved) { StateOwner.SyncState = new ConflictResolvedState(StateOwner, resolved, _sourceSyncItem, this); }
public override void Resolve(ISerializableObject resolved) { throw new InvalidOperationException("Objects in PrematureState cannont not perform any actions. Run SyncTool.Analyze first!"); }
public ISOViewModel(ISerializableObject obj) { ISO = obj; Name = getName(); Icon = getIcon(); }
private void loadCollectionDefinitionsWorker(IReportDetailedProgress progress) { ObjectSyncList transferList = new ObjectSyncList(); progress.advanceProgress(5); String sql = null; IList <ISerializableObject> list = null; progress.ProgressDescriptionID = 1160; try { sql = @"SELECT * FROM [" + OptionsAccess.RepositoryOptions.InitialCatalog + "].[dbo].[AnalysisProjectList] (" + ConnectionsAccess.Profile.ProjectID + ")"; list = ConnectionsAccess.RepositoryDB.Connector.LoadList(typeof(Analysis), sql); transferList.addList(list); foreach (ISerializableObject iso in list) { Analysis ana = (Analysis)iso; IRestriction rana = RestrictionFactory.Eq(typeof(AnalysisResult), "_AnalysisID", ana.AnalysisID); IList <ISerializableObject> resultList = ConnectionsAccess.RepositoryDB.Connector.LoadList(typeof(AnalysisResult), rana); transferList.addList(resultList); } } catch (Exception e) { MessageBox.Show(e.Message); _Log.ErrorFormat("Exception while updating AnalysisTaxonomicGroups: {0}", e);; } sql = @"SELECT AnalysisID,TaxonomicGroup,RowGUID FROM [" + OptionsAccess.RepositoryOptions.InitialCatalog + "].[dbo].[AnalysisTaxonomicGroupForProject] (" + ConnectionsAccess.Profile.ProjectID + ")"; IList <AnalysisTaxonomicGroup> atgList = new List <AnalysisTaxonomicGroup>(); IDbConnection connRepository = ConnectionsAccess.RepositoryDB.CreateConnection(); connRepository.Open(); IDbCommand com = connRepository.CreateCommand(); com.CommandText = sql; IDataReader reader = null; try { reader = com.ExecuteReader(); while (reader.Read()) { AnalysisTaxonomicGroup atg = new AnalysisTaxonomicGroup(); atg.AnalysisID = reader.GetInt32(0); atg.TaxonomicGroup = reader.GetString(1); atg.Rowguid = Guid.NewGuid(); atgList.Add(atg); } connRepository.Close(); } catch (Exception e) { MessageBox.Show(e.Message); _Log.ErrorFormat("Exception while updating AnalysisTaxonomicGroups: {0}", e);; connRepository.Close(); } foreach (AnalysisTaxonomicGroup atg in atgList) { foreach (ISerializableObject iso in list) { if (iso.GetType().Equals(typeof(Analysis))) { Analysis ana = (Analysis)iso; if (ana.AnalysisID == atg.AnalysisID) { transferList.addObject(atg); } } } } double progressPerType = 90d / _defTypes.Count; foreach (Type t in _defTypes) { transferList.Load(t, ConnectionsAccess.RepositoryDB); progress.advanceProgress(progressPerType); } transferList.initialize(LookupSynchronizationInformation.downloadDefinitionsList(), LookupSynchronizationInformation.getReflexiveReferences(), LookupSynchronizationInformation.getReflexiveIDFields()); List <ISerializableObject> orderedObjects = transferList.orderedObjects; progress.ProgressDescriptionID = 1161; foreach (ISerializableObject iso in orderedObjects) { try { ConnectionsAccess.MobileDB.Connector.InsertPlain(iso); } catch (Exception) { try { if (iso.GetType().Equals(typeof(AnalysisTaxonomicGroup))) { AnalysisTaxonomicGroup atg = (AnalysisTaxonomicGroup)iso; IRestriction r1 = RestrictionFactory.Eq(iso.GetType(), "_AnalysisID", atg.AnalysisID); IRestriction r2 = RestrictionFactory.Eq(iso.GetType(), "_TaxonomicGroup", atg.TaxonomicGroup); IRestriction r = RestrictionFactory.And().Add(r1).Add(r2); ISerializableObject isoStored = ConnectionsAccess.MobileDB.Connector.Load(iso.GetType(), r); atg.Rowguid = isoStored.Rowguid; } else { IRestriction r = RestrictionFactory.Eq(iso.GetType(), "_guid", iso.Rowguid); ISerializableObject isoStored = ConnectionsAccess.MobileDB.Connector.Load(iso.GetType(), r); } ConnectionsAccess.MobileDB.Connector.UpdatePlain(iso); } catch (Exception ex) { _Log.ErrorFormat("Exception while transferring [{0}]: [{1}]", iso, ex); } } } }
public abstract void UpdateOneToMany(Object collection, ISerializableObject owner, Type storedType, Serializer serializer);
public Conflict compareFields(FieldInfo fi, ISerializableObject o1, ISerializableObject o2) { Conflict conflict=null; Object v1 = fi.GetValue(object1); Object v2 = fi.GetValue(object2); if (v1 == null) { if (v2 != null) { conflict=new Conflict(ownerType, fi, v1, v2); } } else if (v2 == null) { conflict=new Conflict(ownerType, fi, v1, v2); } else if (!v1.Equals(v2)) { conflict=new Conflict(ownerType, fi, v1, v2); } return conflict; }
public void AppendObject(ISerializableObject obj) { obj.Serialize(this); }