public async Task <StorageFile> WriteableBitmapSaveToFile(WriteableBitmap combine_wb)
        {
            if (combine_wb == null)
            {
                return(null);
            }

            var storageManager = await LocalCacheManager.InitializeAsync(StorageFolderType.Pictures);

            var         filename = "ink" + SecurityHelper.MD5(DateTime.Now.ToString(("yyyy-MM-dd HH:mm:ss fff"))) + ".jpg";
            var         path     = Path.Combine(storageManager.CurrentFolder.Path, filename);
            var         md5Name  = DownloadHelper.GetDownloadedLocalFileName(path);
            StorageFile file     = await storageManager.CurrentFolder.CreateFileAsync(md5Name, CreationCollisionOption.ReplaceExisting);

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                //await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);

                SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, combine_wb.PixelWidth, combine_wb.PixelHeight);
                softwareBitmap.CopyFromBuffer(combine_wb.PixelBuffer);

                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream);

                encoder.SetSoftwareBitmap(softwareBitmap);
                await encoder.FlushAsync();
            }
            return(file);
        }
Пример #2
0
        private static void AddCache()
        {
            var  startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long timeStamp = (long)(DateTime.Now - startTime).TotalSeconds;

            LocalCacheManager.Add("dynamic", new { userid = "*****@*****.**", pwd = "123456", uid = "jiangy", exp_in = timeStamp });
        }
Пример #3
0
        public async Task <ActionResult> WorkLogin(string nonce)
        {
            var        errmsg  = string.Empty;
            OAuthModel token   = null;
            var        errcode = 0;

            try
            {
                var user = LocalCacheManager.Get <User>(nonce);
                if (user == null)
                {
                    throw new Exception("nonce 无效或已过期");
                }
                LocalCacheManager.Remove(nonce);
                if (string.IsNullOrEmpty(user.WorkUserId))
                {
                    //记录日志
                    throw new Exception("用户未绑定业务系统账号,请联系管理员");
                }
                //根据OAuth2.0 颁发令牌
                token = await GetTokenAsync(user);

                if (token == null)
                {
                    throw new Exception("令牌获取失败");
                }
            }
            catch (Exception ex)
            {
                errcode = 500;
                errmsg  = ex.Message;
            }

            return(Content(JsonHandler.ToJson(new { errmsg, errcode, token })));
        }
        public async void InitFromUrl(string imageUrl)
        {
            ProgressAction(true);

            if (await StorageHelper.FileExistsAsync(imageUrl))
            {
                this.sourcefile = await StorageHelper.TryGetFileFromPathAsync(imageUrl);

                await InitDrawArea();

                ProgressAction(false);

                return;
            }

            var tcs            = new TaskCompletionSource <PictureEditor>();
            var storageManager = await LocalCacheManager.InitializeAsync(StorageFolderType.Pictures);

            DownloadHelper.DownloadAsync(imageUrl, storageManager.CurrentFolder, async(path, url) =>
            {
                if (imageUrl == url)
                {
                    this.sourcefile = await StorageHelper.TryGetFileFromPathAsync(path);

                    await InitDrawArea();
                }
                else
                {
                }

                ProgressAction(false);
            });
        }
Пример #5
0
        public void GetDynamicCache_Dynamic_DynamicIsNotNull()
        {
            var obj = LocalCacheManager.Get <dynamic>("dynamic");

            Console.WriteLine(obj.userid);
            Console.WriteLine(obj.pwd);
        }
Пример #6
0
        public ActionResult WorkLogin(string nonce, string returnUrl = null, string appcode = null)
        {
            var user = LocalCacheManager.Get <User>(nonce);

            try
            {
                if (user == null)
                {
                    throw new Exception("nonce 无效或已过期");
                }
                if (string.IsNullOrEmpty(user.WorkUserId))
                {
                    throw new ArgumentNullException(nameof(user.WorkUserId));
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("error", "home", new { errmsg = ex.Message, appcode }));
            }
            ViewBag.AppCode   = appcode;
            ViewBag.WebSite   = "http://meunsc.oicp.net";
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.Nonce     = nonce;
            return(View());
        }
Пример #7
0
 // Use this for initialization
 void Start()
 {
     State = GameState.Invalid;
     LoadConfig();
     LocalCacheManager        = new LocalCacheManager("0");
     m_gameRunTimeData        = new GameRunTimeData(this);
     GameRunTimeData.Instance = m_gameRunTimeData;
     m_gameRunTimeData.State  = State;
     m_uiManager.Initialize(m_gameRunTimeData);
     StartCoroutine(InitializeControllerByArgs());
     StartCoroutine(LoadGameStateAsync(m_startState));
 }
Пример #8
0
    private IEnumerator Initialze()
    {
        State = GameState.Invalid;
        yield return(StartCoroutine(LoadConfig()));

        LocalCacheManager        = new LocalCacheManager("0");
        m_gameRunTimeData        = new GameRunTimeData(this);
        ColorProvider            = GetComponent <ColorProvider>();
        GameRunTimeData.Instance = m_gameRunTimeData;
        m_gameRunTimeData.State  = State;
        m_uiManager.Initialize(m_gameRunTimeData);
        StartCoroutine(InitializeControllerByArgs());
        ChangeGameState(m_startState);
    }
Пример #9
0
        protected DataRepository(RedisCacheManager redisCacheManager, LocalCacheManager localCacheManager,
                                 TDbContext dbCtx, RedisBusHandler busHandler, Type dataType, RepositorySetup setup)
        {
            this.redisCacheManager = redisCacheManager;
            this.localCacheManager = localCacheManager;
            this.dbContext         = dbCtx;
            this.typeName          = dataType.FullName;
            this.hashSetKey        = $"hashset-{typeName}-{setup.EnvironnementPrefix}";
            this.busHandler        = busHandler;
            this.setup             = setup;

            UseDistributedCache = true;
            UseLocalCache       = true;
            UseBus = true;
        }
Пример #10
0
        public static void Register()
        {
            IWeChatAppService         appService    = AutofacManager.Resolve <IWeChatAppService>();
            IApplicationConfigService configService = AutofacManager.Resolve <IApplicationConfigService>();
            var config = configService.ListApplicationConfig()
                         .FirstOrDefault(m => m.ConfigType.ToLower() == Constants.WECHAT.ToLower() && m.ConfigKey.ToLower() == Constants.CORP_ID.ToLower());

            LocalCacheManager.Add(Constants.CORP_ID, config.ConfigValue);

            List <WeChatAppConfig> apps = appService.ListApps();

            apps.ForEach(app =>
            {
                WeChatManager.RegisterWorkApp(config.ConfigValue, app.SecretValue, app.AppName);
            });
        }
