コード例 #1
0
        public Task <ActionResult <string> > Post([FromRoute] string key, [FromBody] string data)
        {
            return(ThrowToAction(() =>
            {
                //Because we have a single combined interface that MIGHt need to create or update, need to lock
                var uid = GetRequesterUid();

                lock (userlocks.GetOrAdd(uid, l => new object()))
                {
                    var existing = GetVariable(key).Result;

                    if (existing == null)
                    {
                        existing = new EntityValue()
                        {
                            key = Keys.VariableKey + key, value = data
                        };
                        existing.entityId = -uid;
                    }
                    else
                    {
                        existing.value = data;
                    }

                    provider.WriteAsync(existing).Wait();

                    return Task.FromResult(existing.value);
                }
            }));
        }
コード例 #2
0
ファイル: EntitySetValue.cs プロジェクト: reductech/Core
        /// <inheritdoc />
        protected override async Task <Result <Entity, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var entityResult = await Entity.Run(stateMonad, cancellationToken);

            if (entityResult.IsFailure)
            {
                return(entityResult);
            }

            var propertyResult = await Property.Run(stateMonad, cancellationToken);

            if (propertyResult.IsFailure)
            {
                return(propertyResult.ConvertFailure <Entity>());
            }

            var valueResult = await Value.Run(stateMonad, cancellationToken)
                              .Bind(x => EntityHelper.TryUnpackObjectAsync(x, cancellationToken));

            if (valueResult.IsFailure)
            {
                return(valueResult.ConvertFailure <Entity>());
            }

            var propertyName = await propertyResult.Value.GetStringAsync();

            var entityValue = EntityValue.CreateFromObject(valueResult.Value);

            var newEntity = entityResult.Value.WithProperty(propertyName, entityValue);

            return(newEntity);
        }
コード例 #3
0
ファイル: EntityProperty.cs プロジェクト: reductech/Core
 /// <summary>
 /// Create a new Entity property
 /// </summary>
 public EntityProperty(string name, EntityValue baseValue, EntityValue?newValue, int order)
 {
     Name      = name;
     BaseValue = baseValue;
     NewValue  = newValue;
     Order     = order;
 }
コード例 #4
0
ファイル: EntityGetValue.cs プロジェクト: reductech/Core
        /// <inheritdoc />
        protected override async Task <Result <T, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var entity = await Entity.Run(stateMonad, cancellationToken);

            if (entity.IsFailure)
            {
                return(entity.ConvertFailure <T>());
            }

            var propertyResult = await Property.Run(stateMonad, cancellationToken)
                                 .Map(x => x.GetStringAsync());

            if (propertyResult.IsFailure)
            {
                return(propertyResult.ConvertFailure <T>());
            }

            var epk = new EntityPropertyKey(propertyResult.Value);

            var entityValue = entity.Value.TryGetValue(epk);

            if (entityValue.HasNoValue)
            {
                return(EntityValue.GetDefaultValue <T>());
            }

            var result = entityValue.Value.TryGetValue <T>()
                         .MapError(x => x.WithLocation(this));

            return(result);
        }
コード例 #5
0
        /// <summary>
        ///     Determine if the entity is just a reference to some entity external to the graph.
        ///     This is achieved by determining if the bulk query result came from the 'id' node, which is the only one with no fields.
        ///     (All non-leaf nodes will have at least requested the 'name' field)
        /// </summary>
        private bool IsReferenceOnly(EntityValue entityValue)
        {
            var  requestNodes = entityValue.Nodes;
            bool isRefNode    = requestNodes.Count( ) == 1 && requestNodes.First( ).Request.Fields.Count == 0;

            return(isRefNode);
        }
