コード例 #1
0
ファイル: Grammar.cs プロジェクト: macias/NaiveLanguageTools
        internal Grammar(IEnumerable <Tuple <GrammarElementEnum, object> > elements,
                         IEnumerable <LexItem> implicitLexerRules,
                         List <string> warnings)
        {
            var throw_errors = new List <string>();

            {
                Dictionary <GrammarElementEnum, int> elem_counts = EnumExtensions.GetValues <GrammarElementEnum>().ToDictionary(it => it, it => 0);
                foreach (Tuple <GrammarElementEnum, object> elem in elements)
                {
                    if (elem.Item2 != null)
                    {
                        ++elem_counts[elem.Item1];
                    }
                }

                var optionals = new HashSet <GrammarElementEnum>(new GrammarElementEnum[] {
                    GrammarElementEnum.Types,
                    GrammarElementEnum.Terminals,
                    GrammarElementEnum.Options,
                    GrammarElementEnum.Prededence,
                    GrammarElementEnum.LexerTypeInfo,
                    GrammarElementEnum.ExplicitLexerRules,
                    GrammarElementEnum.LexerStates,
                    GrammarElementEnum.ParserTypeInfo,
                    GrammarElementEnum.ParserRules,
                    GrammarElementEnum.PatternsInfo,
                    GrammarElementEnum.Using
                });

                foreach (KeyValuePair <GrammarElementEnum, int> count in elem_counts.Where(it => it.Value != 1))
                {
                    if (count.Value > 1)
                    {
                        throw ParseControlException.NewAndRun(count.Key.ToString() + " section is duplicated");
                    }
                    // if not optional section
                    else if (!optionals.Contains(count.Key))
                    {
                        throw ParseControlException.NewAndRun(count.Key.ToString() + " section is missing");
                    }
                }


                {
                    // if we have lexer name section, then we have to have lexer rules as well
                    // in reverse -- if we don't have the first, we cannot have the latter one and lexer states section
                    // so it is not symmetric!
                    var lexer_count = elem_counts[GrammarElementEnum.LexerTypeInfo];
                    if (elem_counts[GrammarElementEnum.LexerStates] > lexer_count ||
                        elem_counts[GrammarElementEnum.ExplicitLexerRules] != lexer_count)
                    {
                        throw ParseControlException.NewAndRun("Lexer definition is given only partially: lexer name section "
                                                              + (lexer_count > 0 ? "exists" : "does not exist") + " while lexer states section "
                                                              + (elem_counts[GrammarElementEnum.LexerStates] > 0 ? "exists" : "does not exist") + " and lexer rules section "
                                                              + (elem_counts[GrammarElementEnum.ExplicitLexerRules] > 0 ? "exists" : "does not exist") + ".");
                    }
                }

                if (elem_counts[GrammarElementEnum.ParserRules] != elem_counts[GrammarElementEnum.ParserTypeInfo])
                {
                    throw ParseControlException.NewAndRun("Parser definition is given only partially");
                }
            }

            Dictionary <GrammarElementEnum, object> dict_elements = EnumExtensions.GetValues <GrammarElementEnum>()
                                                                    .ToDictionary(it => it, it => (object)null);

            foreach (Tuple <GrammarElementEnum, object> elem in elements)
            {
                dict_elements[elem.Item1] = elem.Item2;
            }

            this.usingList        = (((IEnumerable <string>)dict_elements[GrammarElementEnum.Using]) ?? new string[] { }).ToList();
            this.types            = (((IEnumerable <SymbolInfo>)dict_elements[GrammarElementEnum.Types]) ?? new SymbolInfo[] { }).ToDictionary(it => it.SymbolName, it => it.TypeName);
            this.guessed_types    = new Dictionary <string, string>();
            this.NamespaceName    = ((string)dict_elements[GrammarElementEnum.Namespace]);
            this.TokenTypeInfo    = ((TokenInfo)dict_elements[GrammarElementEnum.TokenName]);
            this.PatternsTypeInfo = ((PatternsInfo)dict_elements[GrammarElementEnum.PatternsInfo]) ?? new PatternsInfo(null, null);

            this.LexerTypeInfo = ((FactoryTypeInfo)dict_elements[GrammarElementEnum.LexerTypeInfo]);
            this.Options       = ((GrammarOptions)dict_elements[GrammarElementEnum.Options]) ?? new GrammarOptions();
            this.LexerStates   = ((StatesInfo)dict_elements[GrammarElementEnum.LexerStates]) ?? StatesInfo.CreateDefault();
            // implicit rules first, because lexer matches text in longest-first fashion
            // when user explicitly adds something like <anything> rule with reversed concat order
            // implicit rules will never be matched
            this.lexerRules = implicitLexerRules.Concat((((IEnumerable <IScanningRule>)dict_elements[GrammarElementEnum.ExplicitLexerRules]) ?? new LexItem[] { })
                                                        .Select(it => it as LexItem).Where(it => it != null)).ToList();
            {
                IEnumerable <LexPatternVariable> pattern_vars = (((IEnumerable <IScanningRule>)dict_elements[GrammarElementEnum.ExplicitLexerRules]) ?? new LexPatternVariable[] { })
                                                                .Select(it => it as LexPatternVariable).Where(it => it != null).ToArray();
                this.LexerPatternFields = pattern_vars.Where(it => it.WithField).ToArray();
                this.lexerPatternNames  = pattern_vars.ToDictionary(it => it.Name, it => it.Pattern);
            }

            this.lexerRules.ForEach(it => it.OutputPattern = mergeLexPatterns(it.InputPatterns));

            this.ParserTypeInfo    = ((FactoryTypeInfo)dict_elements[GrammarElementEnum.ParserTypeInfo]);
            this.parserPrecedences = (((IEnumerable <Precedence>)dict_elements[GrammarElementEnum.Prededence]) ?? Enumerable.Empty <Precedence>()).ToList();

            this.terminalRegistry = new OrderedSet <string>(
                (new[] { EOFSymbol })
                .Concat((((IEnumerable <string>)dict_elements[GrammarElementEnum.Terminals]) ?? new string[] { }))
                .Concat(
                    lexerRules.Select(lex_it => lex_it.Context.Concat(lex_it.TerminalName)).Flatten()
                    // error symbol can appear in lexer productions, it is not a terminal though
                    .Where(s => s != null && s != Grammar.ErrorSymbol)));

            this.parserProductions = new List <Production>();
            AddProductions(((IEnumerable <Production>)dict_elements[GrammarElementEnum.ParserRules]) ?? new Production[] { });

            this.symbolRegistry = new OrderedSet <string>(
                (new[] { ErrorSymbol })
                .Concat(terminalRegistry) // EOF starts that set
                .Concat(nonTerminalRegistry)
                .Concat(ParserProductions
                        .Select(prod => prod.RhsAlternatives
                                .Select(alt => alt.RhsGroups
                                        .Select(grp => grp.GetSymbols().Select(s => s.SymbolName))
                                        .Flatten())
                                .Flatten())
                        .Flatten()));

            // here we get partial mapping (useful for lexer, which sees only part of all symbols)
            InitSymbolMapping();

            if (!IsParserBuilt)
            {
                var errors = new List <string>();
                if (dict_elements[GrammarElementEnum.Types] != null)
                {
                    errors.Add("types");
                }

                if (dict_elements[GrammarElementEnum.Prededence] != null)
                {
                    errors.Add("precedence");
                }

                if (dict_elements[GrammarElementEnum.ParserRules] != null)
                {
                    errors.Add("parser productions");
                }

                if (errors.Any())
                {
                    throw ParseControlException.NewAndRun("Parser is not built (no parser name is given); " + errors.Join(", ") + " section(s) are meaningless.");
                }
            }

            {
                IEnumerable <string> undef_symbols = new HashSet <string>(types.Select(it => it.Key).Where(it => !symbolRegistry.Contains(it)));

                if (undef_symbols.Any())
                {
                    warnings.Add("Undefined symbol(s) in types section: " + String.Join(", ", undef_symbols));
                }
            }

            if (IsParserBuilt)
            {
                var rhs_symbol_names = new HashSet <string>(ParserProductions.Select(it => it.RhsAlternatives).Flatten()
                                                            .Select(it => it.RhsGroups).Flatten()
                                                            .Select(it => it.GetSymbols()).Flatten()
                                                            .Select(it => it.SymbolName));

                IEnumerable <string> unused_terminals = terminalRegistry.Where(it => it != Grammar.EOFSymbol && !rhs_symbol_names.Contains(it)).ToList();

                if (unused_terminals.Any())
                {
                    warnings.Add("Unused terminal(s) in parsing section: " + String.Join(", ", unused_terminals));
                }
            }

            ParseControlException.ThrowAndRun(throw_errors);
        }