Пример #11
0
        public void Initialize()
        {
            LocalCacheManager.Add(Constants.CORP_ID, "wx2e8cc6975a5fa1ce");
            var connstr = "server=.;database=dev;uid=sa;pwd=123456";
            ContainerBuilder builder = new ContainerBuilder();

            builder.RegisterType <WeChatAppService>().As <IWeChatAppService>();
            builder.RegisterType <ApplicationConfigService>().As <IApplicationConfigService>();
            builder.RegisterType <MemberService>().As <IMemberService>();
            builder.RegisterType <WeChatAppRepository>().As <IWeChatAppRepository>();
            builder.RegisterType <ApplicationConfigRepository>().As <IApplicationConfigRepository>();
            builder.RegisterType <CorpAppService>().As <ICorpAppService>();
            builder.RegisterInstance(EFContext.CreateForEFDesignTools(connstr));
            container = builder.Build();
            Register();
            AddCache();
        }
Пример #12
0
    public override bool Authorize(IPrincipal principal, string context)
    {
        bool ret = false;

        if (principal.Identity.IsAuthenticated)
        {
            // check the security item key, otherwise check the screen uri
            ret = LocalCacheManager.GetUserSecurityItemsCache(LocalUserManager.UserId, false).Exists(
                si => si.SecurityItemKey.Equals(context, StringComparison.InvariantCultureIgnoreCase));
            if (!ret)
            {
                // check if this item matches a screen uri
                ret = LocalCacheManager.GetUserSecurityItemsCache(LocalUserManager.UserId, false).Exists(
                    si => si.Uri.Equals(context, StringComparison.InvariantCultureIgnoreCase));
            }
        }
        return(ret);
    }
Пример #13
0
 /// <summary>
 /// 消费临时code 换取微信应用信息
 /// </summary>
 /// <param name="code">临时授权码code</param>
 /// <param name="appcode">应用code</param>
 /// <param name="returnUrl">返回url</param>
 /// <returns></returns>
 public ActionResult ConsumeCode(string code, string appcode, string returnUrl = null)
 {
     try
     {
         User user = null;
         if (string.IsNullOrEmpty(appcode))
         {
             throw new ArgumentNullException(nameof(appcode));
         }
         var app         = _currentService.GetApp(appcode);
         var accessToken = AccessTokenContainer.GetToken(corpId, app.SecretValue);
         var result      = OAuth2Api.GetUserId(accessToken, code);
         if (!string.IsNullOrEmpty(result.OpenId))
         {
             //成员未关注该企业微信
             throw new Exception("成员未关注该企业微信");
         }
         else if (!string.IsNullOrEmpty(result.UserId))
         {
             //通过企业微信usesrid 换 业务系统账号密码
             user = _accountService.FindUserByWxUserID(result.UserId);
             if (user == null)
             {
                 //微信用户未绑定对应业务系统账号
                 return(RedirectToAction("login", "account", new { returnUrl, appcode, workUserId = result.UserId }));
             }
             else
             {
                 var nonceStr = Guid.NewGuid().ToString().Replace("-", "");
                 LocalCacheManager.Add(nonceStr, user);
                 //微信网页授权成功 准备获取企业应用授权
                 return(RedirectToAction("worklogin", "account", new { nonce = nonceStr, appcode, returnUrl }));
             }
         }
         else
         {
             throw new Exception(result.errmsg);
         }
     }
     catch (Exception ex)
     {
         return(RedirectToAction("error", "home", new { errmsg = ex.Message, appcode }));
     }
 }
Пример #14
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Executes in two distinct scenarios.
        /// 1. If disposing is true, the method has been called directly
        /// or indirectly by a user's code via the Dispose method.
        /// Both managed and unmanaged resources can be disposed.
        /// 2. If disposing is false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference (access)
        /// other managed objects, as they already have been garbage collected.
        /// Only unmanaged resources can be disposed.
        /// </summary>
        /// <param name="disposing">if set to <c>true</c> this method is called from the
        /// Dispose() method, if set to <c>false</c> it's called from finalizer.</param>
        /// <remarks>
        /// If any exceptions are thrown, that is fine.
        /// If the method is being done in a finalizer, it will be ignored.
        /// If it is thrown by client code calling Dispose,
        /// it needs to be handled by fixing the bug.
        /// If subclasses override this method, they should call the base implementation.
        /// </remarks>
        /// ------------------------------------------------------------------------------------
        protected virtual void Dispose(bool disposing)
        {
            if (m_fDisposed)
            {
                return;
            }

            if (disposing)
            {
                // Dispose managed resources here.
                Close();
                if (m_CacheManager != null)
                {
                    m_CacheManager.Dispose();
                }
            }

            // Dispose unmanaged resources here
            m_CacheManager = null;
        }
Пример #15
0
        public override void ProcessRequest(System.Web.HttpContext context)
        {
            string json = LocalCacheManager <string> .Find(_apimethodname + "_json", () =>
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("接口地址:<span style=\"color:blue;\"><a href=\"###\">{0}</a></span><br/><p/>", new Regex("/json$", RegexOptions.IgnoreCase).Replace(context.Request.Url.AbsolutePath, ""));
                sb.AppendFormat("接口功能:<span style=\"color:blue;\">{0}</span><br/><p/>", _hander.ApiMethodProp.Function ?? string.Empty);
                sb.Append("<font>接口数据序列化格式:json</font><br/><p/>");
                sb.Append("请求参数:<br/>");

                sb.Append("<table style=\"border:solid 1px yellow;\" border=\"1\">");
                sb.AppendFormat("<tr><th>参数名</th><th>参数类型</th><th>备注</th></tr>");
                EntityBufCore.GetPropToTable(_hander._requestType, sb);
                sb.Append("</table>");
                //context.Response.Write(string.Format("{0}", sb.ToString()));

                sb.Append("<br/>");
                sb.Append("响应类型:<br/>");

                sb.Append("<table style=\"border:solid 1px yellow;\" border=\"1\">");
                sb.AppendFormat("<tr><th>参数名</th><th>参数类型</th><th>备注</th></tr>");

                var apiType       = typeof(APIResult <>);
                var apiResultType = (_hander.ApiMethodProp.OutPutContentType == OutPutContentType.apiObject || !_hander.ApiMethodProp.StandApiOutPut) ?
                                    _hander._responseType : apiType.MakeGenericType(new[] { _hander._responseType });

                EntityBufCore.GetPropToTable(apiResultType, sb);
                sb.Append("</table>");

                if (!string.IsNullOrWhiteSpace(_ipLimit))
                {
                    sb.Append("<br/>");
                    sb.AppendFormat("<div style='font-weight:bold;color:red;'>ip限制:{0}</div>", _ipLimit);
                }

                return(sb.ToString());
            }, 1440);

            context.Response.Write(json);
        }
        public void LoadData(int selectIndex)
        {
            //处理新存档
            if (selectIndex == 0)
            {
                CurrentArchiveData = new PlayerArchiveData();
                CurrentArchiveData.MissionArchieData       = new MissionArchiveData();
                CurrentArchiveData.CgSceneArchiveData      = new CGSceneArchiveData();
                CurrentArchiveData.EvidenceArchiveData     = new EvidenceArchiveData();
                CurrentArchiveData.TipsArchiveData         = new TipsArchiveData();
                CurrentArchiveData.SoundServiceArchiveData = new SoundServiceArchiveData();
                CurrentArchiveData.StoryArchiveData        = new StoryArchiveData();
                m_playTime          = 0;
                CurrentSaveIndex    = 0;
                m_localCacheManager = null;
                EventManager.Instance.SendEvent(new PlayerLoadArchiveEvent());
                return;
            }
            if (m_localCacheManager != null)
            {
                m_localCacheManager.Clear();
            }
            if (ArchivePreviewData.ArchivePreviewData.Count < selectIndex)
            {
                Debug.LogError($"读档错误!!!!未知档:{selectIndex}");
                return;
            }

            var previewData = ArchivePreviewData.ArchivePreviewData[selectIndex - 1];

            m_playTime = previewData.TotalPlayTime;

            CurrentSaveIndex    = selectIndex;
            m_localCacheManager = new LocalCacheManager(GetArchiveName(previewData));
            CurrentArchiveData  = m_localCacheManager.GetData <PlayerArchiveData>();

            EventManager.Instance.SendEvent(new PlayerLoadArchiveEvent());
        }
