Esempio n. 1
0
        public static void AddMvc(
            this IServiceCollection services,
            WebApiOptions webApiOptions)
        {
            Assembly assembly = typeof(StartupMvc)
                                .GetTypeInfo().Assembly;

            services
            .AddRouting((options) =>
            {
                options.LowercaseUrls = true;
            });

            services
            .AddMvc(mvcOptions =>
            {
                mvcOptions.OutputFormatters
                .AddDefaultJsonOutputFormatter();
            })
            .AddApplicationPart(assembly)
            .AddControllersAsServices()
            .ConfigureApplicationPartManager(manager =>
            {
                manager.FeatureProviders.Clear();
                manager.FeatureProviders.Add(
                    new TypedControllerFeatureProvider <WebApiController>());
            });
        }
        private async Task <ContactEntity> GetContactEntityAsync(int contactId, Tenant tenant)
        {
            // maybe the tenant canceled their subscription...
            // make sure the tenant is running (not off-line or in backup or maintenance mode)

            var tenantStatus = GetTenantStatus(tenant);

            if (tenantStatus.IsRunning)
            {
                var sysUserInfo   = GetSystemUserInfo();
                var sysUserTicket = await GetSystemUserTicket(sysUserInfo);

                var config = new WebApiOptions(tenant.WebApiUrl);
                config.Authorization = new AuthorizationSystemUserTicket(sysUserInfo, sysUserTicket);

                //config.LanguageCode = "en";
                //config.CultureCode = "en";
                //config.TimeZone = "UTC";

                var contactAgent = new ContactAgent(config);
                return(await contactAgent.GetContactEntityAsync(contactId));
            }

            return(null);
        }
 /// <summary>
 /// DI Constructor
 /// </summary>
 public ResponsesController(ResponseDataManager responseDataManager,
                            IOptions <WebApiOptions> config, IMassTransitServiceBus serviceBusClient)
 {
     _config = config.Value;
     _responseDataManager = responseDataManager;
     _serviceBus          = serviceBusClient;
 }
        public async T.Task OnGetAsync()
        {
            if (SearchId > 0)
            {
                var authenticationInfo = HttpContext.AuthenticateAsync()?.Result;
                if (authenticationInfo != null)
                {
                    // could use "User.Claims", but still need AuthInfo to access Tokens...

                    var webApiUrl      = authenticationInfo.Principal.Claims.Where(c => c.Type.Contains("webapi", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                    var clientSettings = _superOfficeOptions.Get(SuperOfficeAuthenticationDefaults.AuthenticationScheme);
                    var callbackUri    = $"{this.Request.Scheme}://{this.Request.Host}{clientSettings.CallbackPath}";

                    var authorization = new AuthorizationAccessToken(
                        authenticationInfo.Properties.GetTokenValue(Constants.OAuth.AccessToken),
                        authenticationInfo.Properties.GetTokenValue(Constants.OAuth.IdToken),
                        authenticationInfo.Properties.GetTokenValue(Constants.OAuth.RefreshToken),
                        clientSettings.ClientId,
                        clientSettings.ClientSecret,
                        callbackUri,
                        GetEnvironment(clientSettings.Environment)
                        );

                    var config = new WebApiOptions(webApiUrl.Value, authorization);

                    ContactAgent ca = new ContactAgent(config);
                    ContactEntity = await ca.GetContactEntityAsync(SearchId);
                }
            }
        }
Esempio n. 5
0
 /// <summary>
 /// DI Constructor
 /// </summary>
 public DevicesController(DevicesDataManager eventDataManager, EventClustersDataManager eventClustersDataManager,
                          IOptions <WebApiOptions> config, IMassTransitServiceBus serviceBus)
 {
     _config                   = config.Value;
     _devicesDataManager       = eventDataManager;
     _eventClustersDataManager = eventClustersDataManager;
     _serviceBus               = serviceBus;
 }
        private TenantStatus GetTenantStatus(Tenant tenant)
        {
            WebApiOptions session = new WebApiOptions(tenant.WebApiUrl);

            // no authorization necessary for getting tenant status...

            var agent = new ApiAgent(session);

            return(agent.GetTenantStatusAsync(tenant.ContextIdentifier, tenant.Environment.Current).Result);
        }
        private async Task <StringDictionary> GetSystemInfo(Tenant tenant)
        {
            WebApiOptions session = new WebApiOptions(tenant.WebApiUrl);

            // no authorization necessary for getting system info...

            var agent = new ApiAgent(session);

            return(await agent.GetApiVersionAsync());
        }
Esempio n. 8
0
        public Client(ILogger <Client <TViewModel> > logger, IOptionsMonitor <WebApiOptions> options, HttpClient client)
        {
            Logger    = logger ?? throw new ArgumentNullException(nameof(logger));
            options   = options ?? throw new ArgumentNullException(nameof(options));
            Options   = options.CurrentValue ?? throw new NullReferenceException(nameof(options.CurrentValue));
            ApiClient = client ?? throw new ArgumentNullException(nameof(client));

            ApiClient.BaseAddress = new Uri(Options.BaseUrl);
            ApiClient.DefaultRequestHeaders.Accept.Clear();
            ApiClient.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }
Esempio n. 9
0
        /// <summary>
        /// DI Constructor
        /// </summary>
        public ReportDataManager(IOptions <WebApiOptions> config,
                                 ICosmosDBRepository <ResponseDAO> repoResponses,
                                 ICosmosDBRepository <EventClusterDAO> repoEventClusters,
                                 ICosmosDBRepository <ChatReportDAO> repoChatReports)
        {
            _config            = config.Value;
            _repoResponses     = repoResponses;
            _repoEventClusters = repoEventClusters;
            _repoChatReports   = repoChatReports;

            _mappingConversationColumns = new Dictionary <string, int>();
            _mappingUserColumns         = new Dictionary <string, int>();
            _mappingEventColumns        = new Dictionary <string, int>();
            SetupMappingTable();
        }
Esempio n. 10
0
        public Startup(
            IConfiguration configuration,
            IHostingEnvironment environment,
            ILoggerFactory loggerFactory,
            Func <HttpMessageHandler> messageHandlerFactory = null)
        {
            this._logger                = loggerFactory.CreateLogger <Startup>();
            this._environment           = environment;
            this._configuration         = configuration;
            this._modulesStartup        = new ModulesStartup(configuration);
            this._messageHandlerFactory = messageHandlerFactory;

            this._applicationOptions = this._configuration.GetSection("App")
                                       .Get <ApplicationOptions>() ?? new ApplicationOptions();

            this._webApiOptions = this._configuration.GetSection("WebApi")
                                  .Get <WebApiOptions>() ?? new WebApiOptions();
        }
        public static void AddAuthentication(
            this IServiceCollection services,
            WebApiOptions webApiOptions,
            Func <HttpMessageHandler> messageHandlerFactory = null)
        {
            Assembly assembly = typeof(StartupAuthentication)
                                .GetTypeInfo().Assembly;

            services
            .AddAuthentication()
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = webApiOptions.AutorityUrl;

                // TODO: extract to string extension
                options.RequireHttpsMetadata =
                    webApiOptions.AutorityUrl.IndexOf("https") > -1;

                // TODO: move to constants
                options.ApiName   = WebApiConstants.ApiName;
                options.ApiSecret = webApiOptions.ApiSecret;

                // Set message handler, mostly used for integration tests
                if (messageHandlerFactory != null)
                {
                    HttpMessageHandler messageHandler =
                        messageHandlerFactory();

                    options.IntrospectionDiscoveryHandler = messageHandler;
                    options.IntrospectionDiscoveryHandler = messageHandler;
                    options.JwtBackChannelHandler         = messageHandler;
                }
            });

            services
            .AddAuthorization(options =>
            {
                options.AddScopePolicies <WebApiController>(
                    webApiOptions.AutorityUrl,
                    assembly: assembly,
                    fromReferenced: true
                    );
            });
        }
