示例#1
0
        /// <summary>
        /// 发送单条消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queue">队列名</param>
        /// <param name="routingKey">路由键</param>
        /// <param name="message">消息体</param>
        /// <param name="settings">配置</param>
        public void Send <T>(string queue, T message, string routingKey = "", RabbitMQDeclareSettings settings = null)
        {
            ObjHelper.NotNull(queue, nameof(queue), "queue is null");

            queue = GetQueueName(queue);

            if (routingKey.IsNull())
            {
                routingKey = queue;
            }

            using var channel = _sendConnection.CreateModel();

            settings = GetSettings(settings);
            var exchange = settings.Exchange;

            channel.ExchangeDeclare(exchange.Name, exchange.Type, exchange.Durable, exchange.AutoDelete, exchange.Arguments);
            channel.QueueDeclare(queue, settings.Queue.Durable, settings.Queue.Exclusive, settings.Queue.AutoDelete, settings.Queue.Arguments);
            channel.QueueBind(queue, exchange.Name, routingKey);

            var body       = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
            var properties = channel.CreateBasicProperties();

            properties.Persistent = true;

            channel.BasicPublish(exchange.Name, routingKey, properties, body);
        }
示例#2
0
        public override void Delete(TEntity entity, bool isPhysicalDelete = false)
        {
            try
            {
                TryAttach(entity);

                if (!isPhysicalDelete)
                {
                    entity.DeletedTime = ObjHelper.ReplaceNullOrDefault(entity.LastUpdatedTime, DateTimeOffset.UtcNow);

                    DbContext.Entry(entity).Property(x => x.DeletedTime).IsModified = true;

                    DbContext.Entry(entity).Property(x => x.DeletedBy).IsModified = true;
                }
                else
                {
                    DbSet.Remove(entity);
                }
            }
            catch (Exception)
            {
                RefreshEntity(entity);

                throw;
            }
        }
示例#3
0
        /// <summary>
        /// 创建连接
        /// </summary>
        internal void CreateConnection()
        {
            ObjHelper.NotNull(_config.UserName, nameof(_config.UserName), "用户名不能为空");
            ObjHelper.NotNull(_config.Password, nameof(_config.Password), "密码不能为空");

            if (_config.HostName.IsNull())
            {
                _config.HostName = "localhost";
            }

            if (_config.Port < 1 || _config.Port > 65535)
            {
                _config.Port = 5672;
            }

            var factory = new ConnectionFactory
            {
                HostName = _config.HostName,
                Port     = _config.Port,
                UserName = _config.UserName,
                Password = _config.Password,
                AutomaticRecoveryEnabled = true,
                NetworkRecoveryInterval  = TimeSpan.FromSeconds(10)
            };

            if (_config.VirtualHost.NotNull())
            {
                factory.VirtualHost = _config.VirtualHost;
            }

            _sendConnection = factory.CreateConnection();

            _receiveConnection = factory.CreateConnection();
        }
示例#4
0
        protected HttpResponseMessage CreateHttpResponse(HttpRequestMessage request, Func <HttpResponseMessage> function)
        {
            HttpResponseMessage response = null;

            try
            {
                response = function.Invoke();
            }
            catch (DbUpdateException ex)
            {
                if (ConfigHelper.LogProviderRequests)
                {
                    ObjHelper.LogProviderRequest(ex, "ApiControllerBase");
                }
                LogError(ex);
                response = request.CreateResponse(HttpStatusCode.BadRequest, ConfigurationReader.ErrorMessage);
            }
            catch (Exception ex)
            {
                if (ConfigHelper.LogProviderRequests)
                {
                    ObjHelper.LogProviderRequest(ex, "ApiControllerBase");
                }
                LogError(ex);
                response = request.CreateResponse(HttpStatusCode.InternalServerError, ConfigurationReader.ErrorMessage);
                //throw;
            }
            return(response);
        }
        public static void DelegateMethod(string name, FunctionArgs args)
        {
            string indicatorName;

            Screen2.Entity.Indicator ind;
            int offset;

            switch (name.ToLower())
            {
            case "iv":
            case "ivalue":
                indicatorName = args.Parameters[0].ParsedExpression.ToString();
                ind           = ExpressionManager.Indicators[ExpressionManager.CurrentIndex];

                args.Result = ObjHelper.GetPropValue(ind, CalcHelper.PropName(indicatorName));
                break;

            case "ivd":
            case "ivalue_d":
                indicatorName = args.Parameters[0].ParsedExpression.ToString();
                offset        = int.Parse(args.Parameters[1].Evaluate().ToString());
                ind           = ExpressionManager.Indicators[ExpressionManager.CurrentIndex + offset];

                args.Result = ObjHelper.GetPropValue(ind, CalcHelper.PropName(indicatorName));
                break;
                //default:
                //    throw new ArgumentException(string.Format("custom function {0} is not defined", name));
            }
        }