Пример #17
0
        public void SaveData(int saveIndex)
        {
            if (saveIndex >= 3)
            {
                return;
            }
            if (m_lastSaveInterval <= 1)
            {
                return;
            }
            m_lastSaveInterval = 0;
            bool isNewData = false;

            if (ArchivePreviewData.ArchivePreviewData.Count <= saveIndex)
            {
                isNewData = true;
                ArchivePreviewData.ArchivePreviewData.Add(new ArchivePreviewData());
            }

            var previewData = ArchivePreviewData.ArchivePreviewData[ArchivePreviewData.ArchivePreviewData.Count - 1];

            if (!isNewData)
            {
                PersistentStorage.Delete(GetArchiveName(previewData));
            }
            //TODO:写入存档预览信息
            previewData.SaveTime      = DateTime.Now.Ticks;
            previewData.Img           = "PreviewImg" + saveIndex.ToString();
            previewData.EPName        = MissionSceneManager.Instance.GetCurrentMission().ToString();
            previewData.TotalPlayTime = (int)m_playTime;
            SortArchivePreViewData();
            Data.LocalCacheManager.SetData(ArchivePreviewData);
            m_localCacheManager = new LocalCacheManager(previewData.SaveTime.ToString());
            EventManager.Instance.SendEvent(new PlayerPreSaveArchiveEvent());
            m_localCacheManager.SetData(CurrentArchiveData);
            EventManager.Instance.SendEvent(new PlayerSaveArchiveEvent());
        }
Пример #18
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Executes in two distinct scenarios.
		/// 1. If disposing is true, the method has been called directly
		/// or indirectly by a user's code via the Dispose method.
		/// Both managed and unmanaged resources can be disposed.
		/// 2. If disposing is false, the method has been called by the
		/// runtime from inside the finalizer and you should not reference (access)
		/// other managed objects, as they already have been garbage collected.
		/// Only unmanaged resources can be disposed.
		/// </summary>
		/// <param name="disposing">if set to <c>true</c> this method is called from the
		/// Dispose() method, if set to <c>false</c> it's called from finalizer.</param>
		/// <remarks>
		/// If any exceptions are thrown, that is fine.
		/// If the method is being done in a finalizer, it will be ignored.
		/// If it is thrown by client code calling Dispose,
		/// it needs to be handled by fixing the bug.
		/// If subclasses override this method, they should call the base implementation.
		/// </remarks>
		/// ------------------------------------------------------------------------------------
		protected virtual void Dispose(bool disposing)
		{
			if (m_fDisposed)
				return;

			if (disposing)
			{
				// Dispose managed resources here.
				Close();
				if (m_CacheManager != null)
					m_CacheManager.Dispose();
			}

			// Dispose unmanaged resources here
			m_CacheManager = null;
		}