Esempio n. 12
0
        public Client(ClientSettings settings, ClientVariables variables, RestartCallback restartCb, WebApiOptions?webOptions = null, CancellationToken cancel = default) : base(cancel)
        {
            settings.Validate();

            // 設定とデータをコピーする
            this.Settings  = settings._CloneDeep();
            this.Variables = variables._CloneDeep();

            this.StartupParams = new OneLineParams(variables.CurrentInstanceArguments._NonNull());

            this.Report_ForceGc = this.StartupParams._HasKey(Consts.DaemonArgKeys.ForceGc);

            // Web オプションを設定する
            if (webOptions == null)
            {
                webOptions = new WebApiOptions();
            }

            if (settings.ServerCertSha._IsEmpty())
            {
                webOptions.Settings.SslAcceptAnyCerts = true;
            }
            else
            {
                webOptions.Settings.SslAcceptCertSHAHashList.Clear();
                webOptions.Settings.SslAcceptCertSHAHashList.Add(settings.ServerCertSha);
                webOptions.Settings.SslAcceptAnyCerts = false;
            }

            // Proxy の利用設定
            webOptions.Settings.UseProxy = settings.UseProxy;

            // RPC Client を作成する
            this.RpcClient = new JsonRpcHttpClient(this.Settings.ServerUrl._NullCheck(), webOptions);

            // RPC インターフェイスを作成する
            this.Rpc = this.RpcClient.GenerateRpcInterface <IRpc>();

            this.RestartCb = restartCb;

            // メインループを開始する
            this.StartMainLoop(MainLoopAsync);
        }
        private async Task <PersonEntity> GetPersonEntityAsync(int personId, Tenant tenant)
        {
            // maybe the tenant canceled their subscription...
            // make sure the tenant is running (not off-line or in backup or maintenance mode)

            var tenantStatus = GetTenantStatus(tenant);

            if (tenantStatus.IsRunning)
            {
                var config = new WebApiOptions(tenant.WebApiUrl);
                config.Authorization = GetAccessTokenAuthorization();


                var personAgent = new PersonAgent(config);
                return(await personAgent.GetPersonEntityAsync(personId));
            }

            return(null);
        }
        /// <summary>
        /// Uses the bitcoin chain.
        /// </summary>
        /// <param name="forgeBuilder">The forge builder.</param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IForgeBuilder UseApi(this IForgeBuilder forgeBuilder, Action <WebApiOptions>?options = null)
        {
            var optionsInstance = new WebApiOptions();

            options?.Invoke(optionsInstance);
            optionsInstance.DiscoverControllers();

            forgeBuilder.AddShard <WebApiShard, WebApiSettings>((context, services) =>
            {
                if (optionsInstance.EnablePublicApi)
                {
                    services.AddApiServiceDefinition(new ApiServiceDefinition
                    {
                        Enabled     = context.GetShardSettings <WebApiSettings>() !.Enabled,
                        Area        = WebApiArea.AREA_API,
                        Name        = "API",
                        Description = optionsInstance.PublicApiDescription,
                        Version     = "v1",
                    });
                }
Esempio n. 15
0
    public WideTunnelOptions(string svcName, string nameSuite, IEnumerable <string> entryUrlList, IEnumerable <Certificate> masterCertificates, ReadOnlyMemory <byte> clientId = default, ReadOnlyMemory <byte> waterMark = default, WebApiOptions?webApiOptions = null, string?controllerGateSecretKey = null, TcpIpSystem?tcpIp = null)
    {
        if (clientId.IsEmpty)
        {
            clientId = GenNewClientId();
        }
        if (waterMark.IsEmpty)
        {
            waterMark = CoresConfig.WtcConfig.DefaultWaterMark;
        }
        if (webApiOptions == null)
        {
            webApiOptions = new WebApiOptions(
                new WebApiSettings
            {
                AllowAutoRedirect = false,
                Timeout           = CoresConfig.WtcConfig.WpcTimeoutMsec,
            },
                tcpIp, false);
        }

        if (clientId.Length != 20)
        {
            throw new ArgumentException($"{nameof(clientId)} must be 20 bytes.");
        }
        if (tcpIp == null)
        {
            tcpIp = LocalNet;
        }

        this.NameSuite = nameSuite;

        SvcName                      = svcName._NonNullTrim();
        ClientId                     = clientId;
        this.EntryUrlList            = entryUrlList.Distinct(StrComparer.IgnoreCaseTrimComparer).OrderBy(x => x, StrComparer.IgnoreCaseTrimComparer).ToList();
        this.TcpIp                   = tcpIp;
        this.WebApiOptions           = webApiOptions;
        this.WaterMark               = waterMark;
        this.MasterCertificates      = masterCertificates;
        this.ControllerGateSecretKey = controllerGateSecretKey._NonNullTrim();
    }
        /// <summary>
        /// 添加webapi,会将api token 提供者注册好的
        /// </summary>
        /// <param name="services"></param>
        /// <param name="action"></param>
        public static void AddWebApi(this IServiceCollection services, Action <WebApiOptions> action)
        {
            var apiOptions = new WebApiOptions();

            action?.Invoke(apiOptions);
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = GetSigningKey(apiOptions.SecretKey),
                ValidateIssuer           = true,
                ValidIssuer      = apiOptions.ValidIssuer,   //EntityAbstract
                ValidateAudience = true,
                ValidAudience    = apiOptions.ValidAudience, //EntityAbstractAudience
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.Zero,
            };

            services.Configure <TokenProviderOptions>(options =>
            {
                options.Issuer             = apiOptions.Issuer;
                options.Audience           = apiOptions.Audience;
                options.SigningCredentials = new SigningCredentials(GetSigningKey(apiOptions.SecretKey), SecurityAlgorithms.HmacSha256);
            })
            .AddAuthorization(options =>
            {
                apiOptions.PolicyBuilder(options);
            })
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = apiOptions.UseHttps; //不使用https
                options.Audience                  = apiOptions.Audience; //??
                options.ClaimsIssuer              = apiOptions.Issuer;
                options.TokenValidationParameters = tokenValidationParameters;
                options.SaveToken                 = true;
            });
        }