コード例 #2
0
 public void GetDescriptionTest()
 {
     Assert.AreEqual(EnumExtensions.GetDescription(TestDescriptionEnum.First), "The First One");
 }
コード例 #3
0
        public void GetAttributeTestNull2()
        {
            object result = EnumExtensions.GetAttribute <MyAttribute>(ConsoleColor.Black);

            Assert.IsTrue(result == null);
        }
コード例 #4
0
 public IObjectAssemblySpecification GetRegistration <TType>(params Enum[] tokens) where TType : class
 {
     return(GetRegistration <TType>(EnumExtensions.CombinedToken(tokens)));
 }
コード例 #5
0
 /// <summary>
 /// Get all valid <see cref="HitResult"/>s for this ruleset.
 /// Generally used for results display purposes, where it can't be determined if zero-count means the user has not achieved any or the type is not used by this ruleset.
 /// </summary>
 /// <remarks>
 /// <see cref="HitResult.Miss"/> is implicitly included. Special types like <see cref="HitResult.IgnoreHit"/> are ignored even when specified.
 /// </remarks>
 protected virtual IEnumerable <HitResult> GetValidHitResults() => EnumExtensions.GetValuesInOrder <HitResult>();
コード例 #6
0
 public IObjectAssemblySpecification RegisterInstance <TType>(TType instance, params Enum[] tokens)
     where TType : class
 {
     return(RegisterInstance(EnumExtensions.CombinedToken(tokens), instance));
 }
コード例 #7
0
 public IObjectAssemblySpecification Register <TType, TImpl>(params Enum[] tokens)
     where TType : class
     where TImpl : class, TType
 {
     return(Register <TType, TImpl>(EnumExtensions.CombinedToken(tokens)));
 }
 /// <summary>
 /// Sets the <see cref="RuleSource"/>.
 /// </summary>
 /// <param name="index">The index of the <see cref="RuleSourceType"/>.</param>
 public virtual void SetRuleSource(int index)
 {
     RuleSource = EnumExtensions.GetByIndex <RuleSourceType>(index);
 }
コード例 #9
0
        public void SubscribeKlineStream(string symbol, KlineInterval interval, Action <BinanceKlineData> messageEventHandler)
        {
            var sockName = $"{symbol.ToLower()}@kline_{EnumExtensions.GetEnumMemberValue(interval)}";

            AddStreamSubscriber(sockName, messageEventHandler);
        }
コード例 #10
0
ファイル: EventLog.ascx.cs プロジェクト: hnjm/YAFNET
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
        {
            // do it only once, not on post-backs
            if (this.IsPostBack)
            {
                return;
            }

            var allItem = new ListItem(this.GetText("ALL"), "-1");

            allItem.Attributes.Add(
                "data-content",
                $"<span class=\"select2-image-select-icon\"><i class=\"fas fa-filter fa-fw text-secondary\"></i>&nbsp;{this.GetText("ALL")}</span>");

            this.Types.Items.Add(allItem);

            EnumExtensions.GetAllItems <EventLogTypes>().ForEach(
                type =>
            {
                var icon = type switch
                {
                    EventLogTypes.Error => "radiation",
                    EventLogTypes.Warning => "exclamation-triangle",
                    EventLogTypes.Information => "exclamation",
                    EventLogTypes.Debug => "exclamation-triangle",
                    EventLogTypes.Trace => "exclamation-triangle",
                    EventLogTypes.SqlError => "exclamation-triangle",
                    EventLogTypes.UserSuspended => "user-clock",
                    EventLogTypes.UserUnsuspended => "user-check",
                    EventLogTypes.UserDeleted => "user-alt-slash",
                    EventLogTypes.IpBanSet => "hand-paper",
                    EventLogTypes.IpBanLifted => "slash",
                    EventLogTypes.IpBanDetected => "hand-paper",
                    EventLogTypes.SpamBotReported => "user-ninja",
                    EventLogTypes.SpamBotDetected => "user-lock",
                    EventLogTypes.SpamMessageReported => "flag",
                    EventLogTypes.SpamMessageDetected => "shield-alt",
                    _ => "exclamation-circle"
                };

                var item = new ListItem {
                    Value = type.ToInt().ToString(), Text = type.ToString()
                };

                item.Attributes.Add(
                    "data-content",
                    $"<span class=\"select2-image-select-icon\"><i class=\"fas fa-{icon} fa-fw text-secondary\"></i>&nbsp;{type}</span>");

                this.Types.Items.Add(item);
            });

            var ci = this.Get <ILocalization>().Culture;

            if (this.Get <BoardSettings>().UseFarsiCalender&& ci.IsFarsiCulture())
            {
                this.SinceDate.Text = PersianDateConverter.ToPersianDate(PersianDate.MinValue).ToString("d");
                this.ToDate.Text    = PersianDateConverter.ToPersianDate(PersianDate.Now).ToString("d");
            }
            else
            {
                this.SinceDate.Text = DateTime.UtcNow.AddDays(-this.Get <BoardSettings>().EventLogMaxDays).ToString(
                    ci.DateTimeFormat.ShortDatePattern, CultureInfo.InvariantCulture);
                this.ToDate.Text = DateTime.UtcNow.Date.ToString(
                    ci.DateTimeFormat.ShortDatePattern, CultureInfo.InvariantCulture);
            }

            this.ToDate.ToolTip = this.SinceDate.ToolTip = this.GetText("COMMON", "CAL_JQ_TT");

            // bind data to controls
            this.BindData();
        }
