private static object CreateWithValues(PropertyValues values, Type type = null) { if (type == null) { type = typeof(T); } try { return(values.ToObject()); } catch { var entity = Activator.CreateInstance(type); Debug.WriteLine(values.ToObject()); foreach (var p in values.Properties) { var name = p.Name; var value = values.GetValue <object>(name); var property = type.GetProperty(name); if (value == null) { continue; } var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; property.SetValue(entity, Convert.ChangeType(value, propertyType), null); } return(entity); } }
private static void WriteLineTag(Socket writer, OPCServer opcserver, string tagname) { try { int count = 0; Array PropertyIDs; Array Descriptions; Array DataTypes; Array PropertyValues; Array Errors; opcserver.QueryAvailableProperties((string)tagname, out count, out PropertyIDs, out Descriptions, out DataTypes); opcserver.GetItemProperties((string)tagname, count, ref PropertyIDs, out PropertyValues, out Errors); if (count <= 0 || count > 100) { return; } // [TagName, Confidence, Value, Timestamp] Dictionary <string, object> tag = new Dictionary <string, object>(); tag.Add("TagName", tagname); tag.Add("Quality", PropertyValues.GetValue(3)); tag.Add("Value", PropertyValues.GetValue(2)); tag.Add("TimeStamp", PropertyValues.GetValue(4).ToString()); Program.WriteLine(writer, serializer.Serialize(tag)); } catch (Exception ex) { System.Console.Out.WriteLine("Error {0}:{1}\n", tagname, ex.Message); } }
public void ReadPropertyValues(ref OPCTag tag) { // count 必须比 propIds.Length 少一个 int count = 4; List <int> propIds = new List <int>(); propIds.Add(0); propIds.Add(1); propIds.Add(2); propIds.Add(3); propIds.Add(4); Array PropertyIDs = propIds.ToArray(); Array PropertyValues; Array Errors; try{ mServer.GetItemProperties(tag.Name, count, ref PropertyIDs, out PropertyValues, out Errors); if ((count == 0) || (count > 10000)) { return; } for (int i = 1; i <= count; i++) { if (i == 1) { VarEnum dataType = (VarEnum)VarEnum.ToObject(typeof(VarEnum), PropertyValues.GetValue(i)); //tag.DataType = dataType; //var text = dataType.ToString(); // these methods are clunkier but run 25% faster on my machine var text2 = Enum.GetName(typeof(VarEnum), dataType); //var text3 = typeof(VarEnum).GetEnumName(dataType); tag.DataTypeText = text2; } else if (i == 2) { tag.SetValue(this, PropertyValues.GetValue(i)); } else if (i == 3) { tag.Quality = (OPCQuality)PropertyValues.GetValue(i); } else if (i == 4) { tag.ItemTimeStamp = (DateTime)PropertyValues.GetValue(i); } break; } } catch (Exception ex) { } }
public void ShouldThrowErrorWithConcurrencyViolation() { using (var transaction = _context.Database.BeginTransaction()) { var product = TestHelpers.CreateProduct("1"); _context.Product.Add(product); _context.SaveChanges(); string sql = $"UPDATE {_context.GetSqlServerTableName<Product>()} " + $"SET Name = 'Foo' WHERE {nameof(Product.ProductId)} = {product.ProductId}"; _context.Database.ExecuteSqlCommand(sql); product.MakeFlag = false; try { _context.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { //Get Current value for name var entityInError = ex.Entries[0]; PropertyValues originalValues = entityInError.OriginalValues; PropertyValues proposedValues = entityInError.CurrentValues; //This makes a database call to get the current values in the database PropertyValues databaseValues = entityInError.GetDatabaseValues(); Debug.WriteLine("Name"); Debug.WriteLine($"Original Name: {originalValues.GetValue<string>(nameof(Product.Name))}"); Debug.WriteLine($"Proposed Name: {proposedValues.GetValue<string>(nameof(Product.Name))}"); Debug.WriteLine($"Database Name: {databaseValues.GetValue<string>(nameof(Product.Name))}"); Debug.WriteLine("Make Flag"); //this is just a different syntax to above Debug.WriteLine( $"Original Make Flag: {entityInError.Property(nameof(Product.MakeFlag)).OriginalValue}"); Debug.WriteLine( $"Proposed Make Flag: {entityInError.Property(nameof(Product.MakeFlag)).CurrentValue}"); var modifiedProperties = entityInError.Properties.Where(p => p.IsModified).ToList(); foreach (var p in modifiedProperties) { Debug.WriteLine($"{p.Metadata.Name}:{p.OriginalValue}:{p.CurrentValue}"); } //This reloads the entity from the database, discarding any proposed changes //entityInError.Reload(); } transaction.Rollback(); } }
//public static T DeepClone<T>(T toClone) //{ // T toCloneInto = default(T); // var properties = toClone.GetType().GetProperties(); // foreach (var property in properties) // { // var value = property.GetValue(toClone); // property.SetValue(toCloneInto, value); // } // return toCloneInto; //} public static T CreateWithValues <T>(PropertyValues values) where T : new() { T entity = new T(); Type type = typeof(T); foreach (var name in values.Properties.Select(l => l.Name)) { var property = type.GetProperty(name); property.SetValue(entity, values.GetValue <object>(name)); } return(entity); }
public void GetItemProperties(string tagName) { int count = 4; List <int> propIds = new List <int>(); propIds.Add(0); propIds.Add(1); propIds.Add(2); propIds.Add(3); propIds.Add(4); Array PropertyIDs = propIds.ToArray(); Array PropertyValues; Array Errors; try{ mServer.GetItemProperties(tagName, count, ref PropertyIDs, out PropertyValues, out Errors); if ((count == 0) || (count > 10000)) { return; } for (int i = 1; i <= count; i++) { if (i == 1) { VarEnum foo = (VarEnum)VarEnum.ToObject(typeof(VarEnum), PropertyValues.GetValue(i)); var text = foo.ToString(); // "Clubs" // these methods are clunkier but run 25% faster on my machine var text2 = Enum.GetName(typeof(VarEnum), foo); // "Clubs" //var text3 = typeof(VarEnum).GetEnumName(foo); // "Clubs" } Console.WriteLine("in GetItemProperties, tagName is : " + tagName + ": DataType is: " + PropertyValues.GetValue(i).GetType() + ": " + PropertyIDs.GetValue(i) + ", " + PropertyValues.GetValue(i).ToString() + ", " + Errors.GetValue(i)); } } catch (Exception ex) { } }
private static void WriteHistoryModifiedState(AutoHistory history, EntityEntry entry, IEnumerable <PropertyEntry> properties) { dynamic json = new System.Dynamic.ExpandoObject(); dynamic bef = new System.Dynamic.ExpandoObject(); dynamic aft = new System.Dynamic.ExpandoObject(); PropertyValues databaseValues = null; foreach (var prop in properties) { if (prop.IsModified) { if (prop.OriginalValue != null) { if (!prop.OriginalValue.Equals(prop.CurrentValue)) { ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = prop.OriginalValue; } else { databaseValues ??= entry.GetDatabaseValues(); var originalValue = databaseValues.GetValue <object>(prop.Metadata.Name); ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = originalValue; } } else { ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = null; } ((IDictionary <String, Object>)aft)[prop.Metadata.Name] = prop.CurrentValue; } } ((IDictionary <String, Object>)json)["before"] = bef; ((IDictionary <String, Object>)json)["after"] = aft; history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Modified; history.Changed = JsonSerializer.Serialize(json, AutoHistoryOptions.Instance.JsonSerializerOptions); }
private void Browse(Socket writer) { Console.Out.WriteLine("start to browse ..."); try { string hostname = args["hostname"]; string servername = args["servername"]; OPCServer opcserver = new OPCServer(); opcserver.Connect(servername, hostname); OPCBrowser opcbrowser = opcserver.CreateBrowser(); //opcbrowser.Filter = args["tagname"]; //opcbrowser.DataType = short.Parse(args["datatype"]); opcbrowser.ShowBranches(); opcbrowser.ShowLeafs(true); long ItemCounts = opcbrowser.Count; Program.WriteLine(writer, "200, Tags total number: " + ItemCounts);// return the number of browsed tags int count = 0; Array PropertyIDs; Array Descriptions; Array DataTypes; Array PropertyValues; Array Errors; foreach (object tagname in opcbrowser) { // tag name, data type, original data type, description, EU type, scan rate, try { opcserver.QueryAvailableProperties((string)tagname, out count, out PropertyIDs, out Descriptions, out DataTypes); opcserver.GetItemProperties((string)tagname, count, ref PropertyIDs, out PropertyValues, out Errors); if (count <= 0 || count > 100) { return; } Dictionary <string, object> tag = new Dictionary <string, object>(); tag.Add("Name", tagname); tag.Add("DataType", DataTypes.GetValue(2)); tag.Add("SourceDataType", DataTypes.GetValue(1)); tag.Add("UnitsType", DataTypes.GetValue(7)); tag.Add("UnitsInfo", PropertyValues.GetValue(8)); tag.Add("ScanRate", PropertyValues.GetValue(6)); if (count > 8) { tag.Add("Description", (string)PropertyValues.GetValue(9)); } Program.WriteLine(writer, serializer.Serialize(tag)); } catch (Exception ex) { System.Console.Out.WriteLine("Error {0}:{1}\n", tagname, ex.Message); } } opcserver.Disconnect(); Program.WriteLine(writer, "###END###"); } catch { System.Console.Out.WriteLine("\browse {0}:{1} failed, \n{2}\n", args["hostname"], args["servername"]); Program.WriteLine(tcpclient.Client, "200, false"); } }
/// <summary> /// Возвратить значение smart-свойства. /// </summary> /// <param name="property">smart-свойство.</param> /// <returns>Значение smart-свойства.</returns> /// <exception cref="SmartPropertyException" /> public object GetValue(SmartProperty property) { return(PropertyValues.GetValue(this, property)); }
internal static TAutoHistory AutoHistory <TAutoHistory>(this EntityEntry entry, Func <TAutoHistory> createHistoryFactory) where TAutoHistory : AutoHistory { var history = createHistoryFactory(); history.TableName = entry.Metadata.GetTableName(); // Get the mapped properties for the entity type. // (include shadow properties, not include navigations & references) var properties = entry.Properties; dynamic json = new System.Dynamic.ExpandoObject(); switch (entry.State) { case EntityState.Added: foreach (var prop in properties) { if (prop.Metadata.IsKey() || prop.Metadata.IsForeignKey()) { continue; } ((IDictionary <String, Object>)json)[prop.Metadata.Name] = prop.CurrentValue != null ? prop.CurrentValue : null; } // REVIEW: what's the best way to set the RowId? history.RowId = "0"; history.Kind = EntityState.Added; history.Changed = JsonSerializer.Serialize(json); break; case EntityState.Modified: dynamic bef = new System.Dynamic.ExpandoObject(); dynamic aft = new System.Dynamic.ExpandoObject(); PropertyValues databaseValues = null; foreach (var prop in properties) { if (prop.IsModified) { if (prop.OriginalValue != null) { if (!prop.OriginalValue.Equals(prop.CurrentValue)) { ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = prop.OriginalValue; } else { databaseValues = databaseValues ?? entry.GetDatabaseValues(); var originalValue = databaseValues.GetValue <object>(prop.Metadata.Name); ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = originalValue != null ? originalValue : null; } } else { ((IDictionary <String, Object>)bef)[prop.Metadata.Name] = null; } ((IDictionary <String, Object>)aft)[prop.Metadata.Name] = prop.CurrentValue != null ? prop.CurrentValue : null; } } ((IDictionary <String, Object>)json)["before"] = bef; ((IDictionary <String, Object>)json)["after"] = aft; history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Modified; history.Changed = JsonSerializer.Serialize(json); break; case EntityState.Deleted: foreach (var prop in properties) { ((IDictionary <String, Object>)json)[prop.Metadata.Name] = prop.OriginalValue != null ? prop.OriginalValue : null; } history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Deleted; history.Changed = JsonSerializer.Serialize(json); break; case EntityState.Detached: case EntityState.Unchanged: default: throw new NotSupportedException("AutoHistory only support Deleted and Modified entity."); } return(history); }
internal static TAutoHistory AutoHistory <TAutoHistory>(this EntityEntry entry, Func <TAutoHistory> createHistoryFactory) where TAutoHistory : AutoHistory { var history = createHistoryFactory(); history.TableName = entry.Metadata.GetTableName(); // Get the mapped properties for the entity type. // (include shadow properties, not include navigations & references) var properties = entry.Properties; var formatting = AutoHistoryOptions.Instance.JsonSerializerSettings.Formatting; var jsonSerializer = AutoHistoryOptions.Instance.JsonSerializer; var json = new JObject(); switch (entry.State) { case EntityState.Added: foreach (var prop in properties) { if (prop.Metadata.IsKey() || prop.Metadata.IsForeignKey()) { continue; } json[prop.Metadata.Name] = prop.CurrentValue != null ? JToken.FromObject(prop.CurrentValue, jsonSerializer) : JValue.CreateNull(); } // REVIEW: what's the best way to set the RowId? history.RowId = "0"; history.Kind = EntityState.Added; history.Changed = json.ToString(formatting); break; case EntityState.Modified: var bef = new JObject(); var aft = new JObject(); PropertyValues databaseValues = null; foreach (var prop in properties) { if (prop.IsModified) { if (prop.OriginalValue != null) { if (!prop.OriginalValue.Equals(prop.CurrentValue)) { bef[prop.Metadata.Name] = JToken.FromObject(prop.OriginalValue, jsonSerializer); } else { databaseValues = databaseValues ?? entry.GetDatabaseValues(); var originalValue = databaseValues.GetValue <object>(prop.Metadata.Name); bef[prop.Metadata.Name] = originalValue != null ? JToken.FromObject(originalValue, jsonSerializer) : JValue.CreateNull(); } } else { bef[prop.Metadata.Name] = JValue.CreateNull(); } aft[prop.Metadata.Name] = prop.CurrentValue != null ? JToken.FromObject(prop.CurrentValue, jsonSerializer) : JValue.CreateNull(); } } json["before"] = bef; json["after"] = aft; history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Modified; history.Changed = json.ToString(formatting); break; case EntityState.Deleted: foreach (var prop in properties) { json[prop.Metadata.Name] = prop.OriginalValue != null ? JToken.FromObject(prop.OriginalValue, jsonSerializer) : JValue.CreateNull(); } history.RowId = entry.PrimaryKey(); history.Kind = EntityState.Deleted; history.Changed = json.ToString(formatting); break; case EntityState.Detached: case EntityState.Unchanged: default: throw new NotSupportedException("AutoHistory only support Deleted and Modified entity."); } return(history); }