示例#6
0
 public override T Add(T entity)
 {
     entity.DeletedTime     = null;
     entity.LastUpdatedTime = entity.CreatedTime = ObjHelper.ReplaceNullOrDefault(entity.CreatedTime, DateTimeOffset.UtcNow);
     entity = DbSet.Add(entity).Entity;
     return(entity);
 }
示例#7
0
        public override void Update(T entity)
        {
            TryAttach(entity);

            entity.LastUpdatedTime = ObjHelper.ReplaceNullOrDefault(entity.LastUpdatedTime, DateTimeOffset.UtcNow);

            DbContext.Entry(entity).State = EntityState.Modified;
        }
示例#8
0
        /// <summary>
        /// 初始化文件信息
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="size">大小</param>
        public FileInfo(string name, long size = 0L)
        {
            ObjHelper.NotNull(name, nameof(name), "文件名称不能为空");

            FileName = name;
            Size     = new FileSize(size);
            Ext      = System.IO.Path.GetExtension(FileName)?.TrimStart('.');
        }
示例#9
0
        private static IContainer RegisterServices(ContainerBuilder containerBuilder, Assembly executingAssembly)
        {
            try
            {
                containerBuilder.RegisterApiControllers(executingAssembly);

                containerBuilder.RegisterType <HeatChartContext>()
                .As <DbContext>()
                .InstancePerRequest();

                containerBuilder.RegisterType <DBFactory>()
                .As <IDBFactory>()
                .InstancePerRequest();

                containerBuilder.RegisterType <EFUnitOfWork>()
                .As <IEFUnitOfWork>()
                .InstancePerRequest();

                containerBuilder.RegisterType <EFUnitOfWork>()
                .As <IUnitOfWork>()
                .InstancePerRequest();

                containerBuilder.RegisterGeneric(typeof(EFRepository <>))
                .As(typeof(IEFRepository <>))
                .InstancePerRequest();

                containerBuilder.RegisterType <DataRepositoryFactory>()
                .As <IDataRepositoryFactory>()
                .InstancePerRequest();

                containerBuilder.RegisterType <MembershipService>()
                .As <IMembershipService>()
                .InstancePerRequest();

                containerBuilder.RegisterType <EncryptionService>()
                .As <IEncryptionService>()
                .InstancePerRequest();

                container = containerBuilder.Build();


                return(container);
            }
            catch (Exception ex)
            {
                if (ConfigHelper.LogProviderRequests)
                {
                    ObjHelper.LogProviderRequest(ex, "UnityResolver");
                }

                return(null);
            }
        }
示例#10
0
        public void Test_UpdateOrder()
        {
            TradeOrderBLL bll = new TradeOrderBLL(_unit);

            var        order = bll.GetByID(58);
            TradeOrder to    = new TradeOrder();

            to      = ObjHelper.DeepCopy(order);
            to.Id   = order.Id;
            to.Size = 1000;

            bll.UpdateOrder(to);
        }
        public async Task <IHttpActionResult> AddShareToWatchBatch(int watchID, [FromBody] int[] inlist)
        {
            string shareList = "";

            shareList = ObjHelper.GetStringFromInts(inlist, ",");

            try
            {
                var currentUser = await base.GetCurrentUser();

                (new WatchListBLL(_unit)).AddShareToWatchList(watchID, currentUser.Id, shareList);
            }
            catch (Exception ex)
            {
                LogHelper.Error(_log, ex.ToString());
                return(InternalServerError(ex));
            }
            return(Ok());
        }
        // Use this for initialization
        void Start()
        {
            mainCamera = Camera.main;

            mainCamera.nearClipPlane = 0.01f;

            if (target == null)
            {
                target = ObjHelper.GetChild(transform, "camera_slot");
                SetDefaultCamPos();
            }

            //mainCamera.transform.parent = transform;
            mainCamera.transform.parent = target;

            IsFirstPerson          = false;
            originalCameraRotation = mainCamera.transform.localRotation;
            originalPlayerRotation = transform.localRotation;
        }
示例#13
0
        public static T GetKey <T>(this HttpContext httpContext, string keyName)
        {
            httpContext.Request.Headers.TryGetValue(keyName, out var keyInHeader);

            string keyStrData = keyInHeader;

            if (string.IsNullOrWhiteSpace(keyStrData))
            {
                keyStrData = httpContext.Request.Cookies[keyName];
            }

            if (string.IsNullOrWhiteSpace(keyInHeader))
            {
                keyStrData = httpContext.Request.Query[keyName];
            }

            ObjHelper.TryConvertTo(keyStrData, default(T), out var keyData);

            return(keyData);
        }
        private void LogError(Exception ex)
        {
            try
            {
                if (ConfigHelper.LogProviderRequests)
                {
                    ObjHelper.LogProviderRequest(ex, "ApiControllerBaseExtended");
                }

                Error _error = new Error()
                {
                    Message     = ex.Message,
                    StackTrace  = ex.StackTrace,
                    DateCreated = DateTime.Now
                };

                _errorsRepository.Insert(_error);
                _errorsRepository.Commit();
            }
            catch { }
        }