Esempio n. 17
0
    /// <summary>
    /// Adds the Piranha Api module.
    /// </summary>
    /// <param name="services">The current service collection</param>
    /// <param name="configure">The optional api configuration</param>
    /// <returns>The services</returns>
    public static IServiceCollection AddPiranhaApi(this IServiceCollection services,
                                                   Action <WebApiOptions> configure = null)
    {
        // Configure the api module
        var options = new WebApiOptions();

        configure?.Invoke(options);
        Module.AllowAnonymousAccess = options.AllowAnonymousAccess;

        // Add the api module
        Piranha.App.Modules.Register <Piranha.WebApi.Module>();

        // Setup authorization policies
        services.AddAuthorization(o => {
            // Media policies
            o.AddPolicy(Permissions.Media, policy => {
                policy.RequireClaim(Permissions.Media, Permissions.Media);
            });

            // Page policies
            o.AddPolicy(Permissions.Pages, policy => {
                policy.RequireClaim(Permissions.Pages, Permissions.Pages);
            });

            // Posts policies
            o.AddPolicy(Permissions.Posts, policy => {
                policy.RequireClaim(Permissions.Posts, Permissions.Posts);
            });

            // Sitemap policies
            o.AddPolicy(Permissions.Sitemap, policy => {
                policy.RequireClaim(Permissions.Sitemap, Permissions.Sitemap);
            });
        });

        // Return the service collection
        return(services);
    }