コード例 #11
0
        /// <summary>
        /// Configures a <see cref="Switch"/> instance
        /// </summary>
        /// <param name="device">The instance to configure</param>
        public static void Configure(Switch device)
        {
            if (Instance == null)
            {
                throw new InvalidOperationException("Configuration has not been loaded yet.");
            }

            GraphicsConfig.ShadersDumpPath = Instance.GraphicsShadersDumpPath;

            Logger.AddTarget(new AsyncLogTargetWrapper(
                                 new ConsoleLogTarget(),
                                 1000,
                                 AsyncLogTargetOverflowAction.Block
                                 ));

            if (Instance.EnableFileLog)
            {
                Logger.AddTarget(new AsyncLogTargetWrapper(
                                     new FileLogTarget(Path.Combine(Program.ApplicationDirectory, "Ryujinx.log")),
                                     1000,
                                     AsyncLogTargetOverflowAction.Block
                                     ));
            }

            Logger.SetEnable(LogLevel.Debug, Instance.LoggingEnableDebug);
            Logger.SetEnable(LogLevel.Stub, Instance.LoggingEnableStub);
            Logger.SetEnable(LogLevel.Info, Instance.LoggingEnableInfo);
            Logger.SetEnable(LogLevel.Warning, Instance.LoggingEnableWarn);
            Logger.SetEnable(LogLevel.Error, Instance.LoggingEnableError);
            Logger.SetEnable(LogLevel.Guest, Instance.LoggingEnableGuest);
            Logger.SetEnable(LogLevel.AccessLog, Instance.LoggingEnableFsAccessLog);

            if (Instance.LoggingFilteredClasses.Length > 0)
            {
                foreach (var logClass in EnumExtensions.GetValues <LogClass>())
                {
                    Logger.SetEnable(logClass, false);
                }

                foreach (var logClass in Instance.LoggingFilteredClasses)
                {
                    Logger.SetEnable(logClass, true);
                }
            }

            device.System.State.DiscordIntegrationEnabled = Instance.EnableDiscordIntegration;

            device.EnableDeviceVsync = Instance.EnableVsync;

            device.System.State.DockedMode = Instance.DockedMode;

            device.System.State.SetLanguage(Instance.SystemLanguage);

            if (Instance.EnableMulticoreScheduling)
            {
                device.System.EnableMultiCoreScheduling();
            }

            device.System.FsIntegrityCheckLevel = Instance.EnableFsIntegrityChecks
                ? IntegrityCheckLevel.ErrorOnInvalid
                : IntegrityCheckLevel.None;

            device.System.GlobalAccessLogMode = Instance.FsGlobalAccessLogMode;

            if (Instance.EnableAggressiveCpuOpts)
            {
                Optimizations.AssumeStrictAbiCompliance = true;
            }

            ServiceConfiguration.IgnoreMissingServices = Instance.IgnoreMissingServices;

            if (Instance.GamepadControls.Enabled)
            {
                if (GamePad.GetName(Instance.GamepadControls.Index) == "Unmapped Controller")
                {
                    Instance.GamepadControls.SetEnabled(false);
                }
            }

            device.Hid.InitializePrimaryController(Instance.ControllerType);
            device.Hid.InitializeKeyboard();
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: todo-it/philadelphia
        public static void OnReady()
        {
            var di = new PhillyContainer();

            di.RegisterAlias <IHttpRequester, BridgeHttpRequester>(LifeStyle.Singleton);
            Services.Register(di); //registers discovered services from model
            di.Register <HelloWorldFlow>(LifeStyle.Transient);

            Toolkit.InitializeToolkit();

            var testOrNull = DocumentUtil.GetHashParameterOrNull(MagicsForTests.TestChoiceParamName);

            if (testOrNull == null)
            {
                Document.Body.AppendChild(new HTMLSpanElement {
                    TextContent = "no test selected"
                });
            }

            switch (EnumExtensions.GetEnumByLabel <MagicsForTests.ClientSideFlows>(testOrNull))
            {
            case MagicsForTests.ClientSideFlows.ServerSentEvents: {
                IServerSentEventsService_RegisterListener_SseSubscriber listener = null;
                var service = di.Resolve <IServerSentEventsService>();

                var log = new HTMLDivElement {
                    Id = MagicsForTests.RunClientSideTestLogSpanId
                };
                log.Style.WhiteSpace = WhiteSpace.Pre;

                void LogWriteLine(string x)
                {
                    Logger.Debug(typeof(Program), "adding log line: {0}", x);
                    log.TextContent = log.TextContent + x + "\n";
                }

                void DoConnect()
                {
                    if (listener != null)
                    {
                        throw new Exception("already connected");
                    }

                    var notifScopeRaw = DocumentUtil.GetHashParameterOrNull(MagicsForTests.ValueToSend);
                    var notifScope    = JsonConvert.DeserializeObject <SomeNotifFilter>(notifScopeRaw);

                    listener = new IServerSentEventsService_RegisterListener_SseSubscriber(
                        () => notifScope, false);

                    listener.OnConnOpen += () => LogWriteLine("connected");
                    listener.OnError    += (ev, crs) => LogWriteLine($"connection error {(int)crs}");
                    listener.OnMessage  += x => LogWriteLine($"received: {x}");

                    listener.Connect();
                }

                var sendMsg = new HTMLButtonElement {
                    TextContent = "send", Id = MagicsForTests.RunClientSideTestSendBtnId
                };
                sendMsg.OnClick += async _ => {
                    var msgRaw = DocumentUtil.GetHashParameterOrNull(MagicsForTests.ValueToSend);
                    var msg    = JsonConvert.DeserializeObject <SomeNotif>(msgRaw);

                    await service.Publish(msg);
                };

                var connectAction = new HTMLButtonElement {
                    TextContent = "connect", Id = MagicsForTests.RunClientSideTestConnectId
                };
                connectAction.OnClick += _ => DoConnect();

                var disconnectAction = new HTMLButtonElement {
                    TextContent = "disconnect", Id = MagicsForTests.RunClientSideTestDisconnectId
                };
                disconnectAction.OnClick += _ => {
                    listener.Dispose();
                    listener = null;
                };

                Document.Body.AppendChild(log);
                Document.Body.AppendChild(sendMsg);
                Document.Body.AppendChild(connectAction);
                Document.Body.AppendChild(disconnectAction);
                //TODO add disconnect
            }
            break;

            case MagicsForTests.ClientSideFlows.HelloWorld:
                var renderer = Toolkit.DefaultFormRenderer();

                di.Resolve <HelloWorldFlow>().Run(renderer);
                break;

            case MagicsForTests.ClientSideFlows.SerializationTest_String:
                RunSerializationTestFlow(
                    MagicsForTests.Serialization.String.DefaultTypedVal,
                    s => s,
                    d => d,
                    val => di.Resolve <ISerDeserService>().ProcessString(val));
                break;


            case MagicsForTests.ClientSideFlows.SerializationTest_Int:
                RunSerializationTestFlow(
                    MagicsForTests.Serialization.Int.DefaultTypedVal,
                    s => int.Parse(s),
                    d => d.ToString(),
                    val => di.Resolve <ISerDeserService>().ProcessInt(val));
                break;


            case MagicsForTests.ClientSideFlows.SerializationTest_DateTimeUtc:
                RunSerializationTestFlow(
                    MagicsForTests.Serialization.DateTimeUTC.DefaultTypedVal,
                    s => Convert.ToDateTime(s),
                    d => d.ToStringYyyyMmDdHhMm(),
                    val => di
                    .Resolve <ISerDeserService>()
                    .ProcessDateTime(DateTime.SpecifyKind(val, DateTimeKind.Utc), true));
                break;

            case MagicsForTests.ClientSideFlows.SerializationTest_DateTimeLocal:
                RunSerializationTestFlow(
                    MagicsForTests.Serialization.DateTimeLocal.DefaultTypedVal,
                    s => Convert.ToDateTime(s),
                    d => d.ToStringYyyyMmDdHhMm(),
                    val => di
                    .Resolve <ISerDeserService>()
                    .ProcessDateTime(DateTime.SpecifyKind(val, DateTimeKind.Local), false));
                break;

            case MagicsForTests.ClientSideFlows.SerializationTest_Long:
                RunSerializationTestFlow(
                    MagicsForTests.Serialization.Long.DefaultTypedVal,
                    s => long.Parse(s),
                    d => d.ToString(),
                    val => di.Resolve <ISerDeserService>().ProcessLong(val));
                break;

            case MagicsForTests.ClientSideFlows.SerializationTest_Decimal:
                RunSerializationTestFlow(
                    MagicsForTests.Serialization.Decimal.DefaultTypedVal,
                    s => decimal.Parse(s, CultureInfo.InvariantCulture),
                    d => d.ToString(CultureInfo.InvariantCulture),
                    val => di.Resolve <ISerDeserService>().ProcessDecimal(val));
                break;

            default:
                Document.Body.AppendChild(new HTMLSpanElement {
                    TextContent = "unsupported test selected"
                });
                break;
            }
        }
コード例 #13
0
        public BaseInitService(DataInitType initType, string xmlDataFile)
        {
            this.Name = EnumExtensions.GetDesc <DataInitType>(initType.ToString());

            this.XmlFilePath = Path.Combine(AppContext.BaseDirectory, xmlDataFile);
        }
コード例 #14
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            var sourceTypeProperty = property.FindPropertyRelative("sourceType");
            var sourceTypeValue    = (ImagerySourceType)sourceTypeProperty.enumValueIndex;

            var displayNames = sourceTypeProperty.enumDisplayNames;
            int count        = sourceTypeProperty.enumDisplayNames.Length;

            if (!isGUIContentSet)
            {
                sourceTypeContent = new GUIContent[count];
                for (int extIdx = 0; extIdx < count; extIdx++)
                {
                    sourceTypeContent[extIdx] = new GUIContent
                    {
                        text    = displayNames[extIdx],
                        tooltip = EnumExtensions.Description((ImagerySourceType)extIdx),
                    };
                }
                isGUIContentSet = true;
            }

            // Draw label.
            var sourceTypeLabel = new GUIContent {
                text = "Data Source", tooltip = "Source tileset for Imagery."
            };

            EditorGUI.BeginChangeCheck();
            sourceTypeProperty.enumValueIndex = EditorGUILayout.Popup(sourceTypeLabel, sourceTypeProperty.enumValueIndex, sourceTypeContent);
            if (EditorGUI.EndChangeCheck())
            {
                EditorHelper.CheckForModifiedProperty(property);
            }
            sourceTypeValue = (ImagerySourceType)sourceTypeProperty.enumValueIndex;

            var sourceOptionsProperty = property.FindPropertyRelative("sourceOptions");
            var layerSourceProperty   = sourceOptionsProperty.FindPropertyRelative("layerSource");
            var layerSourceId         = layerSourceProperty.FindPropertyRelative("Id");

            EditorGUI.BeginChangeCheck();

            switch (sourceTypeValue)
            {
            case ImagerySourceType.MapboxStreets:
            case ImagerySourceType.MapboxOutdoors:
            case ImagerySourceType.MapboxDark:
            case ImagerySourceType.MapboxLight:
            case ImagerySourceType.MapboxSatellite:
            case ImagerySourceType.MapboxSatelliteStreet:
                var sourcePropertyValue = MapboxDefaultImagery.GetParameters(sourceTypeValue);
                layerSourceId.stringValue = sourcePropertyValue.Id;
                GUI.enabled = false;
                EditorGUILayout.PropertyField(sourceOptionsProperty, _tilesetIdGui);
                GUI.enabled = true;
                break;

            case ImagerySourceType.Custom:
                EditorGUILayout.PropertyField(sourceOptionsProperty, new GUIContent {
                    text = "Tileset Id / Style URL", tooltip = _tilesetIdGui.tooltip
                });
                break;

            case ImagerySourceType.None:
                break;

            default:
                break;
            }

            if (EditorGUI.EndChangeCheck())
            {
                EditorHelper.CheckForModifiedProperty(property);
            }

            if (sourceTypeValue != ImagerySourceType.None)
            {
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(property.FindPropertyRelative("rasterOptions"));
                if (EditorGUI.EndChangeCheck())
                {
                    EditorHelper.CheckForModifiedProperty(property);
                }
            }
        }
