private string GetDescription(OperationType enumerationValue)
        {
            Type type = enumerationValue.GetType();

            if (!type.IsEnum)
            {
                throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
            }

            //Tries to find a DescriptionAttribute for a potential friendly name
            //for the enum
            MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
            if (memberInfo != null && memberInfo.Length > 0)
            {
                object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    //Pull out the description value
                    return(((DescriptionAttribute)attrs[0]).Description);
                }
            }
            //If we have no description attribute, just return the ToString of the enum
            return(enumerationValue.ToString());
        }
예제 #2
0
 /// <summary>
 /// 产生实体SQL 语句缓存需要的键值。
 /// </summary>
 /// <param name="entityType"></param>
 /// <param name="operationType"></param>
 /// <param name="properties"></param>
 /// <returns></returns>
 public string GenerateCacheKey(Type entityType, OperationType operationType, string[] properties)
 {
     if (properties == null || properties.Length == 0)
     {
         return(string.Format("{0}_{1}", entityType.FullName, operationType.ToString()));
     }
     else
     {
         return(string.Format("{0}_{1}_{2}", entityType.FullName, operationType.ToString(), string.Join("-", properties)));
     }
 }
예제 #3
0
 /// <summary>
 /// Logs the duration of the operation.
 /// </summary>
 /// <param name="val">The value.</param>
 /// <param name="operationType">Type of the operation.</param>
 public static void LogOperationDuration(long val, OperationType operationType)
 {
     if (mdmEnabled)
     {
         operationDurationMetrics.LogValue(val, operationType.ToString());
     }
 }
예제 #4
0
 public Operation(OperationType operationType, int operationValue, int taxPayed)
 {
     this.operationType  = operationType.ToString();
     this.operationValue = operationValue;
     this.taxPayed       = taxPayed;
     operationDate       = DateTime.Now.ToString();
 }