示例#15
0
        protected virtual void StandardizeEntities()
        {
            var listState = new List <EntityState>
            {
                EntityState.Added,
                EntityState.Modified
            };

            var listEntryAddUpdate =
                DbContext.ChangeTracker.Entries()
                .Where(x => x.Entity is BaseEntity && listState.Contains(x.State))
                .Select(x => x).ToList();

            var dateTimeNow = DateTimeOffset.UtcNow;

            foreach (var entry in listEntryAddUpdate)
            {
                if (!(entry.Entity is BaseEntity entity))
                {
                    continue;
                }

                if (entry.State == EntityState.Added)
                {
                    entity.DeletedTime     = null;
                    entity.LastUpdatedTime = entity.CreatedTime = ObjHelper.ReplaceNullOrDefault(entity.CreatedTime, dateTimeNow);
                }
                else
                {
                    if (entity.DeletedTime != null)
                    {
                        entity.DeletedTime = ObjHelper.ReplaceNullOrDefault(entity.DeletedTime, dateTimeNow);
                    }
                    else
                    {
                        entity.LastUpdatedTime = ObjHelper.ReplaceNullOrDefault(entity.LastUpdatedTime, dateTimeNow);
                    }
                }
            }
        }
示例#16
0
        public override void Update(T entity, params string[] changedProperties)
        {
            TryAttach(entity);

            changedProperties = changedProperties?.Distinct().ToArray();

            entity.LastUpdatedTime = ObjHelper.ReplaceNullOrDefault(entity.LastUpdatedTime, DateTimeOffset.UtcNow);

            if (changedProperties?.Any() == true)
            {
                DbContext.Entry(entity).Property(x => x.LastUpdatedTime).IsModified = true;

                foreach (var property in changedProperties)
                {
                    DbContext.Entry(entity).Property(property).IsModified = true;
                }
            }
            else
            {
                DbContext.Entry(entity).State = EntityState.Modified;
            }
        }
示例#17
0
        /// <summary>
        /// 使用事件接收消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queue">队列名称</param>
        /// <param name="func">回调函数</param>
        /// <param name="settings">定义设置</param>
        public Consumer Receive <T>(string queue, Func <T, bool> func, RabbitMQDeclareSettings settings = null)
        {
            ObjHelper.NotNull(queue, nameof(queue), "queue is null");
            ObjHelper.NotNull(func, nameof(func), "func is null");

            queue = GetQueueName(queue);

            var channel = _receiveConnection.CreateModel();

            channel.BasicQos(0, 1, false);
            settings = GetSettings(settings);
            channel.QueueDeclare(queue, settings.Queue.Durable, settings.Queue.Exclusive, settings.Queue.AutoDelete, settings.Queue.Arguments);

            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += (sender, eventArgs) =>
            {
                var message = JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(eventArgs.Body.ToArray()));
                if (func(message))
                {
                    channel.BasicAck(eventArgs.DeliveryTag, false);
                }
                else
                {
                    channel.BasicNack(eventArgs.DeliveryTag, false, true);
                }
            };

            var tag = channel.BasicConsume(queue, false, consumer);

            return(new Consumer
            {
                Channel = channel,
                Tag = tag
            });
        }
示例#18
0
        protected override void StandardizeEntities()
        {
            var listState = new List <EntityState>
            {
                EntityState.Added,
                EntityState.Modified,
                EntityState.Deleted
            };

            var listEntry = DbContext.ChangeTracker.Entries()
                            .Where(x => x.Entity is BaseEntity && listState.Contains(x.State))
                            .Select(x => x).ToList();

            var dateTimeNow = GoblinDateTimeHelper.SystemTimeNow;

            foreach (var entry in listEntry)
            {
                if (entry.Entity is BaseEntity baseEntity)
                {
                    if (entry.State == EntityState.Added)
                    {
                        baseEntity.DeletedTime = null;

                        baseEntity.LastUpdatedTime = baseEntity.CreatedTime = dateTimeNow;
                    }
                    else
                    {
                        if (baseEntity.DeletedTime != null)
                        {
                            baseEntity.DeletedTime =
                                ObjHelper.ReplaceNullOrDefault(baseEntity.DeletedTime, dateTimeNow);
                        }
                        else
                        {
                            baseEntity.LastUpdatedTime = dateTimeNow;
                        }
                    }
                }

                if (!(entry.Entity is GoblinEntity entity))
                {
                    continue;
                }

                var loggedInUserId = LoggedInUser.Current.Id;

                if (entry.State == EntityState.Added)
                {
                    if (entity.CreatedBy == null || entity.CreatedBy == default(long))
                    {
                        entity.CreatedBy = entity.LastUpdatedBy = loggedInUserId;
                    }
                }
                else
                {
                    if (entity.DeletedTime != null)
                    {
                        if (entity.DeletedBy == null || entity.DeletedBy == default(long))
                        {
                            entity.DeletedBy = loggedInUserId;
                        }
                    }
                    else
                    {
                        if (entity.LastUpdatedBy == null || entity.LastUpdatedBy == default(long))
                        {
                            entity.LastUpdatedBy = loggedInUserId;
                        }
                    }
                }
            }
        }