Пример #19
0
        public void Configuration(IAppBuilder app)
        {
            var applicationInsightsKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");

            if (!string.IsNullOrEmpty(applicationInsightsKey))
            {
                TelemetryConfiguration.Active.InstrumentationKey = applicationInsightsKey;
            }

            if (_managerAssembly != null)
            {
                AreaRegistration.RegisterAllAreas();
                CallChildConfigure(app, _managerAssembly, "VirtoCommerce.Platform.Web.Startup", "Configuration", "~/areas/admin", "admin/");
            }

            var appSettings = ConfigurationManager.AppSettings;

            UnityWebActivator.Start();
            var container = UnityConfig.GetConfiguredContainer();

            UnityServiceLocator locator = new UnityServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => locator);

            //Cure for System.Runtime.Caching.MemoryCache freezing
            //https://www.zpqrtbnk.net/posts/appdomains-threads-cultureinfos-and-paracetamol
            app.SanitizeThreadCulture();
            // Caching configuration
            // Be cautious with SystemWebCacheHandle because it does not work in native threads (Hangfire jobs).
            var localCache        = CacheFactory.FromConfiguration <object>("storefrontCache");
            var localCacheManager = new LocalCacheManager(localCache);

            container.RegisterInstance <ILocalCacheManager>(localCacheManager);

            //Because CacheManagerOutputCacheProvider used diff cache manager instance need translate clear region by this way
            //https://github.com/MichaCo/CacheManager/issues/32
            localCacheManager.OnClearRegion += (sender, region) =>
            {
                try
                {
                    CacheManagerOutputCacheProvider.Cache.ClearRegion(region.Region);
                }
                catch { }
            };
            localCacheManager.OnClear += (sender, args) =>
            {
                try
                {
                    CacheManagerOutputCacheProvider.Cache.Clear();
                }
                catch { }
            };

            var distributedCache = CacheFactory.Build("distributedCache", settings =>
            {
                var jsonSerializerSettings = new JsonSerializerSettings {
                    TypeNameHandling = TypeNameHandling.All
                };
                var redisCacheEnabled = appSettings.GetValue("VirtoCommerce:Storefront:RedisCache:Enabled", false);

                var memoryHandlePart = settings
                                       .WithJsonSerializer(jsonSerializerSettings, jsonSerializerSettings)
                                       .WithUpdateMode(CacheUpdateMode.Up)
                                       .WithSystemRuntimeCacheHandle("memory")
                                       .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(1));

                if (redisCacheEnabled)
                {
                    var redisCacheConnectionStringName = appSettings.GetValue("VirtoCommerce:Storefront:RedisCache:ConnectionStringName", "RedisCache");
                    var redisConnectionString          = ConfigurationManager.ConnectionStrings[redisCacheConnectionStringName].ConnectionString;

                    memoryHandlePart
                    .And
                    .WithRedisConfiguration("redis", redisConnectionString)
                    .WithRetryTimeout(100)
                    .WithMaxRetries(1000)
                    .WithRedisBackplane("redis")
                    .WithRedisCacheHandle("redis", true)
                    .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(1));
                }
            });
            var distributedCacheManager = new DistributedCacheManager(distributedCache);

            container.RegisterInstance <IDistributedCacheManager>(distributedCacheManager);

            var logger = LogManager.GetLogger("default");

            container.RegisterInstance <ILogger>(logger);

            // Create new work context for each request
            container.RegisterType <WorkContext, WorkContext>(new PerRequestLifetimeManager());
            Func <WorkContext> workContextFactory = () => container.Resolve <WorkContext>();

            container.RegisterInstance(workContextFactory);

            // Workaround for old storefront base URL: remove /api/ suffix since it is already included in every resource address in VirtoCommerce.Client library.
            var baseUrl = ConfigurationManager.ConnectionStrings["VirtoCommerceBaseUrl"].ConnectionString;

            if (baseUrl != null && baseUrl.EndsWith("/api/", StringComparison.OrdinalIgnoreCase))
            {
                var apiPosition = baseUrl.LastIndexOf("/api/", StringComparison.OrdinalIgnoreCase);
                if (apiPosition >= 0)
                {
                    baseUrl = baseUrl.Remove(apiPosition);
                }
            }

            var apiAppId     = appSettings["vc-public-ApiAppId"];
            var apiSecretKey = appSettings["vc-public-ApiSecretKey"];

            container.RegisterInstance(new HmacCredentials(apiAppId, apiSecretKey));

            container.RegisterType <VirtoCommerceApiRequestHandler>(new PerRequestLifetimeManager());

            ServicePointManager.UseNagleAlgorithm = false;

            var compressionHandler = new System.Net.Http.HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };

            var baseUri = new Uri(baseUrl);

            container.RegisterType <ICartModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CartModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <ICatalogModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CatalogModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <IContentModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new ContentModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <ICoreModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CoreModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <ICustomerModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new CustomerModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <IInventoryModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new InventoryModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <IMarketingModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new MarketingModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <IOrdersModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new OrdersModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <IPlatformModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new PlatformModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <IPricingModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new PricingModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <IQuoteModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new QuoteModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <ISearchApiModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new SearchApiModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <IStoreModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new StoreModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <ISitemapsModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new SitemapsModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));
            container.RegisterType <ISubscriptionModuleApiClient>(new PerRequestLifetimeManager(), new InjectionFactory(c => new SubscriptionModuleApiClient(baseUri, c.Resolve <VirtoCommerceApiRequestHandler>(), compressionHandler)));

            container.RegisterType <IMarketingService, MarketingServiceImpl>();
            container.RegisterType <IPromotionEvaluator, PromotionEvaluator>();
            container.RegisterType <ITaxEvaluator, TaxEvaluator>();
            container.RegisterType <IPricingService, PricingServiceImpl>();
            container.RegisterType <ICustomerService, CustomerServiceImpl>();
            container.RegisterType <IMenuLinkListService, MenuLinkListServiceImpl>();
            container.RegisterType <ISeoRouteService, SeoRouteService>();

            container.RegisterType <ICartBuilder, CartBuilder>();
            container.RegisterType <IQuoteRequestBuilder, QuoteRequestBuilder>();
            container.RegisterType <ICatalogSearchService, CatalogSearchServiceImpl>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(context => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <IStorefrontUrlBuilder, StorefrontUrlBuilder>(new PerRequestLifetimeManager());

            //Register domain events
            container.RegisterType <IEventPublisher <OrderPlacedEvent>, EventPublisher <OrderPlacedEvent> >();
            container.RegisterType <IEventPublisher <UserLoginEvent>, EventPublisher <UserLoginEvent> >();
            container.RegisterType <IEventPublisher <QuoteRequestUpdatedEvent>, EventPublisher <QuoteRequestUpdatedEvent> >();
            //Register event handlers (observers)
            container.RegisterType <IAsyncObserver <OrderPlacedEvent>, CustomerServiceImpl>("Invalidate customer cache when user placed new order");
            container.RegisterType <IAsyncObserver <QuoteRequestUpdatedEvent>, CustomerServiceImpl>("Invalidate customer cache when quote request was updated");
            container.RegisterType <IAsyncObserver <UserLoginEvent>, CartBuilder>("Merge anonymous cart with loggined user cart");
            container.RegisterType <IAsyncObserver <UserLoginEvent>, QuoteRequestBuilder>("Merge anonymous quote request with loggined user quote");

            var cmsContentConnectionString = BlobConnectionString.Parse(ConfigurationManager.ConnectionStrings["ContentConnectionString"].ConnectionString);
            var themesBasePath             = cmsContentConnectionString.RootPath.TrimEnd('/') + "/" + "Themes";
            var staticContentBasePath      = cmsContentConnectionString.RootPath.TrimEnd('/') + "/" + "Pages";
            //Use always file system provider for global theme
            var globalThemesBlobProvider = new FileSystemContentBlobProvider(ResolveLocalPath("~/App_Data/Themes/default"));
            IContentBlobProvider       themesBlobProvider;
            IStaticContentBlobProvider staticContentBlobProvider;

            if ("AzureBlobStorage".Equals(cmsContentConnectionString.Provider, StringComparison.OrdinalIgnoreCase))
            {
                themesBlobProvider        = new AzureBlobContentProvider(cmsContentConnectionString.ConnectionString, themesBasePath, localCacheManager);
                staticContentBlobProvider = new AzureBlobContentProvider(cmsContentConnectionString.ConnectionString, staticContentBasePath, localCacheManager);
            }
            else
            {
                themesBlobProvider        = new FileSystemContentBlobProvider(ResolveLocalPath(themesBasePath));
                staticContentBlobProvider = new FileSystemContentBlobProvider(ResolveLocalPath(staticContentBasePath));
            }
            container.RegisterInstance <IStaticContentBlobProvider>(staticContentBlobProvider);

            var shopifyLiquidEngine = new ShopifyLiquidThemeEngine(localCacheManager, workContextFactory, () => container.Resolve <IStorefrontUrlBuilder>(), themesBlobProvider, globalThemesBlobProvider, "~/themes/assets", "~/themes/global/assets");

            container.RegisterInstance <ILiquidThemeEngine>(shopifyLiquidEngine);

            //Register liquid engine
            ViewEngines.Engines.Add(new DotLiquidThemedViewEngine(shopifyLiquidEngine));

            // Shopify model binders convert Shopify form fields with bad names to VirtoCommerce model properties.
            container.RegisterType <IModelBinderProvider, ShopifyModelBinderProvider>("shopify");

            //Static content service
            var staticContentService = new StaticContentServiceImpl(shopifyLiquidEngine, localCacheManager, workContextFactory, () => container.Resolve <IStorefrontUrlBuilder>(), StaticContentItemFactory.GetContentItemFromPath, staticContentBlobProvider);

            container.RegisterInstance <IStaticContentService>(staticContentService);
            //Register generate sitemap background job
            container.RegisterType <GenerateSitemapJob>(new InjectionFactory(c => new GenerateSitemapJob(themesBlobProvider, c.Resolve <ISitemapsModuleApiClient>(), c.Resolve <IStorefrontUrlBuilder>())));

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, workContextFactory, () => container.Resolve <CommonController>());
            RouteConfig.RegisterRoutes(RouteTable.Routes, container.Resolve <ISeoRouteService>(), workContextFactory, () => container.Resolve <IStorefrontUrlBuilder>());
            AuthConfig.ConfigureAuth(app, () => container.Resolve <IStorefrontUrlBuilder>());
            container.Resolve <BundleConfig>().RegisterBundles(BundleTable.Bundles);

            //This special binders need because all these types not contains default ctor and Money with Currency properties
            ModelBinders.Binders.Add(typeof(Model.Cart.Shipment), new CartModelBinder <Model.Cart.Shipment>(workContextFactory));
            ModelBinders.Binders.Add(typeof(Model.Cart.Payment), new CartModelBinder <Model.Cart.Payment>(workContextFactory));
            ModelBinders.Binders.Add(typeof(Model.Order.PaymentIn), new OrderModelBinder <Model.Order.PaymentIn>(workContextFactory));

            app.Use <WorkContextOwinMiddleware>(container);
            app.UseStageMarker(PipelineStage.PostAuthorize);
            app.Use <StorefrontUrlRewriterOwinMiddleware>(container);
            app.UseStageMarker(PipelineStage.PostAuthorize);
        }