コード例 #15
0
 public IObjectAssemblySpecification Register <TType>(Func <IAssembleObject, TType> func, params Enum[] tokens)
     where TType : class
 {
     return(Register(EnumExtensions.CombinedToken(tokens), func));
 }
コード例 #16
0
        public async Task <IActionResult> Delete(int id)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = true,
                        StatusCode = ((int)ResponseStatus.BadRequest).ToString(),
                        Message = string.Join("; ", ModelState.Values
                                              .SelectMany(x => x.Errors)
                                              .Select(x => x.ErrorMessage))
                    }));
                }
                StreamDataAccess _streamAccess = new StreamDataAccess(_iconfiguration);

                DatabaseResponse response = await _streamAccess.DeleteStream(id);

                if (response.ResponseCode == (int)DbReturnValue.DeleteSuccess)
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = true,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.DeleteSuccess),
                        ReturnedObject = response.Results
                    }));
                }
                else if (response.ResponseCode == (int)DbReturnValue.ActiveTryDelete)
                {
                    Log.Error(EnumExtensions.GetDescription(DbReturnValue.ActiveTryDelete));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.ActiveTryDelete),
                        ReturnedObject = response.Results
                    }));
                }
                else
                {
                    Log.Error(EnumExtensions.GetDescription(DbReturnValue.NotExists));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.NotExists),
                        ReturnedObject = response.Results
                    }));
                }
            }
            catch (Exception ex)
            {
                Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok(new OperationResponse
                {
                    HasSucceeded = false,
                    Message = StatusMessages.ServerError,
                    StatusCode = ((int)ResponseStatus.ServerError).ToString(),
                    IsDomainValidationErrors = false
                }));
            }
        }