示例#19
0
 public static string ToJsonString(this object obj)
 {
     return(ObjHelper.ToJsonString(obj));
 }
示例#20
0
 public static T Clone <T>(this T obj)
 {
     return(ObjHelper.Clone(obj));
 }
示例#21
0
 public static T ConvertTo <T>(this object obj)
 {
     return(ObjHelper.ConvertTo <T>(obj));
 }
示例#22
0
 public static T WithoutRefLoop <T>(this T obj)
 {
     return(ObjHelper.WithoutRefLoop(obj));
 }
示例#23
0
 /// <summary>
 ///     Execute a mapping from the source object to the existing destination object There
 ///     must be a mapping between objects before calling this method.
 /// </summary>
 /// <typeparam name="TSource"> Source type </typeparam>
 /// <typeparam name="TDestination"> Destination type </typeparam>
 /// <param name="source">      Source object </param>
 /// <param name="destination"> Destination object </param>
 /// <returns></returns>
 public static TDestination MapTo <TSource, TDestination>(this TSource source, TDestination destination) where TDestination : class, new()
 {
     return(ObjHelper.MapTo(source, destination));
 }
示例#24
0
 /// <summary>
 ///     Converts an object to another using AutoMapper library. Creates a new object of
 ///     <typeparamref name="TDestination" />. There must be a mapping between objects before
 ///     calling this method.
 /// </summary>
 /// <typeparam name="TDestination"> Type of the destination object </typeparam>
 /// <param name="source"> Source object </param>
 public static TDestination MapTo <TDestination>(this object source) where TDestination : class, new()
 {
     return(ObjHelper.MapTo <TDestination>(source));
 }
示例#25
0
        protected override void StandardizeEntities()
        {
            var listState = new List <EntityState>
            {
                EntityState.Added,
                EntityState.Modified
            };

            var listEntryAddUpdate = DbContext.ChangeTracker.Entries()
                                     .Where(x => x.Entity is BaseEntity && listState.Contains(x.State))
                                     .Select(x => x).ToList();

            var dateTimeNow = DateTimeOffset.UtcNow;

            foreach (var entry in listEntryAddUpdate)
            {
                if (entry.Entity is BaseEntity baseEntity)
                {
                    if (entry.State == EntityState.Added)
                    {
                        baseEntity.DeletedTime     = null;
                        baseEntity.LastUpdatedTime = baseEntity.CreatedTime = ObjHelper.ReplaceNullOrDefault(baseEntity.CreatedTime, dateTimeNow);
                    }
                    else
                    {
                        if (baseEntity.DeletedTime != null)
                        {
                            baseEntity.DeletedTime = ObjHelper.ReplaceNullOrDefault(baseEntity.DeletedTime, dateTimeNow);
                        }
                        else
                        {
                            baseEntity.LastUpdatedTime = ObjHelper.ReplaceNullOrDefault(baseEntity.LastUpdatedTime, dateTimeNow);
                        }
                    }
                }

                if (!(entry.Entity is Entity entity))
                {
                    continue;
                }

                // Add more information if Entry is Entity Type

                Guid?loggedInUserId = null;  // TODO implementation to get logged in user id

                if (entry.State == EntityState.Added)
                {
                    entity.LastUpdatedBy = entity.CreatedBy = entity.CreatedBy;
                }
                else
                {
                    if (entity.DeletedTime != null)
                    {
                        entity.DeletedBy = entity.DeletedBy ?? loggedInUserId;
                    }
                    else
                    {
                        entity.LastUpdatedBy = entity.LastUpdatedBy ?? loggedInUserId;
                    }
                }
            }
        }
示例#26
0
 public static T WithoutVirtualProp <T>(this T obj)
 {
     return(ObjHelper.WithoutVirtualProp(obj));
 }