Пример #20
0
        public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            string json = LocalCacheManager <string> .Find(_apimethodname + "_invoke", () =>
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<html>");
                sb.Append(@"<head><title>接口调用</title><style>
.heading1{background:#003366;margin-top:0px; color:#fff; padding-top:5px; line-height:40px; width:100%;display:block;} 
#datacontainer table {
width:98%;
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #ccc;
border-collapse: collapse;
}
#datacontainer table th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #ccc;
background-color: #dedede;
}
#datacontainer table td {
vertical-align:top;
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #ccc;
background-color: #ffffff;
}
.spanbutton{
  cursor:pointer;
  margin-right:5px;
  font-weight:bold;
  font-size:18px;
  color:#10bd86;

}
h2{margin:0;padding:0;}
#overlay{position:absolute;top:0;left:0;width:100%;height:100%;background: rgba(0, 0, 0, 0.5);display:none;}
#win{position:absolute;top:10%;left:10%;width:80%;height:80%;background:#fff;border:4px solid #ccc;opacity:1;filter:alpha(opacity=100);}
h2{font-size:12px;text-align:right;background:#ccc;border-bottom:3px solid #ccc;padding:5px;}
h2 span{color:#f90;cursor:pointer;background:#fff;border:1px solid #ccc;padding:0 2px;}
#tab1,#tab2 {float:left; width:120px; line-height:25px; margin-right:5px;margin-top:4px; color:#333; background:#eee; text-align:center; cursor:pointer; font-weight:bold;}
#tab1.on,#tab2.on {background:#333; color:#fff;}
textarea {border:0px;}
</style></head>");
                sb.Append("<body style='width:100%;margin:0px;'>");
                sb.Append("<h1 class=\"heading1\">" + (this._hander.ApiMethodProp.Aliname ?? this._apimethodname) + "接口调用</h1>");


                sb.Append("<div id='datacontainer' style=\"width:90%;margin:0 auto;\">");
                EntityBufCore.GetInvokeHtml(_hander._requestType, false, sb);
                //context.Response.Write(string.Format("{0}", sb.ToString()));
                sb.Append("<div style=\"clear:both;\"></div>");
                sb.Append("<div style=\"float:right;margin-top:15px;margin-bottom:50px;padding-right:20px;\"><input type=\"button\" value=\"提 交\" style='width:200px;line-height:30px;' onclick=\"submit()\"/></div>");
                sb.Append("</div>");

                sb.Append("<div id =\"overlay\" >");
                sb.Append("<div id=\"win\"><span id=\"tab1\" onclick=\"changetab('tab1','page1','tab2','page2')\" style='margin-left:10px;'>请求</span><span class='on' onclick=\"changetab('tab2','page2','tab1','page1')\" id=\"tab2\">结果</span><h2><span id =\"close\"> x </span></h2><div id='page1' style=\"width:100%;height:90%;display:none;\"><textarea id=\"sendjsondata\" style=\"width:100%;height:100%;\"></textarea></div><div id='page2' style=\"width:100%;height:90%;\"><textarea id=\"jsondata\" style=\"width:100%;height:100%;\"></textarea></div></div>");
                sb.Append("</div>");

                sb.Append(Functions(new Regex("/invoke$", RegexOptions.IgnoreCase).Replace(request.Url, "")));
                sb.Append("</body>");
                sb.Append("</html>");

                return(sb.ToString());
            }, 1440);

            response.Content    = json;
            response.ReturnCode = 200;

            return(true);
        }