コード例 #17
0
 public IObjectAssemblySpecification Register(Type type, Func <IAssembleObject, object> func, params Enum[] tokens)
 {
     return(Register(EnumExtensions.CombinedToken(tokens), type, func));
 }
コード例 #18
0
ファイル: AdminOrderController.cs プロジェクト: santhign/Grid
        public async Task <IActionResult> GetOrderDetails([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromRoute] int orderID)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = true,
                        Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty)
                    }));
                }
                AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration);

                DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token);

                if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess)
                {
                    if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired)
                    {
                        if (!ModelState.IsValid)
                        {
                            return(StatusCode((int)HttpStatusCode.OK,
                                              new OperationResponse
                            {
                                HasSucceeded = false,
                                IsDomainValidationErrors = true,
                                Message = string.Join("; ", ModelState.Values
                                                      .SelectMany(x => x.Errors)
                                                      .Select(x => x.ErrorMessage))
                            }));
                        }

                        CommonDataAccess commonData = new CommonDataAccess(_iconfiguration);

                        var orderList = await commonData.GetOrderDetails(orderID);

                        if (orderList == null || orderList.OrderID == 0)
                        {
                            return(Ok(new ServerResponse
                            {
                                HasSucceeded = false,
                                Message = EnumExtensions.GetDescription(DbReturnValue.NotExists)
                            }));
                        }
                        else
                        {
                            // DownloadFile


                            DatabaseResponse awsConfigResponse = await commonData.GetConfiguration(ConfiType.AWS.ToString());

                            if (awsConfigResponse != null && awsConfigResponse.ResponseCode == (int)DbReturnValue.RecordExists)
                            {
                                MiscHelper configHelper = new MiscHelper();

                                GridAWSS3Config awsConfig = configHelper.GetGridAwsConfig((List <Dictionary <string, string> >)awsConfigResponse.Results);

                                AmazonS3 s3Helper = new AmazonS3(awsConfig);


                                DownloadResponse FrontImageDownloadResponse = new DownloadResponse();

                                DownloadResponse BackImageDownloadResponse = new DownloadResponse();

                                if (!string.IsNullOrEmpty(orderList.DocumentURL))
                                {
                                    FrontImageDownloadResponse = await s3Helper.DownloadFile(orderList.DocumentURL.Remove(0, awsConfig.AWSEndPoint.Length));

                                    if (FrontImageDownloadResponse.HasSucceed)
                                    {
                                        orderList.FrontImage = FrontImageDownloadResponse.FileObject != null?configHelper.GetBase64StringFromByteArray(FrontImageDownloadResponse.FileObject, orderList.DocumentURL.Remove(0, awsConfig.AWSEndPoint.Length)) : null;

                                        orderList.DocumentURL = "";
                                    }
                                    else
                                    {
                                        orderList.DocumentURL = "";
                                        orderList.FrontImage  = "";
                                    }
                                }

                                if (!string.IsNullOrEmpty(orderList.DocumentBackURL))
                                {
                                    BackImageDownloadResponse = await s3Helper.DownloadFile(orderList.DocumentBackURL.Remove(0, awsConfig.AWSEndPoint.Length));

                                    if (BackImageDownloadResponse.HasSucceed)
                                    {
                                        orderList.BackImage = BackImageDownloadResponse.FileObject != null?configHelper.GetBase64StringFromByteArray(BackImageDownloadResponse.FileObject, orderList.DocumentBackURL.Remove(0, awsConfig.AWSEndPoint.Length)) : null;

                                        orderList.DocumentBackURL = "";
                                    }
                                    else
                                    {
                                        orderList.DocumentBackURL = "";
                                        orderList.BackImage       = "";
                                    }
                                }
                                return(Ok(new ServerResponse
                                {
                                    HasSucceeded = true,
                                    Message = StatusMessages.SuccessMessage,
                                    Result = orderList
                                }));
                            }
                            else
                            {
                                // unable to get aws config
                                LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.FailedToGetConfiguration));

                                return(Ok(new OperationResponse
                                {
                                    HasSucceeded = false,
                                    Message = EnumExtensions.GetDescription(CommonErrors.FailedToGetConfiguration)
                                }));
                            }
                        }
                    }
                    else
                    {
                        //Token expired

                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken));

                        return(Ok(new OperationResponse
                        {
                            HasSucceeded = false,
                            Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired),
                            IsDomainValidationErrors = true
                        }));
                    }
                }

                else
                {
                    // token auth failure
                    LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed),
                        IsDomainValidationErrors = false
                    }));
                }
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok(new OperationResponse
                {
                    HasSucceeded = false,
                    Message = StatusMessages.ServerError,
                    IsDomainValidationErrors = false
                }));
            }
        }
コード例 #19
0
 public IObjectAssemblySpecification RegisterInstance(Type type, object instance, params Enum[] tokens)
 {
     return(RegisterInstance(EnumExtensions.CombinedToken(tokens), type, instance));
 }