Esempio n. 18
0
        /// <summary>
        /// Starts the actual application.
        /// </summary>
        /// <param name="args">The arguments for the application.</param>
        /// <param name="usesShadowCopying">A flag indicating whether shadow copying should be used.</param>
        /// <returns>
        /// The return code for the application.
        /// </returns>
        public int Run(string[] args, bool usesShadowCopying)
        {
            // Parse the command line arguments
            var webOptions  = new WebApiOptions();
            var consoleArgs = new ConsoleRunnerArguments();
            var opts        = new OptionSet();

            opts.Add("h|?|help", "display this help screen", v => consoleArgs.ShowHelp = v != null)
            .Add("c|config=", "the configuration file to use (defaults to ccnet.conf)", v => consoleArgs.ConfigFile = v)
            .Add("r|remoting=", "turn remoting on/off (defaults to on)", v => consoleArgs.UseRemoting                = v == "on")
            .Add("p|project=", "the project to integrate (???)", v => consoleArgs.Project                            = v)
            .Add("v|validate", "validate the configuration file and exit", v => consoleArgs.ValidateConfigOnly       = v != null)
            .Add("l|logging=", "turn logging on/off (defaults to on)", v => consoleArgs.Logging                      = v == "on")
            .Add("sc|shadowCopy=", "turn shadow copying on/off (defaults to on)", v => usesShadowCopying             = v == "on")
            .Add("e|errorpause=", "turn pause on error on/off (defaults to on)", v => consoleArgs.PauseOnError       = v == "on")
            .Add("we|webEndPoint=", "the base endpoint for the web API (default none)", v => webOptions.BaseEndpoint = v);
            try
            {
                opts.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(1);
            }

            // Display the help
            if (consoleArgs.ShowHelp)
            {
                DisplayHelp(opts);
                return(0);
            }

            ICruiseServerFactory factory = null;

            try
            {
                // Start the actual console runner
                if (webOptions.IsConfigured)
                {
                    var apiFactory = new WebApiServerFactory();
                    apiFactory.StartWebApi(apiFactory, webOptions);
                    factory = apiFactory;
                }
                else
                {
                    factory = new CruiseServerFactory();
                }

                runner = new ConsoleRunner(consoleArgs, factory);
                if (!usesShadowCopying)
                {
                    Log.Warning("Shadow-copying has been turned off - hot-swapping will not work!");
                }

                runner.Run();
                return(0);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                if (consoleArgs.PauseOnError)
                {
                    Console.WriteLine("An unexpected error has caused the console to crash");
                    Console.ReadKey();
                }
                return(2);
            }
            finally
            {
                // Clean up
                runner = null;
                var disposable = factory as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Esempio n. 19
0
        public ActionResult New()
        {
            //BE.EPerfiles objResult;
            ViewBag.Title   = "Register Profile";
            ViewBag.Confirm = string.Format(MessageResource.SaveConfirm, "Profile");

            ProfileViewModel ViewProfile = new ProfileViewModel();

            try
            {
                BE.Session objSession = new BE.Session()
                {
                    UserId = AutenticationManager.GetUser().IdUsuario,
                };

                ViewBag.Estado = Extension.GetStatus().Select(x => new SelectListItem
                {
                    Value = x.Id,
                    Text  = x.Value
                });

                List <ResulOptionProfileViewModel> ListOptionProfile = new List <ResulOptionProfileViewModel>();

                ViewProfile.ProfileId = 0;
                ViewProfile.Profile   = "";
                ViewProfile.Status    = "1";

                List <BE.MOptions> options = new List <BE.MOptions>();
                BE.MOptions        option  = new BE.MOptions();
                option.ProfileId = 0;

                options = new WebApiOptions().GetOptionsByProfile(option, objSession);

                ResulOptionProfileViewModel oOptionProfile = new ResulOptionProfileViewModel();

                foreach (BE.MOptions item in options)
                {
                    oOptionProfile                = new ResulOptionProfileViewModel();
                    oOptionProfile.ProfileId      = item.ProfileId;
                    oOptionProfile.OptionId       = item.OptionId;
                    oOptionProfile.FlagActive     = item.FlagActive;
                    oOptionProfile.Title          = item.Title;
                    oOptionProfile.TitleSubModule = item.TitleSubModule;
                    oOptionProfile.TitleModule    = item.TitleModule;

                    if (item.FlagActive.ToString().Equals("1"))
                    {
                        oOptionProfile.FlagCheck = "true";
                    }
                    else
                    {
                        oOptionProfile.FlagCheck = "false";
                    }

                    ListOptionProfile.Add(oOptionProfile);
                }

                ViewProfile.Result = ListOptionProfile;
            }
            catch (Exception)
            {
                ModelState.AddModelError("viewError", MessageResource.PartialViewLoadError);
                return(View("_ErrorView"));
            }
            return(PartialView("Register", ViewProfile));
        }
Esempio n. 20
0
        /// <summary>
        /// 加入jwt验证
        /// </summary>
        /// <param name="services"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static AuthenticationBuilder AddJwt(this IServiceCollection services, Action <WebApiOptions> options = null)
        {
            var apiOptions = new WebApiOptions();

            options?.Invoke(apiOptions);
            var s = services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
                    .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = apiOptions.UseHttps;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    LifetimeValidator = (before, expires, token, param) =>
                    {
                        return(expires > DateTime.UtcNow);
                    },
                    RequireExpirationTime = true,
                    ValidIssuer           = apiOptions.Issuer,
                    ValidAudience         = apiOptions.Audience,
                    IssuerSigningKey      = GetSigningKey(apiOptions.SecretKey),
                    ValidateAudience      = false,
                    ValidateIssuer        = false,
                    ValidateActor         = false,
                    ValidateLifetime      = true,
                    ClockSkew             = TimeSpan.Zero // remove delay of token when expire
                };
                //cfg.Events = new JwtBearerEvents
                //{
                //    OnMessageReceived = context =>
                //    {
                //        context.Token = context.Request.Query["access_token"];
                //        if (context.Token==null)
                //        {
                //            var r = context.HttpContext.Request.Headers["Authorization"].ToArray();
                //            if (r != null && r.Length > 0)
                //            {
                //                context.Token = r[0];
                //            }
                //        }

                //        return Task.CompletedTask;
                //    }
                //};
            });

            services.Configure <WebApiSettings>(opt =>
            {
                opt.SecretKey = apiOptions.SecretKey;
                opt.Host      = apiOptions.Issuer;
            });
            services.Configure <TokenProviderOptions>(o =>
            {
                o.Issuer             = apiOptions.ValidIssuer;
                o.Audience           = apiOptions.ValidAudience;
                o.SigningCredentials = new SigningCredentials(GetSigningKey(apiOptions.SecretKey), SecurityAlgorithms.HmacSha256);
            });
            return(s);
        }