Пример #21
0
        public override bool Process(HttpServer server, HttpRequest request, HttpResponse response)
        {
            string json = LocalCacheManager <string> .Find(_apimethodname + "_json", () =>
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<html>");
                sb.Append(@"<head><title>接口文档</title><style>.heading1{background:#003366;margin-top:0px; color:#fff; padding-top:5px; line-height:40px; width:100%;display:block;} table,pre{ background:#e5e5cc;} table{border-left:solid 1px #ccc;font-size:11px;width:98%;margin-left:5px;border-bottom:none;border-top:solid 1px #ccc;border-right:none;} td,th{border-top:none;border-right:solid 1px #ccc;border-bottom:solid 1px #ccc;} iframe{width:100%; background:#e5e5cc; margin-bottom:15px;}
                      </style></head>");
                sb.Append("<body style='width:100%;margin:0px;padding:0px;'>");
                sb.Append("<h1 class=\"heading1\">" + (this._hander.ApiMethodProp.Aliname ?? this._apimethodname) + "接口文档</h1>");
                sb.AppendFormat("<span class='title'>接口地址:</span><span style=\"color:blue;\"><a href=\"###\">{0}</a></span><br/><p/>", new Regex("/json$", RegexOptions.IgnoreCase).Replace(request.Url, ""));
                sb.AppendFormat("<span class='title'>接口功能:</span><span style=\"color:blue;\">{0}</span><br/><p/>", _hander.ApiMethodProp.Function ?? string.Empty);
                sb.Append("<span class='title'><font>接口数据序列化格式:json</font></span><br/><p/>");
                sb.AppendFormat("<span class='title'>接口请求json示例:</span><span style=\"color:blue;display:none;\"><a href=\"{0}\" target=\"_blank\">{0}</a></span><br/><p/>", new Regex("/json$", RegexOptions.IgnoreCase).Replace(request.Url, "") + "/req");

                sb.AppendFormat("<iframe id=\"req\" frameborder=\"no\" border=\"0\" marginwidth=\"0\" marginheight=\"0\" src=\"{0}/req\"></iframe>", new Regex("/json$", RegexOptions.IgnoreCase).Replace(request.Url, ""));

                sb.AppendFormat("<span class='title'>接口响应json示例:</span><span style=\"color:blue;display:none;\"><a href=\"{0}\" target=\"_blank\">{0}</a></span><br/><p/>", new Regex("/json$", RegexOptions.IgnoreCase).Replace(request.Url, "") + "/resp");

                sb.AppendFormat("<iframe id=\"resp\" frameborder=\"no\" border=\"0\" marginwidth=\"0\" marginheight=\"0\" src=\"{0}/resp\"></iframe>", new Regex("/json$", RegexOptions.IgnoreCase).Replace(request.Url, ""));

                sb.Append("<span class='title'>请求参数说明:</span><p/>");

                sb.Append("<table cellpadding=0 cellspacing=0 border=\"0\">");
                sb.AppendFormat("<tr><th>参数名</th><th>参数类型</th><th>备注</th></tr>");
                EntityBufCore.GetPropToTable(_hander._requestType, sb);
                sb.Append("</table>");
                //context.Response.Write(string.Format("{0}", sb.ToString()));

                sb.Append("<br/>");
                sb.Append("响应类型:<p/>");

                sb.Append("<table cellpadding=0 cellspacing=0 border=\"0\">");
                sb.AppendFormat("<tr><th>参数名</th><th>参数类型</th><th>备注</th></tr>");

                var apiType       = typeof(APIResult <>);
                var apiResultType = (_hander.ApiMethodProp.OutPutContentType == OutPutContentType.apiObject || !_hander.ApiMethodProp.StandApiOutPut) ?
                                    _hander._responseType : apiType.MakeGenericType(new[] { _hander._responseType });

                EntityBufCore.GetPropToTable(apiResultType, sb);
                sb.Append("</table>");

                sb.Append("<br/>");
                sb.AppendFormat("<a href=\"{0}\">接口调用测试</a>", new Regex("/json$", RegexOptions.IgnoreCase).Replace(request.Url, "") + "/invoke");

                if (!string.IsNullOrWhiteSpace(_ipLimit))
                {
                    sb.Append("<br/>");
                    sb.AppendFormat("<div style='font-weight:bold;color:red;'>ip限制:{0}</div>", _ipLimit);
                }

                sb.Append("<p/></p>");
                sb.Append("</body>");
                sb.Append("</html>");

                return(sb.ToString());
            }, 1440);

            response.Content    = json;
            response.ReturnCode = 200;

            return(true);
        }
Пример #22
0
        /// <summary>
        /// Gets the likelihood of crunching based off the genres of various games
        /// a studio has put out.
        /// </summary>
        /// <returns>The genre score.</returns>
        /// <param name="name">The name of the Studio, which is passed to the IGDB API.</param>
        /// <param name="aliases">What it's saved as in the cache. This may differ from the name retrieved from the Giantbomb API.</param>
        /// <param name="DEBUG">Is this Studio in Debug mode?</param>
        public static float[] GetGenreScore(string name, List <string> aliases, bool DEBUG)
        {
            //Log information
            if (Logger.VERBOSE)
            {
                Logger.Log("Finding genre score.");
            }

            //If the Studio is not being forced to recaculate values, check if it
            //exists in the cache. If it does, return the values. Otherwise, continue.
            if (!DEBUG && !MainClass.options.force)
            {
                StudioInfo si = LocalCacheManager.GetCachedInfo(aliases[0]);
                if (si.id != "-1" && !DEBUG)
                {
                    List <float> f = Array.ConvertAll(si.genreArray, x => (float)x).ToList();
                    f.Insert(0, si.GenreScore);
                    return(f.ToArray());
                }
            }

            //Get the genres of all released games from IGDB and return their average as the score.
            int[] genres     = IGDBInterfacer.GetGenres(name);
            int[] genreCount = new int[7];

            Logger.Log(name + ", " + aliases.ToArray().GetString(), Logger.LogLevel.DEBUG, true);

            //Uses a Unit Circle based system.
            float totalX = 0.0f;
            float totalY = 0.0f;

            if (genres != null && genres.Length > 0)
            {
                for (int i = 0; i < genres.Length; i++)
                {
                    //Get the angle because it uses a unit-circle based system.
                    //See the ReadMe or Whitepaper for more info.
                    float angle = (float)((i / 7) * 2 * Math.PI);

                    totalX += genres[i] * (float)Math.Cos(angle);
                    totalY += genres[i] * (float)Math.Sin(angle);

                    genreCount[genres[i]]++;
                }
            }
            else
            {
                //If an exception was thrown, it means the name doesn't exist on IGDB.
                //Then we use the different aliases.

                bool broken = false;
                foreach (string alias in aliases)
                {
                    genres = IGDBInterfacer.GetGenres(alias);

                    //This means this name doesn't exist either, so try the next one.
                    if (genres == null || genres.Length <= 0)
                    {
                        continue;
                    }

                    for (int i = 0; i < genres.Length; i++)
                    {
                        //Get the angle because it uses a unit-circle based system.
                        //See the ReadMe or Whitepaper for more info.
                        float angle = (float)((i / 7) * 2 * Math.PI);

                        totalX += genres[i] * (float)Math.Cos(angle);
                        totalY += genres[i] * (float)Math.Sin(angle);

                        genreCount[genres[i]]++;
                    }

                    broken = true;
                    break;
                }

                //If no genres were found, throw an exception.
                if (!broken)
                {
                    throw new Exception(name + " doesn't exist in IGDB!");
                }
            }

            //Average
            totalX /= genres.Length;
            totalY /= genres.Length;

            //Normalize
            float hyp = (float)Math.Sqrt((totalX * totalX) + (totalY * totalY));

            totalX /= hyp;
            totalY /= hyp;

            //Return the value.
            return(new float[] {
                (float)(Math.Atan(totalY / totalX) / (2 * Math.PI)),
                genreCount[0],
                genreCount[1],
                genreCount[2],
                genreCount[3],
                genreCount[4],
                genreCount[5],
                genreCount[6],
            });
        }