コード例 #20
0
ファイル: AdminOrderController.cs プロジェクト: santhign/Grid
        public async Task <IActionResult> UpdateNRICDetails([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromForm] NRICDetails request)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = true,
                        Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty)
                    }));
                }
                AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration);

                DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token);

                if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess)
                {
                    if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired)
                    {
                        if (!ModelState.IsValid)
                        {
                            return(StatusCode((int)HttpStatusCode.OK,
                                              new OperationResponse
                            {
                                HasSucceeded = false,
                                IsDomainValidationErrors = true,
                                Message = string.Join("; ", ModelState.Values
                                                      .SelectMany(x => x.Errors)
                                                      .Select(x => x.ErrorMessage))
                            }));
                        }

                        if (!string.IsNullOrEmpty(request.IdentityCardNumber))
                        {
                            EmailValidationHelper _helper = new EmailValidationHelper();
                            if (!_helper.NRICValidation(null, request.IdentityCardNumber, out string _warningmsg))
                            {
                                LogInfo.Warning("NRIC Validation with type: " + _warningmsg);
                                return(Ok(new OperationResponse
                                {
                                    HasSucceeded = false,
                                    Message = "Document details are invalid",
                                    IsDomainValidationErrors = false
                                }));
                            }
                        }

                        int deliveryStatusNumber = request.IDVerificationStatus;

                        var              authToken         = (AuthTokenResponse)tokenAuthResponse.Results;
                        MiscHelper       configHelper      = new MiscHelper();
                        CommonDataAccess _commonDataAccess = new CommonDataAccess(_iconfiguration);

                        NRICDetailsRequest personalDetails = new NRICDetailsRequest
                        {
                            OrderID            = request.OrderID,
                            IdentityCardNumber = request.IdentityCardNumber,
                            IdentityCardType   = request.IdentityCardType,
                            Nationality        = request.Nationality,
                            NameInNRIC         = request.NameInNRIC,
                            DOB     = request.DOB,
                            Expiry  = request.Expiry,
                            Remarks = request.Remarks,
                            IDVerificationStatus = request.IDVerificationStatus,
                        };

                        if (request.FrontImage != null || request.BackImage != null)
                        {
                            string IDCardNumberForImage = string.Empty;

                            DatabaseResponse awsConfigResponse = await _commonDataAccess.GetConfiguration(ConfiType.AWS.ToString());

                            if (awsConfigResponse != null && awsConfigResponse.ResponseCode == (int)DbReturnValue.RecordExists)
                            {
                                GridAWSS3Config awsConfig = configHelper.GetGridAwsConfig((List <Dictionary <string, string> >)awsConfigResponse.Results);
                                // Check for IdentityCardNumber
                                //Start
                                if (string.IsNullOrEmpty(request.IdentityCardNumber))
                                {
                                    var orderDetailsForIDCard = await _commonDataAccess.GetOrderDetails(request.OrderID);

                                    IDCardNumberForImage = orderDetailsForIDCard.IdentityCardNumber;
                                }
                                else
                                {
                                    IDCardNumberForImage = request.IdentityCardNumber;
                                }
                                //End
                                AmazonS3 s3Helper = new AmazonS3(awsConfig);
                                if (request.FrontImage != null)
                                {
                                    string fileNameFront = IDCardNumberForImage.Substring(1, IDCardNumberForImage.Length - 2) +
                                                           "_Front_" + DateTime.Now.ToString("yyMMddhhmmss") + Path.GetExtension(request.FrontImage.FileName); //Grid_IDNUMBER_yyyymmddhhmmss.extension

                                    UploadResponse s3UploadResponse = await s3Helper.UploadFile(request.FrontImage, fileNameFront);

                                    if (s3UploadResponse.HasSucceed)
                                    {
                                        personalDetails.FrontImage = awsConfig.AWSEndPoint + s3UploadResponse.FileName;
                                    }
                                    else
                                    {
                                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.S3UploadFailed));
                                    }
                                }
                                if (request.BackImage != null)
                                {
                                    string fileNameBack = IDCardNumberForImage.Substring(1, IDCardNumberForImage.Length - 2) + "_Back_" + DateTime.Now.ToString("yyMMddhhmmss")
                                                          + Path.GetExtension(request.BackImage.FileName); //Grid_IDNUMBER_yyyymmddhhmmss.extension

                                    UploadResponse s3UploadResponse = await s3Helper.UploadFile(request.BackImage, fileNameBack);

                                    if (s3UploadResponse.HasSucceed)
                                    {
                                        personalDetails.BackImage = awsConfig.AWSEndPoint + s3UploadResponse.FileName;
                                    }
                                    else
                                    {
                                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.S3UploadFailed));
                                    }
                                }
                            }
                            else
                            {
                                // unable to get aws config
                                LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.FailedToGetConfiguration));
                            }
                        }

                        var returnResponse = await _commonDataAccess.UpdateNRICDetails(authToken.CustomerID, deliveryStatusNumber, personalDetails);

                        if (returnResponse.ResponseCode == (int)DbReturnValue.UpdateSuccessSendEmail)
                        {
                            var emailDetails = (EmailResponse)returnResponse.Results;
                            DatabaseResponse configResponse        = new DatabaseResponse();
                            DatabaseResponse tokenCreationResponse = new DatabaseResponse();

                            string finalURL = string.Empty;
                            // Fetch the URL
                            if (emailDetails.VerificationStatus == 2) // Rejected then token
                            {
                                configResponse        = ConfigHelper.GetValueByKey(ConfigKeys.NRICReUploadLink.GetDescription(), _iconfiguration);
                                tokenCreationResponse = await _adminOrderDataAccess.CreateTokenForVerificationRequests(request.OrderID);

                                var tokenCreation = (VerificationRequestResponse)tokenCreationResponse.Results;
                                finalURL = configResponse.Results.ToString() + tokenCreation.RequestToken;
                            }
                            else
                            {
                                var result = await _commonDataAccess.UpdateTokenForVerificationRequests(request.OrderID);
                            }

                            //Sending message start
                            // Send email to customer email                            ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration);
                            DatabaseResponse registrationResponse = await _adminOrderDataAccess.GetEmailNotificationTemplate(emailDetails.VerificationStatus == 2?NotificationEvent.ICValidationReject.GetDescription() : NotificationEvent.ICValidationChange.GetDescription());

                            string[] changelog = emailDetails.ChangeLog.Split(";");
                            string   finallog  = "";
                            foreach (string log in changelog)
                            {
                                if (!string.IsNullOrWhiteSpace(log))
                                {
                                    finallog = finallog + "&bull; " + log.Trim() + "<br/>";
                                }
                            }
                            var notificationMessage = MessageHelper.GetMessage(emailDetails.Email, emailDetails.Name, emailDetails.VerificationStatus == 2 ? NotificationEvent.ICValidationReject.GetDescription() : NotificationEvent.ICValidationChange.GetDescription(),
                                                                               ((EmailTemplate)registrationResponse.Results).TemplateName,
                                                                               _iconfiguration, string.IsNullOrWhiteSpace(finalURL) ? "-" : finalURL, string.IsNullOrWhiteSpace(emailDetails.Remark) ? "-" : emailDetails.Remark.Replace(";", "<br />"), string.IsNullOrWhiteSpace(emailDetails.ChangeLog) ? "-" : finallog);
                            var notificationResponse = await _adminOrderDataAccess.GetConfiguration(ConfiType.Notification.ToString());


                            MiscHelper parser             = new MiscHelper();
                            var        notificationConfig = parser.GetNotificationConfig((List <Dictionary <string, string> >)notificationResponse.Results);

                            Publisher customerNotificationPublisher = new Publisher(_iconfiguration, notificationConfig.SNSTopic);
                            await customerNotificationPublisher.PublishAsync(notificationMessage);

                            try
                            {
                                DatabaseResponse notificationLogResponse = await _adminOrderDataAccess.CreateEMailNotificationLogForDevPurpose(
                                    new NotificationLogForDevPurpose
                                {
                                    EventType = NotificationEvent.OrderSuccess.ToString(),
                                    Message   = JsonConvert.SerializeObject(notificationMessage)
                                });
                            }
                            catch (Exception ex)
                            {
                                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
                            }
                            //Sending message Stop
                            return(Ok(new ServerResponse
                            {
                                HasSucceeded = true,
                                Message = StatusMessages.SuccessMessage,
                                Result = null
                            }));
                        }
                        else if (returnResponse.ResponseCode == (int)DbReturnValue.UpdateSuccess)
                        {
                            var emailDetails = (EmailResponse)returnResponse.Results;
                            DatabaseResponse configResponse        = new DatabaseResponse();
                            DatabaseResponse tokenCreationResponse = new DatabaseResponse();
                            string           finalURL = string.Empty;
                            if (emailDetails.VerificationStatus == 2) // Rejected then token
                            {
                                configResponse        = ConfigHelper.GetValueByKey(ConfigKeys.NRICReUploadLink.GetDescription(), _iconfiguration);
                                tokenCreationResponse = await _adminOrderDataAccess.CreateTokenForVerificationRequests(request.OrderID);

                                var tokenCreation = (VerificationRequestResponse)tokenCreationResponse.Results;
                                finalURL = configResponse.Results.ToString() + tokenCreation.RequestToken;

                                DatabaseResponse registrationResponse = await _adminOrderDataAccess.GetEmailNotificationTemplate(NotificationEvent.ICValidationReject.GetDescription());

                                var notificationMessage = MessageHelper.GetMessage(emailDetails.Email, emailDetails.Name, NotificationEvent.ICValidationReject.GetDescription(),
                                                                                   ((EmailTemplate)registrationResponse.Results).TemplateName,
                                                                                   _iconfiguration, string.IsNullOrWhiteSpace(finalURL) ? "-" : finalURL, string.IsNullOrWhiteSpace(emailDetails.Remark) ? "-" : emailDetails.Remark.Replace(";", "<br />"), string.IsNullOrWhiteSpace(emailDetails.ChangeLog) ? "-" : emailDetails.ChangeLog);
                                var notificationResponse = await _adminOrderDataAccess.GetConfiguration(ConfiType.Notification.ToString());


                                MiscHelper parser             = new MiscHelper();
                                var        notificationConfig = parser.GetNotificationConfig((List <Dictionary <string, string> >)notificationResponse.Results);

                                Publisher customerNotificationPublisher = new Publisher(_iconfiguration, notificationConfig.SNSTopic);
                                await customerNotificationPublisher.PublishAsync(notificationMessage);

                                try
                                {
                                    DatabaseResponse notificationLogResponse = await _adminOrderDataAccess.CreateEMailNotificationLogForDevPurpose(
                                        new NotificationLogForDevPurpose
                                    {
                                        EventType = NotificationEvent.OrderSuccess.ToString(),
                                        Message   = JsonConvert.SerializeObject(notificationMessage)
                                    });
                                }
                                catch (Exception ex)
                                {
                                    LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
                                }
                            }
                            else
                            {
                                var result = await _commonDataAccess.UpdateTokenForVerificationRequests(request.OrderID);
                            }

                            //Sending message start
                            // Send email to customer email                            ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration);


                            return(Ok(new ServerResponse
                            {
                                HasSucceeded = true,
                                Message = StatusMessages.SuccessMessage,
                                Result = null
                            }));
                        }
                        else
                        {
                            LogInfo.Error("UpdateNRICDetails failed for " + request.OrderID + " Order Id " + DbReturnValue.UpdationFailed);
                            return(Ok(new OperationResponse
                            {
                                HasSucceeded = false,
                                Message = EnumExtensions.GetDescription(DbReturnValue.UpdationFailed),
                                IsDomainValidationErrors = false
                            }));
                        }
                    }
                    else
                    {
                        //Token expired

                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken));

                        return(Ok(new OperationResponse
                        {
                            HasSucceeded = false,
                            Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired),
                            IsDomainValidationErrors = true
                        }));
                    }
                }

                else
                {
                    // token auth failure
                    LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed),
                        IsDomainValidationErrors = false
                    }));
                }
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok(new OperationResponse
                {
                    HasSucceeded = false,
                    Message = StatusMessages.ServerError,
                    IsDomainValidationErrors = false
                }));
            }
        }