コード例 #6
0
        /// <summary>
        /// The entity management update.
        /// </summary>
        /// <param name="entity">
        /// The entity.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        /// <exception cref="Exception">
        /// </exception>
        public static ResultObje Update(T entity)
        {
            var type = typeof(T);

            if (type.Name == "Object")
            {
                type = entity.GetType();
            }

            var result = new ResultObje();

            var pkProperty = type.GetProperties()
                             .Where(p => p.GetCustomAttributes(typeof(PrimaryKeyAttribute), true).Length > 0)
                             .FirstOrDefault();

            try
            {
                var table = (entity).GetType().BaseType.Name == "Object" ? entity.GetType().Name : (entity).GetType().BaseType.Name;

                string selectSql = string.Format("{0} * {1} {2} {3} {4}= @p1", SqlQueryEnum.SELECT, SqlQueryEnum.FROM,
                                                 table, SqlQueryEnum.WHERE, pkProperty.Name);

                var adapter = new SqlDataAdapter(selectSql, DBHelper.Connection());
                adapter.SelectCommand.Parameters.AddWithValue("@p1", pkProperty.GetValue(entity, null));

                var dTable = new System.Data.DataTable();

                adapter.Fill(dTable);

                var row = dTable.Rows[0];

                EntityValue <T> .GetValueRow(entity, dTable, type, ref row);

                var cmdBuilder = new SqlCommandBuilder(adapter);
                adapter.UpdateCommand = cmdBuilder.GetUpdateCommand();
                result.success        = true;
                try
                {
                    adapter.Update(new[] { row });
                }
                catch (Exception ex)
                {
                    result.success = false;
                    result.Mesaj   = ex.Message;
                    throw new Exception(ex.Message);
                }
            }
            catch (Exception ex)
            {
                result.success = false;
                result.Mesaj   = ex.Message;
                throw new Exception("Pk Attribute Olmadığı İçin Kayıt Yapılamaz. HATA KODU: " + ex.Message);
            }

            return(result);
        }
コード例 #7
0
ファイル: Solar.cs プロジェクト: Souper07/Autopilot
        /// <param name="block">Must be an IMyTerminalBlock</param>
        public Solar(IMyCubeBlock block)
        {
            myBlock = block;
            myLogger = new Logger("Solar", block);
            (myBlock as IMyTerminalBlock).CustomNameChanged += Solar_CustomNameChanged;
            myBlock.OnClose += myBlock_OnClose;
            m_termControl_faceSun = new EntityValue<bool>(block, 0, () => s_termControl_faceSun.UpdateVisual());

            Registrar.Add(block, this);
        }
コード例 #8
0
        public void TestGetExpected(
            object o,
            string expectedString,
            Maybe <int> expectedInt,
            Maybe <double> expectedDouble,
            Maybe <bool> expectedBool,
            Maybe <EncodingEnum> expectedEnumeration,
            Maybe <DateTime> expectedDateTime,
            Maybe <Entity> expectedEntity,
            Maybe <IReadOnlyList <string> > expectedList)
        {
            var entityValue = EntityValue.CreateFromObject(o);

            var actualString = entityValue.TryGetValue <string>().Value;

            actualString.Should().Be(expectedString);

            var actualInt = entityValue.TryGetValue <int>().ToMaybe();

            actualInt.Should().Be(expectedInt);

            var actualDouble = entityValue.TryGetValue <double>().ToMaybe();

            actualDouble.Should().Be(expectedDouble);

            var actualBool = entityValue.TryGetValue <bool>().ToMaybe();

            actualBool.Should().Be(expectedBool);

            var actualEnumeration = entityValue.TryGetValue <EncodingEnum>().ToMaybe();

            actualEnumeration.Should().Be(expectedEnumeration);

            var actualDateTime = entityValue.TryGetValue <DateTime>().ToMaybe();

            actualDateTime.Should().Be(expectedDateTime);

            var actualEntity = entityValue.TryGetValue <Entity>().ToMaybe();

            actualEntity.Should().Be(expectedEntity);

            var actualList = entityValue.TryGetValue <Array <StringStream> >().ToMaybe();

            actualList.HasValue.Should().Be(expectedList.HasValue);

            if (actualList.HasValue)
            {
                actualList.Value.GetElementsAsync(CancellationToken.None)
                .Result
                .Value.Select(x => x.GetString())
                .Should()
                .BeEquivalentTo(expectedList.Value);
            }
        }
コード例 #9
0
 public void TestGetDefaultValue()
 {
     EntityValue.GetDefaultValue <Entity>().Should().Equal(Entity.Empty);
     EntityValue.GetDefaultValue <StringStream>().Should().Be(StringStream.Empty);
     EntityValue.GetDefaultValue <string>().Should().Be(string.Empty);
     EntityValue.GetDefaultValue <int>().Should().Be(0);
     EntityValue.GetDefaultValue <double>().Should().Be(0.0);
     EntityValue.GetDefaultValue <bool>().Should().Be(false);
     EntityValue.GetDefaultValue <Array <int> >().Should().Be(Array <int> .Empty);
     EntityValue.GetDefaultValue <Array <double> >().Should().Be(Array <double> .Empty);
 }