Пример #23
0
 public void LocalCacheManager_Add_IsNotNull()
 {
     LocalCacheManager.Add("test", 1212);
     Console.WriteLine(LocalCacheManager.Get <int>("test"));
 }
Пример #24
0
        public void Configuration(IAppBuilder app)
        {
            if (_managerAssembly != null)
            {
                AreaRegistration.RegisterAllAreas();
                CallChildConfigure(app, _managerAssembly, "VirtoCommerce.Platform.Web.Startup", "Configuration", "~/areas/admin", "admin/");
            }

            UnityWebActivator.Start();
            var container = UnityConfig.GetConfiguredContainer();

            // Caching configuration
            // Be cautious with SystemWebCacheHandle because it does not work in native threads (Hangfire jobs).
            var localCache        = CacheFactory.FromConfiguration <object>("storefrontCache");
            var localCacheManager = new LocalCacheManager(localCache);

            container.RegisterInstance <ILocalCacheManager>(localCacheManager);

            //Because CacheManagerOutputCacheProvider used diff cache manager instance need translate clear region by this way
            //https://github.com/MichaCo/CacheManager/issues/32
            localCacheManager.OnClearRegion += (sender, region) =>
            {
                try
                {
                    CacheManagerOutputCacheProvider.Cache.ClearRegion(region.Region);
                }
                catch { }
            };
            localCacheManager.OnClear += (sender, args) =>
            {
                try
                {
                    CacheManagerOutputCacheProvider.Cache.Clear();
                }
                catch { }
            };

            var distributedCache = CacheFactory.Build("distributedCache", settings =>
            {
                var jsonSerializerSettings = new JsonSerializerSettings {
                    TypeNameHandling = TypeNameHandling.All
                };
                var redisCacheEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Storefront:RedisCache:Enabled", false);

                var memoryHandlePart = settings
                                       .WithJsonSerializer(jsonSerializerSettings, jsonSerializerSettings)
                                       .WithUpdateMode(CacheUpdateMode.Up)
                                       .WithSystemRuntimeCacheHandle("memory")
                                       .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(1));

                if (redisCacheEnabled)
                {
                    var redisCacheConnectionStringName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Storefront:RedisCache:ConnectionStringName", "RedisCache");
                    var redisConnectionString          = ConfigurationManager.ConnectionStrings[redisCacheConnectionStringName].ConnectionString;

                    memoryHandlePart
                    .And
                    .WithRedisConfiguration("redis", redisConnectionString)
                    .WithRetryTimeout(100)
                    .WithMaxRetries(1000)
                    .WithRedisBackplane("redis")
                    .WithRedisCacheHandle("redis", true)
                    .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromHours(1));
                }
            });
            var distributedCacheManager = new DistributedCacheManager(distributedCache);

            container.RegisterInstance <IDistributedCacheManager>(distributedCacheManager);

            var logger = LogManager.GetLogger("default");

            container.RegisterInstance <ILogger>(logger);

            // Create new work context for each request
            container.RegisterType <WorkContext, WorkContext>(new PerRequestLifetimeManager());
            Func <WorkContext> workContextFactory = () => container.Resolve <WorkContext>();

            container.RegisterInstance(workContextFactory);

            // Workaround for old storefront base URL: remove /api/ suffix since it is already included in every resource address in VirtoCommerce.Client library.
            var baseUrl = ConfigurationManager.ConnectionStrings["VirtoCommerceBaseUrl"].ConnectionString;

            if (baseUrl != null && baseUrl.EndsWith("/api/", StringComparison.OrdinalIgnoreCase))
            {
                var apiPosition = baseUrl.LastIndexOf("/api/", StringComparison.OrdinalIgnoreCase);
                if (apiPosition >= 0)
                {
                    baseUrl = baseUrl.Remove(apiPosition);
                }
            }

            var apiAppId           = ConfigurationManager.AppSettings["vc-public-ApiAppId"];
            var apiSecretKey       = ConfigurationManager.AppSettings["vc-public-ApiSecretKey"];
            var hmacHandler        = new HmacRestRequestHandler(apiAppId, apiSecretKey);
            var currentUserHandler = new CurrentUserRestRequestHandler(workContextFactory);

            container.RegisterInstance <IVirtoCommerceCartApi>(new VirtoCommerceCartApi(new CartModule.Client.Client.ApiClient(baseUrl, new CartModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceCatalogApi>(new VirtoCommerceCatalogApi(new CatalogModule.Client.Client.ApiClient(baseUrl, new CatalogModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceContentApi>(new VirtoCommerceContentApi(new ContentModule.Client.Client.ApiClient(baseUrl, new ContentModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceCoreApi>(new VirtoCommerceCoreApi(new CoreModule.Client.Client.ApiClient(baseUrl, new CoreModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceCustomerApi>(new VirtoCommerceCustomerApi(new CustomerModule.Client.Client.ApiClient(baseUrl, new CustomerModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceInventoryApi>(new VirtoCommerceInventoryApi(new InventoryModule.Client.Client.ApiClient(baseUrl, new InventoryModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceMarketingApi>(new VirtoCommerceMarketingApi(new MarketingModule.Client.Client.ApiClient(baseUrl, new MarketingModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommercePlatformApi>(new VirtoCommercePlatformApi(new Platform.Client.Client.ApiClient(baseUrl, new Platform.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommercePricingApi>(new VirtoCommercePricingApi(new PricingModule.Client.Client.ApiClient(baseUrl, new PricingModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceOrdersApi>(new VirtoCommerceOrdersApi(new OrderModule.Client.Client.ApiClient(baseUrl, new OrderModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceQuoteApi>(new VirtoCommerceQuoteApi(new QuoteModule.Client.Client.ApiClient(baseUrl, new QuoteModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceSearchApi>(new VirtoCommerceSearchApi(new SearchModule.Client.Client.ApiClient(baseUrl, new SearchModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));
            container.RegisterInstance <IVirtoCommerceStoreApi>(new VirtoCommerceStoreApi(new StoreModule.Client.Client.ApiClient(baseUrl, new StoreModule.Client.Client.Configuration(), hmacHandler.PrepareRequest, currentUserHandler.PrepareRequest)));

            container.RegisterType <IMarketingService, MarketingServiceImpl>();
            container.RegisterType <IPromotionEvaluator, PromotionEvaluator>();
            container.RegisterType <ICartValidator, CartValidator>();
            container.RegisterType <IPricingService, PricingServiceImpl>();
            container.RegisterType <ICustomerService, CustomerServiceImpl>();
            container.RegisterType <IMenuLinkListService, MenuLinkListServiceImpl>();

            container.RegisterType <ICartBuilder, CartBuilder>();
            container.RegisterType <IQuoteRequestBuilder, QuoteRequestBuilder>();
            container.RegisterType <ICatalogSearchService, CatalogSearchServiceImpl>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(context => HttpContext.Current.GetOwinContext().Authentication));


            container.RegisterType <IStorefrontUrlBuilder, StorefrontUrlBuilder>(new PerRequestLifetimeManager());

            //Register domain events
            container.RegisterType <IEventPublisher <OrderPlacedEvent>, EventPublisher <OrderPlacedEvent> >();
            container.RegisterType <IEventPublisher <UserLoginEvent>, EventPublisher <UserLoginEvent> >();
            container.RegisterType <IEventPublisher <QuoteRequestUpdatedEvent>, EventPublisher <QuoteRequestUpdatedEvent> >();
            //Register event handlers (observers)
            container.RegisterType <IAsyncObserver <OrderPlacedEvent>, CustomerServiceImpl>("Invalidate customer cache when user placed new order");
            container.RegisterType <IAsyncObserver <QuoteRequestUpdatedEvent>, CustomerServiceImpl>("Invalidate customer cache when quote request was updated");
            container.RegisterType <IAsyncObserver <UserLoginEvent>, CartBuilder>("Merge anonymous cart with loggined user cart");
            container.RegisterType <IAsyncObserver <UserLoginEvent>, QuoteRequestBuilder>("Merge anonymous quote request with loggined user quote");


            var cmsContentConnectionString = BlobConnectionString.Parse(ConfigurationManager.ConnectionStrings["ContentConnectionString"].ConnectionString);
            var themesBasePath             = cmsContentConnectionString.RootPath.TrimEnd('/') + "/" + "Themes";
            var staticContentBasePath      = cmsContentConnectionString.RootPath.TrimEnd('/') + "/" + "Pages";
            //Use always file system provider for global theme
            var globalThemesBlobProvider = new FileSystemContentBlobProvider(ResolveLocalPath("~/App_Data/Themes/default"));
            IContentBlobProvider       themesBlobProvider;
            IStaticContentBlobProvider staticContentBlobProvider;

            if ("AzureBlobStorage".Equals(cmsContentConnectionString.Provider, StringComparison.OrdinalIgnoreCase))
            {
                themesBlobProvider        = new AzureBlobContentProvider(cmsContentConnectionString.ConnectionString, themesBasePath, localCacheManager);
                staticContentBlobProvider = new AzureBlobContentProvider(cmsContentConnectionString.ConnectionString, staticContentBasePath, localCacheManager);
            }
            else
            {
                themesBlobProvider        = new FileSystemContentBlobProvider(ResolveLocalPath(themesBasePath));
                staticContentBlobProvider = new FileSystemContentBlobProvider(ResolveLocalPath(staticContentBasePath));
            }
            container.RegisterInstance <IStaticContentBlobProvider>(staticContentBlobProvider);

            var shopifyLiquidEngine = new ShopifyLiquidThemeEngine(localCacheManager, workContextFactory, () => container.Resolve <IStorefrontUrlBuilder>(), themesBlobProvider, globalThemesBlobProvider, "~/themes/assets", "~/themes/global/assets");

            container.RegisterInstance <ILiquidThemeEngine>(shopifyLiquidEngine);

            //Register liquid engine
            ViewEngines.Engines.Add(new DotLiquidThemedViewEngine(shopifyLiquidEngine));

            // Shopify model binders convert Shopify form fields with bad names to VirtoCommerce model properties.
            container.RegisterType <IModelBinderProvider, ShopifyModelBinderProvider>("shopify");

            //Static content service
            var staticContentService = new StaticContentServiceImpl(shopifyLiquidEngine, localCacheManager, workContextFactory, () => container.Resolve <IStorefrontUrlBuilder>(), StaticContentItemFactory.GetContentItemFromPath, staticContentBlobProvider);

            container.RegisterInstance <IStaticContentService>(staticContentService);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters, workContextFactory, () => container.Resolve <CommonController>());
            RouteConfig.RegisterRoutes(RouteTable.Routes, workContextFactory, container.Resolve <IVirtoCommerceCoreApi>(), container.Resolve <IStaticContentService>(), localCacheManager);
            AuthConfig.ConfigureAuth(app, () => container.Resolve <IStorefrontUrlBuilder>());

            app.Use <WorkContextOwinMiddleware>(container);
            app.UseStageMarker(PipelineStage.PostAuthorize);
            app.Use <StorefrontUrlRewriterOwinMiddleware>(container);
            app.UseStageMarker(PipelineStage.PostAuthorize);
        }
Пример #25
0
        /// <summary>
        /// Gets studio information from the Giantbomb API
        /// </summary>
        /// <returns>A struct representing the various information.</returns>
        /// <param name="name">The name of the studio.</param>
        /// <param name="DEBUG">Is the studio in debug mode?</param>
        public static StudioInfo GetStudio(string name, bool DEBUG)
        {
            //If the API key is not set, load it from the app.config file.
            if (API_KEY == "")
            {
                API_KEY = ConfigurationManager.AppSettings["GBkey"];
            }

            //Logging
            if (Logger.VERBOSE)
            {
                Logger.Log(name + " in DEBUG mode: [" + DEBUG.ToString().ToUpper() + "]");
            }

            //Check to see if there's a cached value, unless we are forcibly retrieving
            //new values.
            StudioInfo si;

            if (!MainClass.options.force)
            {
                si         = LocalCacheManager.GetCachedInfo(name);
                si.aliases = Extensions.Extensions.CreateAliasList(name);

                if (si.id != "-1")
                {
                    return(si);
                }
            }

            //Get the employee count from Wikipedia.
            int employeeCount = Extensions.Extensions.GetEmployeeCount(name);

            //Get an alternative topic from Wikipedia.
            string wikiName = Wiki.WikipediaRetriever.GetActualTopic(name);

            name = Regex.Replace(name, "\\(company\\)", "", RegexOptions.IgnoreCase).Trim();

            //Get information on release dates of games.
            string[] gameInfo = GetGBInfo(name, wikiName);

            //Change the game info into years, excluding the last two entries,
            //since they're different pieces of information.
            int[] gameYears = new int[gameInfo.Length - 3];

            //Parse all of the actual years.
            for (int a = 0; a < gameInfo.Length - 3; a++)
            {
                gameYears[a] = int.Parse(gameInfo[a]);
            }

            //Sort them together in ascending order.
            Array.Sort(gameYears);

            //Return the new information, including the ID and name from game info.
            si = new StudioInfo
            {
                id            = gameInfo[gameInfo.Length - 3],
                name          = gameInfo[gameInfo.Length - 2],
                companyName   = gameInfo[gameInfo.Length - 1],
                employeeCount = employeeCount,
                gameYears     = gameYears,
                aliases       = Extensions.Extensions.CreateAliasList(name)
            };

            si.aliases.Insert(0, si.companyName);

            //LocalCacheManager.SaveCachedInfo(si);
            return(si);
        }