コード例 #21
0
 public IObjectAssemblySpecification Register(Type tType, Type tImpl, params Enum[] tokens)
 {
     return(Register(EnumExtensions.CombinedToken(tokens), tType, tImpl));
 }
コード例 #22
0
ファイル: AdminOrderController.cs プロジェクト: santhign/Grid
        public async Task <IActionResult> GetOrdersList([FromHeader(Name = "Grid-Authorization-Token")] string token, string deliveryStatus, DateTime?fromDate, DateTime?toDate)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = true,
                        Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty)
                    }));
                }
                AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration);

                DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token);

                if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess)
                {
                    if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired)
                    {
                        if (!ModelState.IsValid)
                        {
                            return(StatusCode((int)HttpStatusCode.OK,
                                              new OperationResponse
                            {
                                HasSucceeded = false,
                                IsDomainValidationErrors = true,
                                Message = string.Join("; ", ModelState.Values
                                                      .SelectMany(x => x.Errors)
                                                      .Select(x => x.ErrorMessage))
                            }));
                        }
                        int?deliveryStatusNumber = null;
                        if (!string.IsNullOrWhiteSpace(deliveryStatus))
                        {
                            if (deliveryStatus.Trim().ToLower() == IDVerificationStatus.PendingVerification.GetDescription().Trim().ToLower())
                            {
                                deliveryStatusNumber = 0;
                            }
                            else if (deliveryStatus.Trim().ToLower() == IDVerificationStatus.AcceptedVerification.GetDescription().Trim().ToLower())
                            {
                                deliveryStatusNumber = 1;
                            }
                            else if (deliveryStatus.Trim().ToLower() == IDVerificationStatus.RejectedVerification.GetDescription().Trim().ToLower())
                            {
                                deliveryStatusNumber = 2;
                            }
                        }

                        var orderList = await _adminOrderDataAccess.GetOrdersList(deliveryStatusNumber, fromDate, toDate);

                        if (orderList == null || orderList.Count == 0)
                        {
                            return(Ok(new ServerResponse
                            {
                                HasSucceeded = true,
                                Message = EnumExtensions.GetDescription(DbReturnValue.NotExists)
                            }));
                        }
                        else
                        {
                            return(Ok(new ServerResponse
                            {
                                HasSucceeded = true,
                                Message = StatusMessages.SuccessMessage,
                                Result = orderList
                            }));
                        }
                    }
                    else
                    {
                        //Token expired

                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken));

                        return(Ok(new OperationResponse
                        {
                            HasSucceeded = false,
                            Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired),
                            IsDomainValidationErrors = true
                        }));
                    }
                }

                else
                {
                    // token auth failure
                    LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed),
                        IsDomainValidationErrors = false
                    }));
                }
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok(new OperationResponse
                {
                    HasSucceeded = false,
                    Message = StatusMessages.ServerError,
                    IsDomainValidationErrors = false
                }));
            }
        }
コード例 #23
0
 public IObjectAssemblySpecification GetRegistration(Type type, params Enum[] tokens)
 {
     return(GetRegistration(EnumExtensions.CombinedToken(tokens), type));
 }