コード例 #10
0
        public AutopilotTerminal(IMyCubeBlock block)
        {
            this.m_logger = new Logger("AutopilotTerminal", block);
            this.m_block = block as IMyTerminalBlock;

            byte index = 0;
            this.m_autopilotControl = new EntityValue<bool>(block, index++, Static.autopilotControl.UpdateVisual, Saver.Instance.LoadOldVersion(69) && ((MyShipController)block).ControlThrusters);
            this.m_autopilotCommands = new EntityStringBuilder(block, index++, Static.autopilotCommands.UpdateVisual);

            m_block.AppendingCustomInfo += AppendingCustomInfo;

            Registrar.Add(block, this);
            m_logger.debugLog("Initialized", Logger.severity.INFO);
        }
コード例 #11
0
        public EntityValue GetValue(Enum id, IEnumerable <EntityValue> values)
        {
            var value = values.FirstOrDefault(x => x.key == keys[id]);

            if (value == null)
            {
                value = new EntityValue()
                {
                    key = keys[id], value = null
                }
            }
            ;

            return(value);
        }
コード例 #12
0
        public ProgrammableBlock(IMyCubeBlock block)
            : base(block)
        {
            m_logger = new Logger(GetType().Name, block);
            m_progBlock = block as Ingame.IMyProgrammableBlock;
            m_networkClient = new RelayClient(block, HandleMessage);

            byte index = 0;
            m_handleDetectedTerminal_ev = new EntityValue<bool>(block, index++, UpdateVisual);
            m_blockCountList_ev = new EntityStringBuilder(block, index++, () => {
                UpdateVisual();
                m_blockCountList_btl = new BlockTypeList(m_blockCountList_sb.ToString().LowerRemoveWhitespace().Split(','));
            });

            Registrar.Add(block, this);
        }
コード例 #13
0
        /// <summary>
        /// Daha İyi Bir Şekilde Yazılmalı
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dbTablo"></param>
        /// <returns></returns>
        public static ResultObje Saves(List <T> entity, object dbTablo = null)
        {
            var result = new ResultObje();

            try
            {
                using (var connection = DBHelper.Connection())
                {
                    var tblName = entity.FirstOrDefault();
                    if (tblName != null && dbTablo == null)
                    {
                        dbTablo = (tblName).GetType().BaseType.Name == "Object" ? tblName.GetType().Name : (tblName).GetType().BaseType.Name;
                    }

                    foreach (var item in entity)
                    {
                        var param = string.Empty;
                        var value = string.Empty;

                        var paramValues = new List <ParamValue>();

                        var property = PropertiesTransactions <T> .DefaulRemoveValueProperty(item, dbTablo);

                        var props = new List <PropertyInfo>(property);

                        EntityValue <T> .GetValue(item, props, ref param, ref value, ref paramValues);

                        connection.Open();

                        result.id = DataProcessingInsert.Insert(dbTablo, param, value, connection, paramValues);

                        connection.Close();
                    }
                    result.success = true;
                }
            }
            catch (Exception ex)
            {
                result.success = false;
                result.Mesaj   = ex.Message;
                throw new Exception(ex.Message);
            }
            return(result);
        }
コード例 #14
0
        private StringBuilder TC_Getter(IMyTerminalBlock block)
        {
            EntityVariables vars;

            if (m_active.TryGetValue(block, out vars))
            {
                Logger.DebugLog("active: " + vars.Text, context: block.nameWithId());
                return(new StringBuilder(vars.Text));
            }
            EntityValue <T> ev = TryGetEntityValue(block, false);

            if (ev != null)
            {
                Logger.DebugLog("stored value: " + ev.Value, context: block.nameWithId());
                return(new StringBuilder(ev.Value.ToString()));
            }
            //Logger.DebugLog("new", context: block.nameWithId());
            return(new StringBuilder());
        }