Esempio n. 21
0
        /// <summary>
        /// Starts the actual application.
        /// </summary>
        /// <param name="args">The arguments for the application.</param>
        /// <param name="usesShadowCopying">A flag indicating whether shadow copying should be used.</param>
        /// <returns>
        /// The return code for the application.
        /// </returns>
        public int Run(string[] args, bool usesShadowCopying)
        {
            // Parse the command line arguments
            var webOptions = new WebApiOptions();
            var consoleArgs = new ConsoleRunnerArguments();
            var opts = new OptionSet();
            opts.Add("h|?|help", "display this help screen", v => consoleArgs.ShowHelp = v != null)
                .Add("c|config=", "the configuration file to use (defaults to ccnet.conf)", v => consoleArgs.ConfigFile = v)
                .Add("r|remoting=", "turn remoting on/off (defaults to on)", v => consoleArgs.UseRemoting = v == "on")
                .Add("p|project=", "the project to integrate (???)", v => consoleArgs.Project = v)
                .Add("v|validate", "validate the configuration file and exit", v => consoleArgs.ValidateConfigOnly = v != null)
                .Add("l|logging=", "turn logging on/off (defaults to on)", v => consoleArgs.Logging = v == "on")
                .Add("sc|shadowCopy=", "turn shadow copying on/off (defaults to on)", v => usesShadowCopying = v == "on")
                .Add("e|errorpause=", "turn pause on error on/off (defaults to on)", v => consoleArgs.PauseOnError = v == "on")
                .Add("we|webEndPoint=", "the base endpoint for the web API (default none)", v => webOptions.BaseEndpoint = v);
            try
            {
                opts.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return 1;
            }

            // Display the help
            if (consoleArgs.ShowHelp)
            {
                DisplayHelp(opts);
                return 0;
            }

            ICruiseServerFactory factory = null;
            try
            {
                // Start the actual console runner
                if (webOptions.IsConfigured)
                {
                    var apiFactory = new WebApiServerFactory();
                    apiFactory.StartWebApi(apiFactory, webOptions);
                    factory = apiFactory;
                }
                else
                {
                    factory = new CruiseServerFactory();
                }

                runner = new ConsoleRunner(consoleArgs, factory);
                if (!usesShadowCopying)
                {
                    Log.Warning("Shadow-copying has been turned off - hot-swapping will not work!");
                }

                runner.Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                if (consoleArgs.PauseOnError)
                {
                    Console.WriteLine("An unexpected error has caused the console to crash");
                    Console.ReadKey();
                }
                return 2;
            }
            finally
            {
                // Clean up 
                runner = null;
                var disposable = factory as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Esempio n. 22
0
        public ActionResult GetMenu(string id, PerfilViewModel model)
        {
            PanelViewModel  modelObj  = new PanelViewModel();
            List <MOptions> lstResult = null;
            List <MOptions> lstQuery;
            string          strController = string.Empty;
            MOptions        entOpciones   = new MOptions();
            UserIdentity    objUserIdenty = AutenticationManager.GetUser();

            Session objSession = new Session()
            {
                UserId = AutenticationManager.GetUser().IdUsuario,
            };

            entOpciones.ProfileId = Convert.ToInt32(id);
            lstResult             = new WebApiOptions().GetOptions(entOpciones, objSession);

            AutenticationManager.SetOpciones(lstResult);
            AutenticationManager.SetPerfil(Convert.ToInt32(id));

            modelObj.PerfilId = id;

            lstQuery = lstResult.Where(x => x.Action == 1).ToList();

            modelObj.Items = new List <PanelTab>();

            foreach (var item in lstQuery)
            {
                PanelTab pnlTab = new PanelTab();
                pnlTab.Items = new List <PanelTabItem>();

                pnlTab.Id   = "p" + item.OptionId.ToString();
                pnlTab.Text = item.Title;

                var lstN2 = lstResult.Where(a => a.Action == 2 && a.IdFather == item.OptionId);
                foreach (var itemN2 in lstN2)
                {
                    PanelTabItem pnlTabItem = new PanelTabItem()
                    {
                        Id          = itemN2.OptionId.ToString(),
                        Text        = itemN2.Title,
                        IsSeparator = true
                    };

                    pnlTab.Items.Add(pnlTabItem);

                    var lstN3 = lstResult.Where(a => a.Action == 3 && a.IdFather == itemN2.OptionId);
                    foreach (var itemN3 in lstN3)
                    {
                        pnlTab.Items.Add(new PanelTabItem()
                        {
                            Id     = itemN3.OptionId.ToString(),
                            Text   = itemN3.Title,
                            Action = string.IsNullOrEmpty(itemN3.Link) ? "" : itemN3.Link
                        });
                    }
                }

                modelObj.Items.Add(pnlTab);
            }

            return(PartialView("_TabMenu", modelObj));
        }