예제 #5
0
 /// <summary>
 /// Logs the bytes processed.
 /// </summary>
 /// <param name="val">The value.</param>
 /// <param name="operationType">Type of the operation.</param>
 public static void LogBytesProcessed(long val, OperationType operationType)
 {
     if (mdmEnabled)
     {
         bytesProcessedMetrics.LogValue(val, operationType.ToString());
     }
 }
        public CodeMemberMethod CreateApiFunction(Settings settings, string relativePath, OperationType httpMethod,
                                                  OpenApiOperation apiOperation, ComponentsToCsTypes coms2CsTypes, bool forAsync, bool useEnsureSuccessStatusCodeEx)
        {
            if (!(new OperationType[] { OperationType.Get, OperationType.Post, OperationType.Put, OperationType.Delete, OperationType.Patch }).Any(d => d == httpMethod))
            {
                Trace.TraceWarning("This HTTP method {0} is not yet supported", httpMethod);
                return(null);
            }

            this.settings     = settings;
            this.nameComposer = new NameComposer(settings);
            this.apiOperation = apiOperation;
            statementOfEnsureSuccessStatusCode = useEnsureSuccessStatusCodeEx ? "EnsureSuccessStatusCodeEx" : "EnsureSuccessStatusCode";

            this.actionName   = nameComposer.GetActionName(apiOperation, httpMethod.ToString(), relativePath);
            this.coms2CsTypes = coms2CsTypes;
            this.forAsync     = forAsync;


            this.RelativePath = RemovePrefixSlash(relativePath);
            this.RelativePath = RegexFunctions.RefineUrlWithHyphenInParameters(RelativePath);

            if (actionName.EndsWith("Async"))
            {
                actionName = actionName[0..^ 5];
예제 #7
0
        private void BuildNotify(IOperationData operationData, DynamicObject proxy, InMemoryUser curUser)
        {
            Type          type            = proxy.ProxyType;
            MethodInfo    mi              = type.GetMethod(_MethodName);
            ParameterInfo pi              = mi.GetParameters().First();
            object        notifyInterface = r.InstanceFromType(pi.ParameterType);
            var           header          = r.InstantiateProperty(notifyInterface, "Header");

            r.InstantiateProperty(header, "SenderID", new { Value = SwConstants.ExternalSystemName });
            r.SetProperty(notifyInterface, "Header", header);
            var    rootIntegrationObject = r.InstantiateArrayReturningSingleElement(notifyInterface, "Content");
            object integrationObject     = r.InstantiateProperty(rootIntegrationObject, 0);

            r.SetProperty(integrationObject, "actionSpecified", true);
            r.InstantiateProperty(integrationObject, "CHANGEDATE", new { Value = DateTime.Now.FromServerToRightKind() });
            //TODO: get current user, in the mobile case below code may be wrong
            WsUtil.SetValue(integrationObject, "ORGID", curUser.OrgId);
            WsUtil.SetValue(integrationObject, "SITEID", curUser.SiteId);
            r.InstantiateProperty(integrationObject, "CHANGEBY", new { Value = curUser.Login });
            OperationType  operationType = operationData.OperationType;
            EntityMetadata metadata      = operationData.EntityMetadata;

            r.SetProperty(integrationObject, "action", operationType.ToString());
            Proxy               = proxy;
            IntegrationObject   = integrationObject;
            RootInterfaceObject = notifyInterface;
        }
예제 #8
0
        public void Validate(
            HttpRequestMessage request,
            OpenApiDocument openApiDocument,
            string pathTemplate,
            OperationType operationType)
        {
            var operationSpec  = openApiDocument.GetOperationByPathAndType(pathTemplate, operationType, out OpenApiPathItem pathSpec);
            var parameterSpecs = ExpandParameterSpecs(pathSpec, operationSpec, openApiDocument);

            // Convert to absolute Uri as a workaround to limitation with Uri class - i.e. most of it's methods are not supported for relative Uri's.
            var requestUri = new Uri(new Uri("http://tempuri.org"), request.RequestUri);

            if (!TryParsePathNameValues(pathTemplate, requestUri.AbsolutePath, out NameValueCollection pathNameValues))
            {
                throw new RequestDoesNotMatchSpecException($"Request URI '{requestUri.AbsolutePath}' does not match specified template '{pathTemplate}'");
            }

            if (request.Method != new HttpMethod(operationType.ToString()))
            {
                throw new RequestDoesNotMatchSpecException($"Request method '{request.Method}' does not match specified operation type '{operationType}'");
            }

            ValidateParameters(parameterSpecs.Where(p => p.In == ParameterLocation.Path), openApiDocument, pathNameValues);
            ValidateParameters(parameterSpecs.Where(p => p.In == ParameterLocation.Query), openApiDocument, HttpUtility.ParseQueryString(requestUri.Query));
            ValidateParameters(parameterSpecs.Where(p => p.In == ParameterLocation.Header), openApiDocument, request.Headers.ToNameValueCollection());

            if (operationSpec.RequestBody != null)
            {
                ValidateContent(operationSpec.RequestBody, openApiDocument, request.Content);
            }
        }
예제 #9
0
        public static void SaveFuzzySetsToFile(
            List <Quantifier> quants,
            List <Qualifier> quals,
            List <Summarizator> summs,
            OperationType op,
            string dest)
        {
            using (var fs = new StreamWriter(dest))
            {
                fs.WriteLine("QUANTIFIERS");
                foreach (var quan in quants)
                {
                    fs.WriteLine($"{quan.Description}:{(quan.IsAbsolute ? "abs" : "rel")}:{GetMembershipString(quan.MembershipFunction)}");
                }
                fs.WriteLine();


                fs.WriteLine("QUALIFIERS");
                foreach (var qual in quals)
                {
                    fs.WriteLine($"{qual.Description}:{qual.AttributeName}:{GetMembershipString(qual.MembershipFunction)}");
                }
                fs.WriteLine();

                fs.WriteLine($"SUMMARIZERS {op.ToString()}");
                foreach (var summ in summs)
                {
                    fs.WriteLine($"{summ.Description}:{summ.AttributeName}:{GetMembershipString(summ.MembershipFunction)}");
                }
                fs.WriteLine();
            }
        }
예제 #10
0
        private string PrintOperationType(OperationType operationType, NamedType namedType)
        {
            var operation = operationType.ToString().ToLower();
            var type      = PrintNamedType(namedType);

            return($"{operation}: {type}");
        }
예제 #11
0
        //根据操作类型获取对应的名称。
        private string getSqlName(OperationType operationType)
        {
            switch (operationType)
            {
            case OperationType.Select:
                return(MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_SELECT_OBJECT);

            case OperationType.SelectByKey:
                return(MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_SELECT_BY_KEY);

            case OperationType.Insert:
                return(MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_ADD_OBJECT);

            case OperationType.Update:
                return(MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_UPDATE_OBJECT);

            case OperationType.Delete:
                return(MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_DELETE_OBJECT);

            case OperationType.DeleteNotIn:
                return(MB.Orm.Mapping.Xml.XmlSqlMappingInfo.SQL_DELETE_NOT_IN_IDS);

            default:
                throw new MB.Util.APPException("操作类型:" + operationType.ToString() + " 还没有配置相应SQL 操作名称!");
            }
        }
예제 #12
0
        private void CheckAuth(
            INode node,
            IProvideMetadata type,
            IProvideClaimsPrincipal userContext,
            ValidationContext context,
            OperationType operationType)
        {
            if (type == null || !type.RequiresAuthorization())
            {
                return;
            }

            var result = type
                         .Authorize(userContext?.User, context.UserContext, context.Inputs, _evaluator)
                         .GetAwaiter()
                         .GetResult();

            if (result.Succeeded)
            {
                return;
            }

            var errors = string.Join("\n", result.Errors);

            context.ReportError(new ValidationError(
                                    context.OriginalQuery,
                                    "authorization",
                                    $"You are not authorized to run this {operationType.ToString().ToLower()}.\n{errors}",
                                    node));
        }
예제 #13
0
        /// <summary>
        /// 获取配置的SQL 字符窜信息。
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="OperationType"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public virtual SqlString[] GenerateSql(Type entityType, OperationType operationType, string[] properties)
        {
            string cacheKey = this.GenerateCacheKey(entityType, operationType, properties);

            if (CacheProxy.ContainsSql(cacheKey))
            {
                return(CacheProxy.GetCachedSql(cacheKey));
            }

            SqlString[] ss = null;
            switch (operationType)
            {
            case (OperationType.Insert):
                ss = GenerateInsertSql(entityType, properties);
                break;

            case (OperationType.Delete):
                ss = GenerateDeleteSql(entityType);
                break;

            case (OperationType.Update):
                ss = GenerateUpdateSql(entityType, properties);
                break;

            case OperationType.Select:
                ss = GenerateSimpleSelectSql(entityType, properties);
                break;

            default:
                throw new MB.Util.APPException("在自动根据配置信息获取对象的操作SQL 语句时,操作类型:" + operationType.ToString() + " 还没有进行定义!");
            }
            return(ss);
        }
예제 #14
0
 public QueryPart(OperationType operation, Type entityType, string id)
 {
     OperationType = operation;
     ID = id ?? operation.ToString();
     EntityType = entityType;
     _parts = new Lazy<List<IQueryPart>>(() => new List<IQueryPart>());
 }
예제 #15
0
 /// <summary>
 /// Logs the watcher count processed.
 /// </summary>
 /// <param name="val">The value.</param>
 /// <param name="operationType">Type of the operation.</param>
 public static void LogWatcherCountProcessed(long val, OperationType operationType)
 {
     if (mdmEnabled)
     {
         watcherCountMatrics.LogValue(val, operationType.ToString());
     }
 }
예제 #16
0
        /// <summary>
        /// Creates or populates Revit element params based on the information contained in this class.
        /// </summary>
        /// <param name="doc">The document.</param>
        /// <param name="element">The element.</param>
        protected override void CreateParametersInternal(Document doc, Element element)
        {
            base.CreateParametersInternal(doc, element);

            if (element != null)
            {
                Category category = IFCPropertySet.GetCategoryForParameterIfValid(element, Id);
                if (category != null)
                {
                    Parameter operationTypeParameter = element.get_Parameter(BuiltInParameter.DOOR_OPERATION_TYPE);
                    if (operationTypeParameter != null)
                    {
                        operationTypeParameter.Set(OperationType.ToString());
                    }
                    IFCPropertySet.AddParameterString(doc, element, category, "IfcOperationType", OperationType.ToString(), Id);

                    Parameter constructionTypeParameter = element.get_Parameter(BuiltInParameter.DOOR_CONSTRUCTION_TYPE);
                    if (constructionTypeParameter != null)
                    {
                        constructionTypeParameter.Set(ConstructionType.ToString());
                    }
                    IFCPropertySet.AddParameterString(doc, element, category, "IfcConstructionType", ConstructionType.ToString(), Id);
                }
            }
        }
        private async Task <ProviderPermissions> GetProviderPermissionsAsync(long ukprn, OperationType operation)
        {
            using (var httpClient = CreateHttpClient(_configuration))
            {
                var queryData = new { Ukprn = ukprn, Operation = operation.ToString() };
                var uri       = new Uri(AddQueryString("accountproviderlegalentities", queryData), UriKind.RelativeOrAbsolute);

                try
                {
                    var response = await httpClient.GetAsync(uri);

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();

                        var providerPermissions = JsonConvert.DeserializeObject <ProviderPermissions>(content);
                        return(providerPermissions);
                    }

                    _logger.LogError($"An invalid response received when trying to get provider relationships. Status:{response.StatusCode} Reason:{response.ReasonPhrase}");
                }
                catch (HttpRequestException ex)
                {
                    _logger.LogError(ex, "Error trying to retrieve legal entities.", null);
                }
                catch (JsonReaderException ex)
                {
                    _logger.LogError(ex, $"Couldn't deserialise {nameof(ProviderPermissions)}.", null);
                }

                return(new ProviderPermissions {
                    AccountProviderLegalEntities = Enumerable.Empty <LegalEntityDto>()
                });
            }
        }
예제 #18
0
    public void Update()
    {
        this.name = operationType.ToString();

        if (!string.IsNullOrEmpty(customName))
        {
            this.name += "-" + customName;
        }
    }
예제 #19
0
파일: WaitForm.cs 프로젝트: mkoscak/koberce
        public WaitForm(DBProvider db, OperationType opType)
        {
            this.OpType = opType;
            this.db = db;

            InitializeComponent();

            this.Text += " "+opType.ToString();
        }
예제 #20
0
 public PageException(OperationType operationType, WorldPart worldPart, GameVersion version) : base
     (
         "Отсутствуют URL адрес удовлетворяющий условию поиска. \n" +
         $"Операция: {operationType.ToString()}\n" +
         $"Расположение сервера: {worldPart.ToString()}\n" +
         $"Версия игры: {version}\n", ExceptionType.Constant
     )
 {
 }
예제 #21
0
        private async Task AuthorizeAsync(
            INode node,
            IProvideMetadata type,
            IProvideClaimsPrincipal userContext,
            ValidationContext context,
            OperationType operationType)
        {
            if (type == null || !type.RequiresAuthorization())
            {
                return;
            }

            if (userContext == null)
            {
                throw new ArgumentNullException(
                          nameof(userContext),
                          $"You must register a user context that implements {nameof(IProvideClaimsPrincipal)}.");
            }

            var policyNames = type.GetPolicies();

            if (policyNames.Count == 0)
            {
                return;
            }

            var tasks = new List <Task <AuthorizationResult> >(policyNames.Count);

            foreach (var policyName in policyNames)
            {
                var task = _authorizationService.AuthorizeAsync(userContext?.User, policyName);
                tasks.Add(task);
            }
            await Task.WhenAll(tasks);

            foreach (var task in tasks)
            {
                var result = task.Result;
                if (!result.Succeeded)
                {
                    var stringBuilder = new StringBuilder("You are not authorized to run this ");
                    stringBuilder.Append(operationType.ToString().ToLower());
                    stringBuilder.AppendLine(".");

                    if (_options.IncludeErrorDetails)
                    {
                        foreach (var failure in result.Failure.FailedRequirements)
                        {
                            AppendFailureLine(stringBuilder, failure);
                        }
                    }

                    context.ReportError(
                        new ValidationError(context.OriginalQuery, "authorization", stringBuilder.ToString(), node));
                }
            }
        }
예제 #22
0
 public override string ToString()
 {
     toStringBuilder.Length = 0;
     toStringBuilder.Append("id:");
     toStringBuilder.Append(id.ToString());
     toStringBuilder.Append(" oper:");
     toStringBuilder.Append(type.ToString());
     return(toStringBuilder.ToString());
 }
        public async Task <Operation> CreateOperationAsync(byte[] video, OperationType operationType)
        {
            var url      = string.Format("{0}/{1}", ServiceHost, operationType.ToString().ToLowerInvariant());
            var response = await SendRequestAsync(HttpMethod.Post, url, video);

            Operation operation = new Operation(response.Headers.GetValues(OperationLocation).First());

            return(operation);
        }
예제 #24
0
 public DynamicJsonValue ToJson()
 {
     return(new DynamicJsonValue
     {
         ["Description"] = Description,
         ["TaskType"] = TaskType.ToString(),
         ["StartTime"] = StartTime,
         ["EndTime"] = EndTime
     });
 }
예제 #25
0
        /// <inheritdoc/>
        protected override void Initialize(ODataContext context, ODataPath path)
        {
            base.Initialize(context, path);

            ODataOperationImportSegment operationImportSegment = path.LastSegment as ODataOperationImportSegment;

            EdmOperationImport = operationImportSegment.OperationImport;

            Request = Context.FindRequest(EdmOperationImport, OperationType.ToString());
        }
예제 #26
0
 public void LogOperation(OperationType operationType, string message)
 {
     lock (_lock)
     {
         Console.ForegroundColor = ConsoleColor.Yellow;
         Console.Write(operationType.ToString() + ":\t");
         Console.ResetColor();
         Console.WriteLine(message);
     }
 }
        private FormSectionOperation(OperationType operation, Type sectionType)
        {
            if (!typeof(ISectionModel).IsAssignableFrom(sectionType))
            {
                throw new ArgumentException("Illegal type.", nameof(sectionType));
            }

            Operation   = operation;
            SectionType = sectionType;
            Name        = $"{operation.ToString()} {sectionType}";
        }
예제 #28
0
 public DynamicJsonValue ToJson()
 {
     return(new DynamicJsonValue
     {
         [nameof(Description)] = Description,
         [nameof(TaskType)] = TaskType.ToString(),
         [nameof(StartTime)] = StartTime,
         [nameof(EndTime)] = EndTime,
         [nameof(DetailedDescription)] = DetailedDescription?.ToJson()
     });
 }
예제 #29
0
        /// <inheritdoc/>
        protected override void Initialize(ODataContext context, ODataPath path)
        {
            base.Initialize(context, path);

            // get the entity set.
            ODataNavigationSourceSegment navigationSourceSegment = path.FirstSegment as ODataNavigationSourceSegment;

            EntitySet = navigationSourceSegment.NavigationSource as IEdmEntitySet;

            Request = Context.FindRequest(EntitySet, OperationType.ToString());
        }
예제 #30
0
        /// <inheritdoc/>
        protected override void Initialize(ODataContext context, ODataPath path)
        {
            // Base Initialize should be called at top of this method.
            base.Initialize(context, path);

            ODataNavigationSourceSegment navigationSourceSegment = path.FirstSegment as ODataNavigationSourceSegment;

            Singleton = navigationSourceSegment.NavigationSource as IEdmSingleton;

            Request = context.FindRequest(Singleton, OperationType.ToString());
        }
        public static Activity StartExecuteActivity(OperationType operationType, int entitiesCount)
        {
            var activity = ActivitySource.StartActivity("EFCore.BulkExtensions.BulkExecute");

            if (activity != null)
            {
                activity.AddTag("operationType", operationType.ToString("G"));
                activity.AddTag("entitiesCount", entitiesCount.ToString(CultureInfo.InvariantCulture));
            }

            return(activity);
        }
예제 #32
0
        internal EmailStatus SendEmail(Move move, OperationType operationType, Security security)
        {
            var user   = GetUser(move);
            var config = user.Config;

            if (!config.SendMoveEmail)
            {
                return(EmailStatus.EmailDisabled);
            }

            var operation = PlainText.Site["general", config.Language, operationType.ToString()];

            var accountInName  = move.In?.Name ?? "---";
            var accountOutName = move.Out?.Name ?? "---";
            var categoryName   = move.Category?.Name ?? "---";

            var nature = PlainText.Site["general", config.Language, move.Nature.ToString()];

            var format = Format.MoveNotification(user);

            var dic = new Dictionary <String, String>
            {
                { "Url", getUrl() },
                { "Operation", operation },
                { "AccountIn", accountInName },
                { "AccountOut", accountOutName },
                { "Date", move.GetDate().ToShortDateString() },
                { "Nature", nature },
                { "Category", categoryName },
                { "Description", move.Description },
                { "Value", move.Value.ToMoney(config.Language) },
                { "Details", detailsHTML(move) },
                { "UnsubscribePath", security.Action.ToString() },
                { "UnsubscribeToken", security.Token },
            };

            var fileContent = format.Layout.Format(dic);

            var sender = new Sender()
                         .To(user.Email)
                         .Subject(format.Subject)
                         .Body(fileContent);

            try
            {
                sender.Send();
                return(EmailStatus.EmailSent);
            }
            catch (MailError e)
            {
                return(e.Type);
            }
        }
예제 #33
0
 public QueryPart(OperationType operation, Type entityType)
     : this(operation, entityType, operation.ToString())
 {
 }
 public async Task<Operation> CreateOperationAsync(string videoUrl, OperationType operationType)
 {
     var url = string.Format("{0}/{1}", ServiceHost, operationType.ToString().ToLowerInvariant());
     var response = await SendRequestAsync(HttpMethod.Post, url, new VideoUrlRequest() { Url = videoUrl });
     Operation operation = new Operation(response.Headers.GetValues(OperationLocation).First());
     return operation;
 }
예제 #35
0
 /// <summary>
 ///     Writes the specified log data.
 /// </summary>
 /// <param name="logData">The log data.</param>
 /// <param name="operationType">Type of the operation.</param>
 /// <param name="customOperationName">Name of the custom operation.</param>
 public void Write(object logData, OperationType operationType, string customOperationName = null)
 {
     EnsureNotDisposed();
     if (operationType == OperationType.Custom)
     {
         Guard.ArgumentNotNullOrEmpty(customOperationName, "customOperationName");
     }
     var operation = customOperationName;
     if (operationType != OperationType.Custom)
     {
         operation = operationType.ToString();
     }
     var item = new AuditLogEntryItem(operation, Guid.NewGuid().ToString(), 1)
     {
         LogData = logData
     };
     logEntry.Items.Add(item);
 }
예제 #36
0
        internal Connection GetConnectionString(string moduleName, string logicDbName, string tableName, OperationType action)
        {
            if (!_ModuleList.ContainsKey(moduleName))
            {
                throw new Exceptions.DbException("模块 " + moduleName + " 不存在,请检查配置文件!");
            }
            Module module = _ModuleList[moduleName];

            if (!module.LogicDbList.ContainsKey(logicDbName))
            {
                throw new Exceptions.DbException("逻辑数据库 " + logicDbName + " 不存在,请检查配置文件!");
            }
            LogicDb logicDb = module.LogicDbList[logicDbName];

            // 获取字典中名称为tableName+action的节点
            if (logicDb.TableList.ContainsKey(tableName + "__" + action.ToString()))
            {
                return logicDb.TableList[tableName + "__" + action.ToString()].Connection;
            }
            else
            {
                if (logicDb.TableList.ContainsKey(tableName))
                {
                    // 如果没有指定操作类型的节点,则默认取未设定操作类型的节点
                    return logicDb.TableList[tableName].Connection;
                }
                else
                {
                    return logicDb.DefaultConnection;
                }
            }
        }