コード例 #15
0
 public void Add <T>(string field, T value, ValidationReason reason)
 {
     if (typeof(T) == typeof(string) || typeof(T) == typeof(int) || typeof(T) == typeof(bool) ||
         typeof(T) == typeof(long) || typeof(T) == typeof(double) || typeof(T) == typeof(decimal))
     {
         _reason.Add(new Tuple <string, object, ValidationReason>(field, value, reason));
     }
     else
     {
         if (value != null)
         {
             EntityValue = value;
             PropertyInfo info = EntityValue.GetType().GetProperties().SingleOrDefault(o => string.Compare(o.Name, field, true) == 0);
             if (info != null)
             {
                 _reason.Add(new Tuple <string, object, ValidationReason>(field, info.GetValue(EntityValue), reason));
             }
         }
     }
 }
コード例 #16
0
        public static ResultObje Saves(T entity, string dbTablo = null)
        {
            var result = new ResultObje();

            try
            {
                if (string.IsNullOrEmpty(dbTablo))
                {
                    dbTablo = (entity).GetType().BaseType.Name == "Object" ? entity.GetType().Name : (entity).GetType().BaseType.Name;
                }

                using (var connection = DBHelper.Connection())
                {
                    var param = string.Empty;
                    var value = string.Empty;

                    var paramValues = new List <ParamValue>();

                    var property = PropertiesTransactions <T> .DefaulRemoveValueProperty(entity, dbTablo);

                    var props = new List <PropertyInfo>(property);

                    EntityValue <T> .GetValue(entity, props, ref param, ref value, ref paramValues);

                    connection.Open();

                    result.id = DataProcessingInsert.Insert(dbTablo, param, value, connection, paramValues);

                    connection.Close();

                    result.success = true;
                }
            }
            catch (Exception ex)
            {
                result.success = false;
                result.Mesaj   = ex.Message;
                throw new Exception(ex.Message);
            }
            return(result);
        }
コード例 #17
0
        /// <summary>
        /// Convert an object to an entity
        /// </summary>
        public static Entity ConvertToEntity(object obj)
        {
            var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            var props = new List <EntityProperty>();

            var i = 0;

            foreach (var propertyInfo in properties)
            {
                var value = propertyInfo.GetValue(obj);

                if (value is not null)
                {
                    var ev = EntityValue.CreateFromObject(value);
                    var ep = new EntityProperty(propertyInfo.Name, ev, null, i);
                    props.Add(ep);
                }

                i++;
            }

            return(new Entity(props));
        }
コード例 #18
0
 public EntityValue(EntityValue copy) : base(copy)
 {
     entityId = copy.entityId;
     key      = copy.key;
     value    = copy.value;
 }