コード例 #24
0
ファイル: AdminOrderController.cs プロジェクト: santhign/Grid
        public async Task <IActionResult> GetOrderDetailsHistory([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromRoute] int orderID)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = true,
                        Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty)
                    }));
                }
                AdminUsersDataAccess _adminUsersDataAccess = new AdminUsersDataAccess(_iconfiguration);

                DatabaseResponse tokenAuthResponse = await _adminUsersDataAccess.AuthenticateAdminUserToken(token);

                if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess)
                {
                    if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired)
                    {
                        if (!ModelState.IsValid)
                        {
                            return(StatusCode((int)HttpStatusCode.OK,
                                              new OperationResponse
                            {
                                HasSucceeded = false,
                                IsDomainValidationErrors = true,
                                Message = string.Join("; ", ModelState.Values
                                                      .SelectMany(x => x.Errors)
                                                      .Select(x => x.ErrorMessage))
                            }));
                        }
                        var orderList = await _adminOrderDataAccess.GetNRICOrderDetailsHistory(orderID);

                        if (orderList == null || orderList.Count == 0)
                        {
                            return(Ok(new ServerResponse
                            {
                                HasSucceeded = false,
                                Message = EnumExtensions.GetDescription(DbReturnValue.NotExists)
                            }));
                        }
                        else
                        {
                            return(Ok(new ServerResponse
                            {
                                HasSucceeded = true,
                                Message = StatusMessages.SuccessMessage,
                                Result = orderList
                            }));
                        }
                    }
                    else
                    {
                        //Token expired

                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken));

                        return(Ok(new OperationResponse
                        {
                            HasSucceeded = false,
                            Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired),
                            IsDomainValidationErrors = true
                        }));
                    }
                }

                else
                {
                    // token auth failure
                    LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed),
                        IsDomainValidationErrors = false
                    }));
                }
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok(new OperationResponse
                {
                    HasSucceeded = false,
                    Message = StatusMessages.ServerError,
                    IsDomainValidationErrors = false
                }));
            }
        }
コード例 #25
0
        public void GetAttributeTest()
        {
            MyAttribute att = EnumExtensions.GetAttribute <MyAttribute>(TestGetAttributeEnum.Dude);

            Assert.IsTrue(att.Num == 42);
        }
 public static IRuleBuilderOptions <T, int> MustBeEnumValue <T>(this IRuleBuilder <T, int> builder, IStringLocalizer localizer, Type enumType) =>
 builder.Must(value => value.IsValidEnum(enumType)).WithMessage($"\"{{PropertyName}}\" {string.Format(localizer["MustBeAnyOf"].Value, string.Join(",", EnumExtensions.StationTrackDirections()))}");
コード例 #27
0
        public void GetAttributeTestNull1()
        {
            object result = EnumExtensions.GetAttribute <MyAttribute>((TestGetAttributeEnum)44);

            Assert.IsTrue(result == null);
        }
コード例 #28
0
ファイル: BookController.cs プロジェクト: sandeep18051989/SMS
        public ActionResult LoadGrid()
        {
            try
            {
                var draw          = Request.Form.GetValues("draw").FirstOrDefault();
                var start         = Request.Form.GetValues("start").FirstOrDefault();
                var length        = Request.Form.GetValues("length").FirstOrDefault();
                var sortColumn    = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]")?.FirstOrDefault() + "][name]")?.FirstOrDefault();
                var sortColumnDir = Request.Form.GetValues("order[0][dir]")?.FirstOrDefault();
                var searchValue   = Request.Form.GetValues("search[value]")?.FirstOrDefault();

                //Paging Size (10,20,50,100)
                int pageSize = length != null?Convert.ToInt32(length) : 0;

                int skip = start != null?Convert.ToInt32(start) : 0;

                int recordsTotal = 0;

                // Getting all data
                var bookData = (from tempbook in _smsService.GetAllBooks() select tempbook);

                //Search
                if (!string.IsNullOrEmpty(searchValue))
                {
                    bookData = bookData.Where(m => m.Name.Contains(searchValue));
                }

                //total number of rows count
                var lstBook = bookData as Book[] ?? bookData.ToArray();
                recordsTotal = lstBook.Count();
                //Paging
                var data = lstBook.Skip(skip).Take(pageSize);

                //Returning Json Data
                return(new JsonResult()
                {
                    Data = new
                    {
                        draw = draw,
                        recordsFiltered = recordsTotal,
                        recordsTotal = recordsTotal,
                        data = data.Select(x => new BookModel()
                        {
                            AcadmicYearId = x.AcadmicYearId,
                            Id = x.Id,
                            Name = x.Name,
                            IsActive = x.IsActive,
                            UserId = x.UserId,
                            Author = x.Author,
                            BookStatusId = x.BookStatusId,
                            Description = x.Description,
                            Price = x.Price,
                            AcadmicYear = _smsService.GetAcadmicYearById(x.AcadmicYearId).Name,
                            BookStatus = x.BookStatusId > 0 ? EnumExtensions.GetDescriptionByValue <BookStatus>(x.BookStatusId) : "",
                        }).OrderBy(x => x.Name).ToList()
                    },
                    ContentEncoding = Encoding.Default,
                    ContentType = "application/json",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    MaxJsonLength = int.MaxValue
                });
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
コード例 #29
0
 /// inheritdoc/>
 protected override Enum UpdateSelection(Enum currentValue)
 {
     return(EnumExtensions.GetEnum(currentValue.GetType(), Enumerable.Empty <Enum>()));
 }
コード例 #30
0
        public string FormatValue(Number value, EffectScalarType scalarType)
        {
            var type = MemberType.GetAssignmentType();

            if (type == null)
            {
                return(value.UInt.ToString());
            }
            var numberType = scalarType.ToNumberType();

            if (type.IsEnum && scalarType == EffectScalarType.Int)
            {
                var enumValue   = (Enum)Enum.ToObject(type, value.UInt);
                var description = EnumExtensions.GetDescription(enumValue);
                return(string.Format("{0} /* {1} */", description, value.UInt));
            }
            else if (type.IsEnum)
            {
                return(value.ToString(numberType));
            }
            if (type == typeof(float))
            {
                return(value.ToString());
            }
            if (type == typeof(byte))
            {
                if (numberType == Shex.NumberType.UInt || numberType == Shex.NumberType.Int)
                {
                    return(string.Format("0x{0:x2}", value.Byte0));
                }
                else
                {
                    return(value.ToString(numberType));
                }
            }
            if (type == typeof(bool))
            {
                if (scalarType == EffectScalarType.Bool)
                {
                    return(string.Format("{0} /* {1} */",
                                         value.ToString(Shex.NumberType.Bool).ToUpper(), value.ToString(Shex.NumberType.Bool)));
                }
                else if (scalarType == EffectScalarType.Int)
                {
                    return(string.Format("{0} /* {1} */",
                                         value.ToString(Shex.NumberType.Bool).ToUpper(), value.UInt));
                }
                else
                {
                    return(value.ToString(numberType));
                }
            }
            if (type == typeof(uint))
            {
                if (scalarType == EffectScalarType.UInt)
                {
                    if (value.UInt > 10000)
                    {
                        return("0x" + value.UInt.ToString("x8"));
                    }
                    return(value.UInt.ToString());
                }
                else
                {
                    return(value.ToString(numberType));
                }
            }
            return(value.ToString(numberType));
        }