コード例 #19
0
 static object?GetValue(EntityValue ev) => ev switch
 {
コード例 #20
0
 public static EntityPackage Add(this EntityPackage entity, EntityValue value)
 {
     entity.Values.Add(value);
     return(entity);
 }
コード例 #21
0
ファイル: Projector.cs プロジェクト: Souper07/Autopilot
        public Projector(IMyCubeBlock block)
        {
            this.m_logger = new Logger(GetType().Name, block);
            this.m_block = block;
            this.m_netClient = new RelayClient(block);

            byte index = 0;
            this.m_options = new EntityValue<Option>(block, index++, UpdateVisual);
            this.m_rangeDetection = new EntityValue<float>(block, index++, UpdateVisual, DefaultRangeDetection);
            this.m_radiusHolo = new EntityValue<float>(block, index++, UpdateVisual, DefaultRadiusHolo);
            this.m_sizeDistScale = new EntityValue<float>(block, index++, UpdateVisual, DefaultSizeScale);
            this.m_centreEntityId = new EntityValue<long>(block, index++, m_centreEntityId_AfterValueChanged);
            this.m_offset_ev = new EntityValue<Vector3>(block, index++, UpdateVisual, new Vector3(0f, 2.5f, 0f));

            Registrar.Add(block, this);
        }
コード例 #22
0
        public static AuditLog Create(DbEntityEntry entry, int status, Type entityType = null)
        {
            var entityValue = new EntityValue();
            var type        = entityType ?? entry.Entity.GetType();
            //   var type = Type.GetType(entry.Entity.GetType().FullName + "," + entry.Entity.GetType().Assembly.GetName().Name)?? entry.Entity.GetType().BaseType;

            var ignorClass = type.IsDefined(typeof(IgnoreLogAttribute), false);

            if (ignorClass)
            {
                return(null);
            }
            var    actionType = (ActionType)status;
            object oldObject, newObject;
            string keyValue;
            IEnumerable <ObjectChangeLog> deltaList;

            switch (actionType)
            {
            case ActionType.Create:
            {
                oldObject = Activator.CreateInstance(type);
                newObject = entityValue.NewObject(entry, type);
                deltaList = newObject.ToChangeLog();
                keyValue  = entry.OriginalValues.PropertyNames.Any(s => s == "Id")
                            ? entry.OriginalValues.GetValue <object>("Id").ToString()
                            : "0";
                break;
            }

            case ActionType.Delete:
                oldObject = entityValue.OldObject(entry, type);
                newObject = oldObject;
                deltaList = newObject.Compare(oldObject);
                keyValue  = entry.OriginalValues.PropertyNames.Any(s => s == "Id")
                        ? entry.OriginalValues.GetValue <object>("Id").ToString()
                        : "0";

                break;

            default:
            {
                if (entry.OriginalValues.PropertyNames.Any(s => s == "Active") &&
                    !entry.CurrentValues.GetValue <bool>("Active"))
                {
                    actionType = ActionType.Cancel;
                }
                newObject = entityValue.NewObject(entry, type);
                oldObject = entityValue.OldObject(entry, type);
                deltaList = newObject.Compare(oldObject);
                keyValue  = entry.OriginalValues.PropertyNames.Any(s => s == "Id")
                            ? entry.OriginalValues.GetValue <object>("Id").ToString()
                            : "0";
                break;
            }
            }

            var audit = new AuditLog
            {
                Id             = AppIdentity.AuditId,
                LoginId        = AppIdentity.AppUser.Id,
                ActionType     = actionType,
                EntityName     = type.Name,
                EntityFullName = type.FullName,
                ActionTime     = DateTime.UtcNow.ToLong(),
                KeyFieldId     = keyValue,
                UserId         = AppIdentity.AppUser.UserId,
                BranchId       = AppIdentity.AppUser.ActiveBranchId,
                ActionUrl      = "",
                ActionUser     = AppIdentity.AppUser.Name + "(" + AppIdentity.AppUser.UserName + ")",
                ActionAgent    = AppIdentity.AgentInfo,
                ValueBefore    = JsonConvert.SerializeObject(oldObject),
                ValueAfter     = JsonConvert.SerializeObject(newObject),
                ValueChange    = JsonConvert.SerializeObject(deltaList)
            };

            return(audit);
        }
コード例 #23
0
ファイル: RSValue.cs プロジェクト: BeauPrime/RuleScript
        public string GetPreviewString(RSTriggerInfo inTriggerContext, RSLibrary inLibrary)
        {
            switch (m_Type)
            {
            case InnerType.String:
                return(string.Format("\"{0}\"", m_StringValue));

            case InnerType.Color:
                return(ColorValue.ToString());

            case InnerType.Bool:
                return(BoolValue ? "true" : "false");

            case InnerType.Float:
                return(FloatValue.ToString());

            case InnerType.Int32:
                return(IntValue.ToString());

            case InnerType.Null:
                return("null");

            case InnerType.Vector2:
                return(AsVector2.ToString());

            case InnerType.Vector3:
                return(AsVector3.ToString());

            case InnerType.Vector4:
                return(AsVector4.ToString());

            case InnerType.EntityScope:
                return(EntityValue.GetPreviewString(inTriggerContext, inLibrary));

            case InnerType.GroupId:
                return(GroupIdValue.ToString(inLibrary));

            case InnerType.TriggerId:
                return(TriggerIdValue.ToString(inLibrary));

            case InnerType.Enum:
            {
                Type enumType = Type.GetType(m_StringValue);
                if (enumType == null)
                {
                    Debug.LogErrorFormat("Enum type {0} no longer exists", m_StringValue);
                    return(m_IntValue.ToString());
                }

                try
                {
                    return(Enum.ToObject(enumType, m_IntValue).ToString());
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                    Debug.LogErrorFormat("Enum {0} cannot be represented as type {1}", m_IntValue, enumType);
                    return(m_IntValue.ToString());
                }
            }

            case InnerType.Invalid:
                return("INVALID");

            default:
                ThrowInvalidCastException(m_Type, typeof(string));
                return(null);
            }
        }