コード例 #1
0
 public void GetSiteTest()
 {
     SecurityService securityService = new SecurityService();
     ServiceResponse<SiteDC> site = securityService.GetSite(1);
     Assert.AreEqual(site.Result.SiteCode, "S001");
     Assert.AreEqual(site.Result.SiteId, 1);
 }
コード例 #2
0
ファイル: TokenServicesTest.cs プロジェクト: jpsjph/JP_EroPro
 public void GetToken_Should_Throw_When_Pass_InvalidParam()
 {
     //AAA
     const int exceptedValue = -1;
     _authTokenConfig.SetupMockEntityRepositoryForGetAll(_authTokenList);
     var service = new SecurityService(_authTokenConfig.MockPersistence.Object, _authTokenConfig.MockLog.Object, _authTokenConfig.MockUtility.Object);
     service.GetToken(exceptedValue);
 }
コード例 #3
0
ファイル: TokenServicesTest.cs プロジェクト: jpsjph/JP_EroPro
 public void IsValid_With_Username_Should_Throw_When_Pass_InvalidParam()
 {
     //AAA
     string exceptedUsername = null;
     const string exceptedPassword = "";
     _authTokenConfig.SetupMockEntityRepositoryForGetAll(_authTokenList);
     var service = new SecurityService(_authTokenConfig.MockPersistence.Object, _authTokenConfig.MockLog.Object, _authTokenConfig.MockUtility.Object);
     service.IsValid(exceptedUsername, exceptedPassword);
 }
コード例 #4
0
        public void WrongCredentialsFailAuthentication()
        {
            Administrator administrator = ObjectMother.GetAdminAndSaveToDatabase();

            var service = new SecurityService();
            bool authenticationResult = service.AuthenticateUser(administrator.Username, "wrong password");

            Assert.False(authenticationResult);
        }
コード例 #5
0
        public void CanAuthenticateUser()
        {
            Administrator administrator = ObjectMother.GetAdminAndSaveToDatabase();

            var service = new SecurityService();
            bool authenticationResult = service.AuthenticateUser(administrator.Username, ObjectMother.AdminPlaintextPassword);

            Assert.True(authenticationResult);
        }
コード例 #6
0
 public MessageServices(IDbContext context)
 {
     _context = context;
     _logger = LogManager.GetCurrentClassLogger();
     _validationService = new ValidationService(_logger);
     _formattingServices = new FormattingServices();
     _applicationServices = new ApplicationService(_context);
     _securityServices = new SecurityService();
     _userServices = new UserService(_context);
 }
コード例 #7
0
ファイル: CarViewPage.cs プロジェクト: josacore/CarsMvc
 public CarViewPage()
 {
     DataContext = new Context();
     Users = new UserService(DataContext);
     Cars = new CarService(DataContext);
     ImageCars = new ImageCarService(DataContext);
     Models = new ModelService(DataContext);
     Brands = new BrandService(DataContext);
     Types = new TypeService(DataContext);
     Security = new SecurityService(Users);
     CurrentUser = Security.GetCurrentUser();
 }
コード例 #8
0
        public void Setup()
        {
            _mocks = new MockRepository();
            _dataRepository = MockRepository.GenerateStub<ISecurityRepository>();
            _securityHelper = MockRepository.GenerateStub<ISecurityHelper>();
            _logService = MockRepository.GenerateStub<ILogService>();
            _log = MockRepository.GenerateStub<ILog>();

            _securityService = new SecurityService(_dataRepository, _securityHelper, _logService);

            _mockUser = MockRepository.GenerateStub<IPortalUser>();
        }
コード例 #9
0
ファイル: HomeController.cs プロジェクト: foster-hub/box-cms
        //
        // GET: /Home/
        public ActionResult Index()
        {
            SecurityService securityService = new SecurityService();

            int user = 0;
            string userLogin = "******";
            var identity = HttpContext.User.Identity;

            string urlRedirect = NT_CALLBACK_URL + "/Core_Signin/NTcallback/?token=";

            if (identity != null) {
                userLogin = identity.Name;
                user = securityService.SignInUserNT(userLogin);
            }

            if (user == 1) {
                UserToken token = securityService.GetAuthTokenByLoginNT(userLogin);
                return Redirect(urlRedirect + token.Token);
            }

            return new HttpStatusCodeResult(HttpStatusCode.Forbidden, String.Format(SharedStrings.Unauthorized_UserNT, userLogin));
        }
コード例 #10
0
ファイル: QuantBook.cs プロジェクト: stephengunter/qc
        /// <summary>
        /// <see cref = "QuantBook" /> constructor.
        /// Provides access to data for quantitative analysis
        /// </summary>
        public QuantBook() : base()
        {
            try
            {
                using (Py.GIL())
                {
                    _pandas = Py.Import("pandas");
                }

                // Issue #4892 : Set start time relative to NY time
                // when the data is available from the previous day
                var newYorkTime   = DateTime.UtcNow.ConvertFromUtc(TimeZones.NewYork);
                var hourThreshold = Config.GetInt("qb-data-hour", 9);

                // If it is after our hour threshold; then we can use today
                if (newYorkTime.Hour >= hourThreshold)
                {
                    SetStartDate(newYorkTime);
                }
                else
                {
                    SetStartDate(newYorkTime - TimeSpan.FromDays(1));
                }


                // Sets PandasConverter
                SetPandasConverter();

                // Initialize History Provider
                var composer          = new Composer();
                var algorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(composer);
                var systemHandlers    = LeanEngineSystemHandlers.FromConfiguration(composer);
                // init the API
                systemHandlers.Initialize();
                systemHandlers.LeanManager.Initialize(systemHandlers,
                                                      algorithmHandlers,
                                                      new BacktestNodePacket(),
                                                      new AlgorithmManager(false));
                systemHandlers.LeanManager.SetAlgorithm(this);

                algorithmHandlers.ObjectStore.Initialize("QuantBook",
                                                         Config.GetInt("job-user-id"),
                                                         Config.GetInt("project-id"),
                                                         Config.Get("api-access-token"),
                                                         new Controls
                {
                    // if <= 0 we disable periodic persistence and make it synchronous
                    PersistenceIntervalSeconds = -1,
                    StorageLimitMB             = Config.GetInt("storage-limit-mb", 5),
                    StorageFileCount           = Config.GetInt("storage-file-count", 100),
                    StoragePermissions         = (FileAccess)Config.GetInt("storage-permissions", (int)FileAccess.ReadWrite)
                });
                SetObjectStore(algorithmHandlers.ObjectStore);

                _dataCacheProvider = new ZipDataCacheProvider(algorithmHandlers.DataProvider);
                _dataProvider      = algorithmHandlers.DataProvider;

                var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder();
                var registeredTypes          = new RegisteredSecurityDataTypesProvider();
                var securityService          = new SecurityService(Portfolio.CashBook,
                                                                   MarketHoursDatabase,
                                                                   symbolPropertiesDataBase,
                                                                   this,
                                                                   registeredTypes,
                                                                   new SecurityCacheProvider(Portfolio));
                Securities.SetSecurityService(securityService);
                SubscriptionManager.SetDataManager(
                    new DataManager(new NullDataFeed(),
                                    new UniverseSelection(this, securityService, algorithmHandlers.DataPermissionsManager, algorithmHandlers.DataProvider),
                                    this,
                                    TimeKeeper,
                                    MarketHoursDatabase,
                                    false,
                                    registeredTypes,
                                    algorithmHandlers.DataPermissionsManager));

                var mapFileProvider = algorithmHandlers.MapFileProvider;
                HistoryProvider = composer.GetExportedValueByTypeName <IHistoryProvider>(Config.Get("history-provider", "SubscriptionDataReaderHistoryProvider"));
                HistoryProvider.Initialize(
                    new HistoryProviderInitializeParameters(
                        null,
                        null,
                        algorithmHandlers.DataProvider,
                        _dataCacheProvider,
                        mapFileProvider,
                        algorithmHandlers.FactorFileProvider,
                        null,
                        true,
                        algorithmHandlers.DataPermissionsManager
                        )
                    );

                SetOptionChainProvider(new CachingOptionChainProvider(new BacktestingOptionChainProvider()));
                SetFutureChainProvider(new CachingFutureChainProvider(new BacktestingFutureChainProvider()));
            }
            catch (Exception exception)
            {
                throw new Exception("QuantBook.Main(): " + exception);
            }
        }
コード例 #11
0
 public LogoutCommand(SecurityService securityService)
 {
     this.securityService = securityService;
 }
コード例 #12
0
        /// <summary>
        /// Executes the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Save response.</returns>
        /// <exception cref="CmsException">Failed to save page properties.</exception>
        public SavePageResponse Execute(EditPagePropertiesViewModel request)
        {
            var isMultilanguageEnabled = cmsConfiguration.EnableMultilanguage;

            ValidateRequest(request, isMultilanguageEnabled);

            var pageQuery =
                Repository.AsQueryable <PageProperties>(p => p.Id == request.Id)
                .FetchMany(p => p.Options)
                .Fetch(p => p.Layout)
                .ThenFetchMany(l => l.LayoutOptions)
                .FetchMany(p => p.MasterPages)
                .AsQueryable();

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                pageQuery = pageQuery.FetchMany(f => f.AccessRules);
            }

            var page         = pageQuery.ToList().FirstOne();
            var beforeChange = new UpdatingPagePropertiesModel(page);

            var roles = page.IsMasterPage
                            ? new[]
            {
                RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent, RootModuleConstants.UserRoles.Administration
            }
                            : new[] { RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent };

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                AccessControlService.DemandAccess(page, Context.Principal, AccessLevel.ReadWrite, roles);
            }
            else
            {
                AccessControlService.DemandAccess(Context.Principal, roles);
            }

            var canEdit = page.IsMasterPage
                              ? SecurityService.IsAuthorized(
                Context.Principal,
                RootModuleConstants.UserRoles.MultipleRoles(RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.Administration))
                              : SecurityService.IsAuthorized(Context.Principal, RootModuleConstants.UserRoles.EditContent);

            IList <PageProperties> translations = null;

            if (canEdit && isMultilanguageEnabled && !page.IsMasterPage)
            {
                translations = LoadAndValidateTranslations(page, request);
            }

            // Load master pages for updating page's master path and page's children master path
            IList <Guid>       newMasterIds;
            IList <Guid>       oldMasterIds;
            IList <Guid>       childrenPageIds;
            IList <MasterPage> existingChildrenMasterPages;

            masterPageService.PrepareForUpdateChildrenMasterPages(page, request.MasterPageId, out newMasterIds, out oldMasterIds, out childrenPageIds, out existingChildrenMasterPages);

            IList <SitemapNode> updatedNodes = null;

            // Start transaction, only when everything is already loaded
            UnitOfWork.BeginTransaction();

            Models.Redirect redirectCreated  = null;
            var             initialSeoStatus = page.HasSEO;

            request.PageUrl = urlService.FixUrl(request.PageUrl);

            if (canEdit && !string.Equals(page.PageUrl, request.PageUrl))
            {
                pageService.ValidatePageUrl(request.PageUrl, request.Id);
                if (request.RedirectFromOldUrl)
                {
                    var redirect = redirectService.CreateRedirectEntity(page.PageUrl, request.PageUrl);
                    if (redirect != null)
                    {
                        Repository.Save(redirect);
                        redirectCreated = redirect;
                    }
                }

                if (request.UpdateSitemap)
                {
                    updatedNodes = sitemapService.ChangeUrlsInAllSitemapsNodes(page.PageUrl, request.PageUrl);
                }

                page.PageUrl = request.PageUrl;
            }

            List <PageProperties> updatePageTranslations = null;

            if (canEdit)
            {
                page.PageUrlHash         = page.PageUrl.UrlHash();
                page.ForceAccessProtocol = request.ForceAccessProtocol;
                page.Category            = request.CategoryId.HasValue ? Repository.AsProxy <CategoryEntity>(request.CategoryId.Value) : null;
                page.Title     = request.PageName;
                page.CustomCss = request.PageCSS;
                page.CustomJS  = request.PageJavascript;

                masterPageService.SetMasterOrLayout(page, request.MasterPageId, request.TemplateId);

                if (isMultilanguageEnabled && !page.IsMasterPage)
                {
                    updatePageTranslations = UpdatePageTranslations(page, translations, request);
                }
            }

            var publishDraftContent = false;

            if (request.CanPublishPage && !page.IsMasterPage)
            {
                AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.PublishContent);

                if (request.IsPagePublished)
                {
                    if (page.Status != PageStatus.Published)
                    {
                        page.Status         = PageStatus.Published;
                        page.PublishedOn    = DateTime.Now;
                        publishDraftContent = true;
                    }
                }
                else
                {
                    page.Status = PageStatus.Unpublished;
                }
            }

            IList <PageOption> pageOptions = page.Options.Distinct().ToList();

            if (canEdit)
            {
                if (!page.IsMasterPage)
                {
                    page.UseNoFollow = request.UseNoFollow;
                    page.UseNoIndex  = request.UseNoIndex;
                    page.IsArchived  = request.IsArchived;
                }

                page.UseCanonicalUrl = request.UseCanonicalUrl;
                page.Version         = request.Version;

                page.Image          = request.Image != null && request.Image.ImageId.HasValue ? Repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null;
                page.SecondaryImage = request.SecondaryImage != null && request.SecondaryImage.ImageId.HasValue
                                          ? Repository.AsProxy <MediaImage>(request.SecondaryImage.ImageId.Value)
                                          : null;
                page.FeaturedImage = request.FeaturedImage != null && request.FeaturedImage.ImageId.HasValue
                                         ? Repository.AsProxy <MediaImage>(request.FeaturedImage.ImageId.Value)
                                         : null;

                pageOptions = optionService.SaveOptionValues(request.OptionValues, pageOptions, () => new PageOption {
                    Page = page
                });

                if (cmsConfiguration.Security.AccessControlEnabled)
                {
                    page.AccessRules.RemoveDuplicateEntities();

                    var accessRules = request.UserAccessList != null?request.UserAccessList.Cast <IAccessRule>().ToList() : null;

                    accessControlService.UpdateAccessControl(page, accessRules);
                }
            }

            // Notify about page properties changing.
            var cancelEventArgs = Events.PageEvents.Instance.OnPagePropertiesChanging(beforeChange, new UpdatingPagePropertiesModel(page));

            if (cancelEventArgs.Cancel)
            {
                Context.Messages.AddError(cancelEventArgs.CancellationErrorMessages.ToArray());
                return(null);
            }

            Repository.Save(page);

            IList <Tag> newTags = null;

            if (canEdit)
            {
                masterPageService.UpdateChildrenMasterPages(existingChildrenMasterPages, oldMasterIds, newMasterIds, childrenPageIds);
                tagService.SavePageTags(page, request.Tags, out newTags);
            }

            if (publishDraftContent)
            {
                contentService.PublishDraftContent(page.Id);
            }

            UnitOfWork.Commit();

            // Notify about page properties change.
            page.Options = pageOptions;
            Events.PageEvents.Instance.OnPagePropertiesChanged(page);

            // Notify about translation properties changed
            if (updatePageTranslations != null)
            {
                updatePageTranslations.ForEach(Events.PageEvents.Instance.OnPagePropertiesChanged);
            }

            // Notify about redirect creation.
            if (redirectCreated != null)
            {
                Events.PageEvents.Instance.OnRedirectCreated(redirectCreated);
            }

            // Notify about SEO status change.
            if (initialSeoStatus != page.HasSEO)
            {
                Events.PageEvents.Instance.OnPageSeoStatusChanged(page);
            }

            // Notify about new tags.
            Events.RootEvents.Instance.OnTagCreated(newTags);

            // Notify about updated sitemap nodes.
            if (updatedNodes != null)
            {
                var updatedSitemaps = new List <Models.Sitemap>();
                foreach (var node in updatedNodes)
                {
                    Events.SitemapEvents.Instance.OnSitemapNodeUpdated(node);
                    if (!updatedSitemaps.Contains(node.Sitemap))
                    {
                        updatedSitemaps.Add(node.Sitemap);
                    }
                }

                foreach (var updatedSitemap in updatedSitemaps)
                {
                    Events.SitemapEvents.Instance.OnSitemapUpdated(updatedSitemap);
                }
            }

            return(new SavePageResponse(page));
        }
コード例 #13
0
        public ResponseModel BulkUploadCRMRole(IFormFile File, int RoleFor = 1)
        {
            string         downloadFilePath    = string.Empty;
            string         bulkUploadFilesPath = string.Empty;
            bool           errorFilesaved      = false;
            bool           successFilesaved    = false;
            int            count            = 0;
            List <string>  CSVlist          = new List <string>();
            SettingsCaller _newCRM          = new SettingsCaller();
            ResponseModel  objResponseModel = new ResponseModel();
            int            statusCode       = 0;
            string         statusMessage    = "";
            DataSet        dataSetCSV       = new DataSet();
            string         fileName         = "";
            string         finalAttchment   = "";
            string         timeStamp        = DateTime.Now.ToString("ddmmyyyyhhssfff");

            string[] filesName = null;

            try
            {
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromTokenCache(Cache, SecurityService.DecryptStringAES(token));

                var files = Request.Form.Files;

                if (files.Count > 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        fileName += files[i].FileName.Replace(".", timeStamp + ".") + ",";
                    }
                    finalAttchment = fileName.TrimEnd(',');
                }
                var Keys = Request.Form;

                var exePath = Path.GetDirectoryName(System.Reflection
                                                    .Assembly.GetExecutingAssembly().CodeBase);
                Regex  appPathMatcher = new Regex(@"(?<!fil)[A-Za-z]:\\+[\S\s]*?(?=\\+bin)");
                var    appRoot        = appPathMatcher.Match(exePath).Value;
                string Folderpath     = appRoot + "\\" + _UploadedBulkFile;
                if (files.Count > 0)
                {
                    filesName = finalAttchment.Split(",");
                    for (int i = 0; i < files.Count; i++)
                    {
                        using (var ms = new MemoryStream())
                        {
                            files[i].CopyTo(ms);
                            var          fileBytes = ms.ToArray();
                            MemoryStream msfile    = new MemoryStream(fileBytes);
                            FileStream   docFile   = new FileStream(Folderpath + "\\" + filesName[i], FileMode.Create, FileAccess.Write);
                            msfile.WriteTo(docFile);
                            docFile.Close();
                            ms.Close();
                            msfile.Close();
                            string s = Convert.ToBase64String(fileBytes);
                            byte[] a = Convert.FromBase64String(s);
                            // act on the Base64 data
                        }
                    }
                }
                #region FilePath
                bulkUploadFilesPath = rootPath + "\\" + "BulkUpload\\UploadFiles" + "\\" + CommonFunction.GetEnumDescription((EnumMaster.FileUpload)RoleFor);
                downloadFilePath    = rootPath + "\\" + "BulkUpload\\DownloadFiles" + "\\" + CommonFunction.GetEnumDescription((EnumMaster.FileUpload)RoleFor);

                #endregion
                dataSetCSV = CommonService.csvToDataSet(Folderpath + "\\" + finalAttchment);
                CSVlist    = _newCRM.CRMRoleBulkUpload(new CRMRoleService(Cache, Db), authenticate.TenantId, authenticate.UserMasterID, RoleFor, dataSetCSV);

                #region Create Error and Succes files and  Insert in FileUploadLog

                if (!string.IsNullOrEmpty(CSVlist[0]))
                {
                    successFilesaved = CommonService.SaveFile(downloadFilePath + "\\CRMRole\\ Success" + "\\" + "CRMRoleSuccessFile.csv", CSVlist[0]);
                }

                if (!string.IsNullOrEmpty(CSVlist[1]))
                {
                    errorFilesaved = CommonService.SaveFile(downloadFilePath + "\\CRMRole\\Error" + "\\" + "CRMRoleErrorFile.csv", CSVlist[1]);
                }

                count = _newCRM.CreateFileUploadLog(new FileUploadService(Cache, Db), authenticate.TenantId, "CRMRolesBulk.csv", errorFilesaved,
                                                    "HierarchyErrorFile.csv", "HierarchySuccessFile.csv", authenticate.UserMasterID, "CRMRole",
                                                    downloadFilePath + "\\Hierarchy\\Error" + "\\" + "CRMRoleErrorFile.csv",
                                                    downloadFilePath + "\\Hierarchy\\ Success" + "\\" + "CRMRoleSuccessFile.csv", RoleFor
                                                    );
                #endregion

                statusCode                    = count > 0 ? (int)EnumMaster.StatusCode.Success : (int)EnumMaster.StatusCode.RecordNotFound;
                statusMessage                 = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);
                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = CSVlist.Count;
            }
            catch (Exception)
            {
                throw;
            }
            return(objResponseModel);
        }
コード例 #14
0
 public void GetRolesTest()
 {
     SecurityService securityService = new SecurityService();
     ServiceResponse<List<RoleDC>> site = securityService.GetRoles();
     Assert.AreEqual(site.Result.Count > 0, true);
 }
コード例 #15
0
        public void RunCommand(string server, string vault, string username, string password, string rootfolder, Boolean exportdwfs, string property, string propertyvalue)
        {
            long propertyid = 0;
            SecurityService secSrv = new SecurityService();
            secSrv.SecurityHeaderValue = new VaultSyncReleased.Security.SecurityHeader();
            secSrv.Url = "http://" + server + "/AutodeskDM/Services/SecurityService.asmx";

            try 
            {
                secSrv.SignIn(username, password, vault);
                DocumentService docSrv = new DocumentService();
                docSrv.SecurityHeaderValue = new VaultSyncReleased.Document.SecurityHeader();
                docSrv.SecurityHeaderValue.UserId = secSrv.SecurityHeaderValue.UserId;
                docSrv.SecurityHeaderValue.Ticket = secSrv.SecurityHeaderValue.Ticket;
                docSrv.Url = "http://" + server + "/AutodeskDM/Services/DocumentService.asmx";
                Folder root = docSrv.GetFolderRoot();
                //root = docSrv.GetFolderByPath("$/Designs/Designs/C690 T3");
                //root = docSrv.GetFolderByPath("$/Amendment");
                Document.PropDef[] defs = docSrv.GetAllPropertyDefinitions();
                foreach (Document.PropDef pd in defs)
                {
                    if (pd.DispName.ToString().ToLower() == property.ToLower())
                    {
                        propertyid = pd.Id;
                    }
                }
                if ((property != "") && (propertyid == 0))
                {
                    Console.WriteLine("Error: Property notdefined in Vault [" + property + "]");
                    Console.WriteLine("Properties that ARE defined in Vault [" + vault + "]:");
                    foreach (Document.PropDef pd in defs)
                    {
                        Console.WriteLine("  " + pd.DispName.ToString());
                    }
                }
                else
                {
                    ProcessFilesInFolder(root, docSrv, rootfolder, exportdwfs, property, propertyvalue, propertyid);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
                return;
            }
        }
コード例 #16
0
 public void RunCommand(string server, string vault, string username, string password, string file, string checkinfile, Boolean printerror, string comment)
 {
     SecurityService secSrv = new SecurityService();
     secSrv.SecurityHeaderValue = new VaultSingleFileCheckin.Security.SecurityHeader();
     secSrv.Url = "http://" + server + "/AutodeskDM/Services/SecurityService.asmx";
     try 
     {
         secSrv.SignIn(username, password, vault);
         DocumentService docSrv = new DocumentService();
         docSrv.SecurityHeaderValue = new VaultSingleFileCheckin.Document.SecurityHeader();
         docSrv.SecurityHeaderValue.UserId = secSrv.SecurityHeaderValue.UserId;
         docSrv.SecurityHeaderValue.Ticket = secSrv.SecurityHeaderValue.Ticket;
         docSrv.Url = "http://" + server + "/AutodeskDM/Services/DocumentService.asmx";
         Folder root = docSrv.GetFolderRoot();
         string filepath = System.IO.Path.GetDirectoryName(file);
         filepath = filepath.Replace("\\", "/");
         CreateFolder(docSrv, filepath);
         Folder filefolder = docSrv.GetFolderByPath(filepath);
         int fileflag = IsFileInFolder(filefolder, docSrv, file);
         //Console.WriteLine("File " + fileflag.ToString());
         byte[] bytes;
         switch (fileflag)
         {
             case 0:
                 Console.WriteLine("File is not in vault");
                 bytes = System.IO.File.ReadAllBytes(checkinfile);
                 File addedfile = docSrv.AddFile(filefolder.Id, System.IO.Path.GetFileName(checkinfile), comment,
                     System.IO.File.GetLastWriteTime(checkinfile), null, null, null, null, null,
                     FileClassification.None, false, bytes);
                 if (addedfile == null)
                 {
                     Console.WriteLine("ERROR: File not checked in to vault");
                 }
                 else
                 {
                     Console.WriteLine("File checked in to vault");
                 }
                 break;
             case 1:
                 Console.WriteLine("File is in vault (not checked out)");
                 File[] files = docSrv.GetLatestFilesByFolderId(filefolder.Id, true);
                 foreach (File afile in files)
                 {           
                     if (filefolder.FullName + "/" + afile.Name == file)
                     {
                         //docSrv.CheckoutFile(filefolder.Id, afile.MasterId,
                         //    Environment.MachineName, Environment.GetEnvironmentVariable("TEMP"), comment,
                         //    true, true, out bytes);
                         docSrv.CheckoutFile(filefolder.Id, afile.Id, CheckoutFileOptions.Master,
                                         Environment.MachineName, "c:\\", "Temporary Checkout",
                                         false, true, out bytes);
                         bytes = System.IO.File.ReadAllBytes(checkinfile);
                         File updatedfile = docSrv.CheckinFile(afile.MasterId, comment,
                             false, System.IO.File.GetLastWriteTime(checkinfile), null, null, null, null, null, false,
                             System.IO.Path.GetFileName(checkinfile), afile.FileClass, afile.Hidden, bytes);
                         if (updatedfile.Id  == afile.Id)
                         {
                             Console.WriteLine("ERROR: File not checked in to vault");
                         }
                         else
                         {
                             Console.WriteLine("File checked in to vault");
                         }
                     }
                 }
                 break;
             case 2:
                 Console.WriteLine("File is in vault (checked out to you)");
                 break;
             default:
                 Console.WriteLine("File is in vault (checked out to someone else)");
                 Console.WriteLine("Cannot check in file");
                 break;
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error retrieving file");
         if (printerror)
         {
             Console.WriteLine(ex.ToString());
         }
         return;
     }
 }
コード例 #17
0
        /// <summary>
        /// Executes the specified request.
        /// </summary>
        /// <param name="id">The page id.</param>
        /// <returns></returns>
        public EditPagePropertiesViewModel Execute(Guid id)
        {
            var pageEntity = Repository.AsQueryable <PageProperties>().FirstOrDefault(p => p.Id == id);

            if (pageEntity == null)
            {
                return(null);
            }

            var modelQuery = Repository
                             .AsQueryable <PageProperties>()
                             .Where(p => p.Id == id)
                             .Select(page =>
                                     new
            {
                Model = new EditPagePropertiesViewModel
                {
                    Id                   = page.Id,
                    Version              = page.Version,
                    PageName             = page.Title,
                    PageUrl              = page.PageUrl,
                    ForceAccessProtocol  = page.ForceAccessProtocol,
                    PageCSS              = page.CustomCss,
                    PageJavascript       = page.CustomJS,
                    UseNoFollow          = page.UseNoFollow,
                    UseNoIndex           = page.UseNoIndex,
                    UseCanonicalUrl      = page.UseCanonicalUrl,
                    IsPagePublished      = page.Status == PageStatus.Published,
                    IsArchived           = page.IsArchived,
                    IsMasterPage         = page.IsMasterPage,
                    TemplateId           = page.Layout.Id,
                    MasterPageId         = page.MasterPage.Id,
                    LanguageId           = page.Language.Id,
                    AccessControlEnabled = cmsConfiguration.Security.AccessControlEnabled,
                    IsInSitemap          = page.PagesView.IsInSitemap,
                    Image                = page.Image == null || page.Image.IsDeleted ? null :
                                           new ImageSelectorViewModel
                    {
                        ImageId      = page.Image.Id,
                        ImageVersion = page.Image.Version,
                        ImageUrl     = fileUrlResolver.EnsureFullPathUrl(page.Image.PublicUrl),
                        ThumbnailUrl = fileUrlResolver.EnsureFullPathUrl(page.Image.PublicThumbnailUrl),
                        ImageTooltip = page.Image.Caption,
                        FolderId     = page.Image.Folder != null ? page.Image.Folder.Id : (Guid?)null
                    },
                    SecondaryImage = page.SecondaryImage == null || page.SecondaryImage.IsDeleted ? null :
                                     new ImageSelectorViewModel
                    {
                        ImageId      = page.SecondaryImage.Id,
                        ImageVersion = page.SecondaryImage.Version,
                        ImageUrl     = fileUrlResolver.EnsureFullPathUrl(page.SecondaryImage.PublicUrl),
                        ThumbnailUrl = fileUrlResolver.EnsureFullPathUrl(page.SecondaryImage.PublicThumbnailUrl),
                        ImageTooltip = page.SecondaryImage.Caption,
                        FolderId     = page.SecondaryImage.Folder != null ? page.SecondaryImage.Folder.Id : (Guid?)null
                    },
                    FeaturedImage = page.FeaturedImage == null || page.FeaturedImage.IsDeleted ? null :
                                    new ImageSelectorViewModel
                    {
                        ImageId      = page.FeaturedImage.Id,
                        ImageVersion = page.FeaturedImage.Version,
                        ImageUrl     = fileUrlResolver.EnsureFullPathUrl(page.FeaturedImage.PublicUrl),
                        ThumbnailUrl = fileUrlResolver.EnsureFullPathUrl(page.FeaturedImage.PublicThumbnailUrl),
                        ImageTooltip = page.FeaturedImage.Caption,
                        FolderId     = page.FeaturedImage.Folder != null ? page.FeaturedImage.Folder.Id : (Guid?)null
                    }
                },
                LanguageGroupIdentifier = page.LanguageGroupIdentifier
            })
                             .ToFuture();

            var tagsFuture = tagService.GetPageTagNames(id);


            var languagesFuture = (cmsConfiguration.EnableMultilanguage) ? languageService.GetLanguagesLookupValues() : null;

            IEnumerable <AccessRule> userAccessFuture;

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                userAccessFuture = Repository
                                   .AsQueryable <Root.Models.Page>()
                                   .Where(x => x.Id == id && !x.IsDeleted)
                                   .SelectMany(x => x.AccessRules)
                                   .OrderBy(x => x.IsForRole)
                                   .ThenBy(x => x.Identity)
                                   .ToFuture();
            }
            else
            {
                userAccessFuture = null;
            }

            var model = modelQuery.ToList().FirstOrDefault();

            if (model != null && model.Model != null)
            {
                if (model.Model.IsMasterPage)
                {
                    AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.Administration);
                }
                else
                {
                    AccessControlService.DemandAccess(Context.Principal, RootModuleConstants.UserRoles.MultipleRoles(RootModuleConstants.UserRoles.EditContent, RootModuleConstants.UserRoles.PublishContent));
                }

                model.Model.Tags = tagsFuture.ToList();
                model.Model.RedirectFromOldUrl  = true;
                model.Model.Categories          = categoryService.GetSelectedCategories <PageProperties, PageCategory>(id).ToList();
                model.Model.CategoriesFilterKey = pageEntity.GetCategorizableItemKey();
                model.Model.PageAccessProtocols = this.GetProtocolForcingTypes();
                model.Model.UpdateSitemap       = true;
                model.Model.CustomOptions       = optionService.GetCustomOptions();
                model.Model.ShowTranslationsTab = cmsConfiguration.EnableMultilanguage && !model.Model.IsMasterPage;
                if (model.Model.ShowTranslationsTab)
                {
                    model.Model.Languages = languagesFuture.ToList();
                    if (!model.Model.Languages.Any())
                    {
                        model.Model.TranslationMessages = new UserMessages();
                        model.Model.TranslationMessages.AddInfo(PagesGlobalization.EditPageProperties_TranslationsTab_NoLanguagesCreated_Message);
                    }
                    if (model.LanguageGroupIdentifier.HasValue)
                    {
                        model.Model.Translations = pageService.GetPageTranslations(model.LanguageGroupIdentifier.Value).ToList();
                    }
                }

                // Get layout options, page options and merge them
                model.Model.OptionValues = optionService.GetMergedMasterPagesOptionValues(model.Model.Id, model.Model.MasterPageId, model.Model.TemplateId);

                if (userAccessFuture != null)
                {
                    model.Model.UserAccessList = userAccessFuture.Select(x => new UserAccessViewModel(x)).ToList();

                    var rules = model.Model.UserAccessList.Cast <IAccessRule>().ToList();

                    SetIsReadOnly(model.Model, rules);
                }

                model.Model.CanPublishPage = SecurityService.IsAuthorized(Context.Principal, RootModuleConstants.UserRoles.PublishContent);

                // Get templates
                model.Model.Templates = layoutService.GetAvailableLayouts(id, model.Model.MasterPageId).ToList();
                model.Model.Templates
                .Where(x => x.TemplateId == model.Model.TemplateId || x.TemplateId == model.Model.MasterPageId)
                .Take(1).ToList()
                .ForEach(x => x.IsActive = true);
            }

            return(model != null ? model.Model : null);
        }
コード例 #18
0
 public VenueController(VenueService venueService, SecurityService securityService)
 {
     _venueService    = venueService;
     _securityService = securityService;
 }
コード例 #19
0
        private void RunTest(
            HiveManager hiveManager,
            FakeFrameworkContext frameworkContext,
            Action installCallback = null)
        {
            var attributeTypeRegistry = new CmsAttributeTypeRegistry();

            AttributeTypeRegistry.SetCurrent(attributeTypeRegistry);
            var appContext = new FakeRebelApplicationContext(hiveManager, false);
            var mockedPropertyEditorFactory = new MockedPropertyEditorFactory(appContext);
            var resolverContext             = new MockedMapResolverContext(frameworkContext, hiveManager, mockedPropertyEditorFactory, new MockedParameterEditorFactory());
            var webmModelMapper             = new CmsModelMapper(resolverContext);

            frameworkContext.SetTypeMappers(new FakeTypeMapperCollection(new AbstractMappingEngine[] { webmModelMapper, new FrameworkModelMapper(frameworkContext) }));

            var devDataset = DemoDataHelper.GetDemoData(appContext, attributeTypeRegistry);

            //Setup permissions
            var permissions = new Permission[] { new SavePermission(), new PublishPermission(), new HostnamesPermission(), new CopyPermission(), new MovePermission() }
            .Select(x => new Lazy <Permission, PermissionMetadata>(() => x, new PermissionMetadata(new Dictionary <string, object>
            {
                { "Id", x.Id },
                { "Name", x.Name },
                { "Type", x.Type },
                { "UserType", x.UserType }
            }))).ToArray();

            //Setup security service
            var usersMembershipProvider = new UsersMembershipProvider {
                AppContext = appContext
            };

            usersMembershipProvider.Initialize("UsersMembershipProvider", new NameValueCollection());
            var usersMembershipService = new MembershipService <User, UserProfile>(frameworkContext, hiveManager,
                                                                                   "security://user-profiles", "security://user-groups", Framework.Security.Model.FixedHiveIds.UserProfileVirtualRoot,
                                                                                   usersMembershipProvider, Enumerable.Empty <MembershipProviderElement>());

            ResetMembershipProvider(usersMembershipService.MembershipProvider);

            var membersMembershipProvider = new MembersMembershipProvider {
                AppContext = appContext
            };

            membersMembershipProvider.Initialize("MembersMembershipProvider", new NameValueCollection());
            var membersMembershipService = new MembershipService <Member, MemberProfile>(frameworkContext, hiveManager,
                                                                                         "security://member-profiles", "security://member-groups", Framework.Security.Model.FixedHiveIds.MemberProfileVirtualRoot,
                                                                                         membersMembershipProvider, Enumerable.Empty <MembershipProviderElement>());

            ResetMembershipProvider(membersMembershipService.MembershipProvider);

            var permissionService   = new PermissionsService(hiveManager, permissions, usersMembershipService);
            var publicAccessService = new PublicAccessService(hiveManager, membersMembershipService, appContext.FrameworkContext);
            var securityService     = new SecurityService(usersMembershipService, membersMembershipService, permissionService, publicAccessService);

            var coreDataInstallTask = new EnsureCoreDataTask(frameworkContext, hiveManager, permissions, securityService);

            //var devDatasetInstallTask = new DevDatasetInstallTask(frameworkContext, mockedPropertyEditorFactory, hiveManager, attributeTypeRegistry);

            //Act

            coreDataInstallTask.InstallOrUpgrade();
            if (installCallback != null)
            {
                installCallback();
            }
            //devDatasetInstallTask.InstallOrUpgrade();
            //if (installCallback != null) installCallback();

            //Assert

            var totalSchemaCount = CoreCmsData.RequiredCoreSchemas().Count() + devDataset.DocTypes.Count() + 1; // +1 for SystemRoot schema
            var totalEntityCount =
                CoreCmsData.RequiredCoreUserGroups(permissions).Count() +
                CoreCmsData.RequiredCoreRootNodes().Count() +
                devDataset.ContentData.Count();
            var totalAttributeTypeCount = CoreCmsData.RequiredCoreSystemAttributeTypes().Count() + CoreCmsData.RequiredCoreUserAttributeTypes().Count();

            DoCoreAssertions(hiveManager, totalSchemaCount, totalEntityCount, totalAttributeTypeCount, 2, permissions, securityService);

            //CoreCmsData.RequiredCoreUsers().ForEach(
            //    x =>
            //    {
            //        securityService.UsersMembershipService.DeleteUser(x.Username, true);
            //        securityService.MembersMembershipService.DeleteUser(x.Username, true);
            //    });

            ResetMembershipProvider(securityService.Users.MembershipProvider);
            ResetMembershipProvider(securityService.Members.MembershipProvider);
        }
コード例 #20
0
        private void TestSubscriptionSynchronizerSpeed(QCAlgorithm algorithm)
        {
            var feed = new MockDataFeed();
            var marketHoursDatabase      = MarketHoursDatabase.FromDataFolder();
            var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder();
            var securityService          = new SecurityService(
                algorithm.Portfolio.CashBook,
                marketHoursDatabase,
                symbolPropertiesDataBase,
                algorithm);

            algorithm.Securities.SetSecurityService(securityService);
            var dataManager = new DataManager(feed,
                                              new UniverseSelection(algorithm, securityService),
                                              algorithm,
                                              algorithm.TimeKeeper,
                                              marketHoursDatabase);

            algorithm.SubscriptionManager.SetDataManager(dataManager);

            algorithm.Initialize();
            algorithm.PostInitialize();

            // set exchanges to be always open
            foreach (var kvp in algorithm.Securities)
            {
                var security = kvp.Value;
                security.Exchange = new SecurityExchange(SecurityExchangeHours.AlwaysOpen(security.Exchange.TimeZone));
            }

            var endTimeUtc   = algorithm.EndDate.ConvertToUtc(TimeZones.NewYork);
            var startTimeUtc = algorithm.StartDate.ConvertToUtc(TimeZones.NewYork);
            var subscriptionBasedTimeProvider = new SubscriptionFrontierTimeProvider(startTimeUtc, dataManager);
            var synchronizer = new SubscriptionSynchronizer(dataManager.UniverseSelection, algorithm.Portfolio.CashBook);

            synchronizer.SetTimeProvider(subscriptionBasedTimeProvider);
            synchronizer.SetSliceTimeZone(algorithm.TimeZone);
            var totalDataPoints = 0;
            var subscriptions   = dataManager.DataFeedSubscriptions;

            foreach (var kvp in algorithm.Securities)
            {
                int dataPointCount;
                subscriptions.TryAdd(CreateSubscription(algorithm, kvp.Value, startTimeUtc, endTimeUtc, out dataPointCount));
                totalDataPoints += dataPointCount;
            }

            // force JIT
            synchronizer.Sync(subscriptions);

            // log what we're doing
            Console.WriteLine($"Running {subscriptions.Count()} subscriptions with a total of {totalDataPoints} data points. Start: {algorithm.StartDate:yyyy-MM-dd} End: {algorithm.EndDate:yyyy-MM-dd}");

            var      count       = 0;
            DateTime currentTime = DateTime.MaxValue;
            DateTime previousValue;
            var      stopwatch = Stopwatch.StartNew();

            do
            {
                previousValue = currentTime;
                var timeSlice = synchronizer.Sync(subscriptions);
                currentTime = timeSlice.Time;
                count      += timeSlice.DataPointCount;
            }while (currentTime != previousValue);

            stopwatch.Stop();

            var kps = count / 1000d / stopwatch.Elapsed.TotalSeconds;

            Console.WriteLine($"Current Time: {currentTime:u}  Elapsed time: {(int)stopwatch.Elapsed.TotalSeconds,4}s  KPS: {kps,7:.00}  COUNT: {count,10}");
            Assert.GreaterOrEqual(count, 100); // this assert is for sanity purpose
        }
コード例 #21
0
 public ActionResult IsAuthorized(string roles)
 {
     return(Json(new WireJson {
         Success = SecurityService.IsAuthorized(roles)
     }));
 }
コード例 #22
0
        public ResponseModel CreateUpdateCRMRole(int CRMRoleID, string RoleName, bool RoleisActive, string ModulesEnabled, string ModulesDisabled)
        {
            int           count            = 0;
            ResponseModel objResponseModel = new ResponseModel();
            int           statusCode       = 0;
            string        statusMessage    = "";

            try
            {
                ////Get token (Double encrypted) and get the tenant id
                string token = Convert.ToString(Request.Headers["X-Authorized-Token"]);


                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromTokenCache(Cache, SecurityService.DecryptStringAES(token));

                SettingsCaller newCRM = new SettingsCaller();

                count = newCRM.InsertUpdateCRMRole(new CRMRoleService(Cache, Db), CRMRoleID, authenticate.TenantId, RoleName, RoleisActive, authenticate.UserMasterID, ModulesEnabled, ModulesDisabled);

                if (CRMRoleID.Equals(0))
                {
                    statusCode = count == 0 ? (int)EnumMaster.StatusCode.RecordAlreadyExists : (int)EnumMaster.StatusCode.Success;
                }
                else
                {
                    statusCode = count == 0 ? (int)EnumMaster.StatusCode.InternalServiceNotWorking : (int)EnumMaster.StatusCode.Success;
                }

                statusMessage = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);

                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = count;
            }
            catch (Exception)
            {
                throw;
            }

            return(objResponseModel);
        }
コード例 #23
0
 public AccountController()
 {
     securityService = new SecurityService();
 }
コード例 #24
0
ファイル: TokenServicesTest.cs プロジェクト: jpsjph/JP_EroPro
 public void GetToken_Should_Return_Null_When_Given_Invalid_Data()
 {
     //AAA
     const int validKey = 11;
     _authTokenConfig.SetupMockEntityRepositoryForGetAll(_authTokenList);
     var service = new SecurityService(_authTokenConfig.MockPersistence.Object, _authTokenConfig.MockLog.Object, _authTokenConfig.MockUtility.Object);
     var result = service.GetToken(validKey);
     Assert.IsNull(result);
 }
コード例 #25
0
        private void AddHourFlyout_Click(object sender, RoutedEventArgs e)
        {
            FrameworkElement senderElement = sender as FrameworkElement;
            Day day = (Day)senderElement.DataContext;

            TimePickerFlyout picker = new TimePickerFlyout();

            picker.ShowAt(senderElement);

            picker.TimePicked += async(s, a) =>
            {
                DateTime date = day.Check.DateTime.Date.AddTicks(a.NewTime.Ticks);
                await Historic.Historic.AddAsync(new TTCheck { DateTime = date, UserName = SecurityService.getCredential().Item1 });
            };
        }
コード例 #26
0
ファイル: TokenServicesTest.cs プロジェクト: jpsjph/JP_EroPro
        public void DecryptUsername_Should_Throw_When_Pass_InvalidParam()
        {
            //AAA
            string exceptedkey = null;

            _authTokenConfig.SetupMockEntityRepositoryForGetAll(_authTokenList);
            var service = new SecurityService(_authTokenConfig.MockPersistence.Object, _authTokenConfig.MockLog.Object, _authTokenConfig.MockUtility.Object);
            service.DecryptUsername(exceptedkey);
        }
コード例 #27
0
 private void LogoffButtonClicked(object sender, RoutedEventArgs e)
 {
     SecurityService.logoff();
     GoToLoginPage();
 }
コード例 #28
0
 public PaymentAccountService(IDbContext context)
 {
     _ctx = context;
     _logger = LogManager.GetCurrentClassLogger();
        _securityServices = new SecurityService();
 }
コード例 #29
0
ファイル: Engine.cs プロジェクト: DyFuente/Lean
        /// <summary>
        /// Runs a single backtest/live job from the job queue
        /// </summary>
        /// <param name="job">The algorithm job to be processed</param>
        /// <param name="manager">The algorithm manager instance</param>
        /// <param name="assemblyPath">The path to the algorithm's assembly</param>
        /// <param name="workerThread">The worker thread instance</param>
        public void Run(AlgorithmNodePacket job, AlgorithmManager manager, string assemblyPath, WorkerThread workerThread)
        {
            var marketHoursDatabaseTask = Task.Run(() => StaticInitializations());

            var algorithm        = default(IAlgorithm);
            var algorithmManager = manager;

            try
            {
                //Reset thread holders.
                var    initializeComplete = false;
                Thread threadAlphas       = null;

                //-> Initialize messaging system
                SystemHandlers.Notify.SetAuthentication(job);

                //-> Set the result handler type for this algorithm job, and launch the associated result thread.
                AlgorithmHandlers.Results.Initialize(job, SystemHandlers.Notify, SystemHandlers.Api, AlgorithmHandlers.Transactions);

                IBrokerage  brokerage    = null;
                DataManager dataManager  = null;
                var         synchronizer = _liveMode ? new LiveSynchronizer() : new Synchronizer();
                try
                {
                    // we get the mhdb before creating the algorithm instance,
                    // since the algorithm constructor will use it
                    var marketHoursDatabase = marketHoursDatabaseTask.Result;

                    AlgorithmHandlers.Setup.WorkerThread = workerThread;

                    // Save algorithm to cache, load algorithm instance:
                    algorithm = AlgorithmHandlers.Setup.CreateAlgorithmInstance(job, assemblyPath);

                    // Set algorithm in ILeanManager
                    SystemHandlers.LeanManager.SetAlgorithm(algorithm);

                    // initialize the alphas handler with the algorithm instance
                    AlgorithmHandlers.Alphas.Initialize(job, algorithm, SystemHandlers.Notify, SystemHandlers.Api);

                    // initialize the object store
                    AlgorithmHandlers.ObjectStore.Initialize(algorithm.Name, job.UserId, job.ProjectId, job.UserToken, job.Controls);

                    // notify the user of any errors w/ object store persistence
                    AlgorithmHandlers.ObjectStore.ErrorRaised += (sender, args) => algorithm.Debug($"ObjectStore Persistence Error: {args.Error.Message}");

                    // Initialize the brokerage
                    IBrokerageFactory factory;
                    brokerage = AlgorithmHandlers.Setup.CreateBrokerage(job, algorithm, out factory);

                    var symbolPropertiesDatabase = SymbolPropertiesDatabase.FromDataFolder();

                    var registeredTypesProvider = new RegisteredSecurityDataTypesProvider();
                    var securityService         = new SecurityService(algorithm.Portfolio.CashBook,
                                                                      marketHoursDatabase,
                                                                      symbolPropertiesDatabase,
                                                                      algorithm,
                                                                      registeredTypesProvider,
                                                                      new SecurityCacheProvider(algorithm.Portfolio));

                    algorithm.Securities.SetSecurityService(securityService);

                    dataManager = new DataManager(AlgorithmHandlers.DataFeed,
                                                  new UniverseSelection(
                                                      algorithm,
                                                      securityService),
                                                  algorithm,
                                                  algorithm.TimeKeeper,
                                                  marketHoursDatabase,
                                                  _liveMode,
                                                  registeredTypesProvider);

                    AlgorithmHandlers.Results.SetDataManager(dataManager);
                    algorithm.SubscriptionManager.SetDataManager(dataManager);

                    synchronizer.Initialize(algorithm, dataManager);

                    // Initialize the data feed before we initialize so he can intercept added securities/universes via events
                    AlgorithmHandlers.DataFeed.Initialize(
                        algorithm,
                        job,
                        AlgorithmHandlers.Results,
                        AlgorithmHandlers.MapFileProvider,
                        AlgorithmHandlers.FactorFileProvider,
                        AlgorithmHandlers.DataProvider,
                        dataManager,
                        (IDataFeedTimeProvider)synchronizer);

                    // set the order processor on the transaction manager (needs to be done before initializing BrokerageHistoryProvider)
                    algorithm.Transactions.SetOrderProcessor(AlgorithmHandlers.Transactions);
                    algorithm.SetOrderEventProvider(AlgorithmHandlers.Transactions);

                    // set the history provider before setting up the algorithm
                    var historyProvider = GetHistoryProvider(job.HistoryProvider);
                    if (historyProvider is BrokerageHistoryProvider)
                    {
                        (historyProvider as BrokerageHistoryProvider).SetBrokerage(brokerage);
                    }

                    var historyDataCacheProvider = new ZipDataCacheProvider(AlgorithmHandlers.DataProvider, isDataEphemeral: _liveMode);
                    historyProvider.Initialize(
                        new HistoryProviderInitializeParameters(
                            job,
                            SystemHandlers.Api,
                            AlgorithmHandlers.DataProvider,
                            historyDataCacheProvider,
                            AlgorithmHandlers.MapFileProvider,
                            AlgorithmHandlers.FactorFileProvider,
                            progress =>
                    {
                        // send progress updates to the result handler only during initialization
                        if (!algorithm.GetLocked() || algorithm.IsWarmingUp)
                        {
                            AlgorithmHandlers.Results.SendStatusUpdate(AlgorithmStatus.History,
                                                                       Invariant($"Processing history {progress}%..."));
                        }
                    },
                            // disable parallel history requests for live trading
                            parallelHistoryRequestsEnabled: !_liveMode
                            )
                        );

                    historyProvider.InvalidConfigurationDetected += (sender, args) => { AlgorithmHandlers.Results.ErrorMessage(args.Message); };
                    historyProvider.NumericalPrecisionLimited    += (sender, args) => { AlgorithmHandlers.Results.DebugMessage(args.Message); };
                    historyProvider.DownloadFailed      += (sender, args) => { AlgorithmHandlers.Results.ErrorMessage(args.Message, args.StackTrace); };
                    historyProvider.ReaderErrorDetected += (sender, args) => { AlgorithmHandlers.Results.RuntimeError(args.Message, args.StackTrace); };

                    algorithm.HistoryProvider = historyProvider;

                    // initialize the default brokerage message handler
                    algorithm.BrokerageMessageHandler = factory.CreateBrokerageMessageHandler(algorithm, job, SystemHandlers.Api);

                    //Initialize the internal state of algorithm and job: executes the algorithm.Initialize() method.
                    initializeComplete = AlgorithmHandlers.Setup.Setup(new SetupHandlerParameters(dataManager.UniverseSelection, algorithm, brokerage, job, AlgorithmHandlers.Results, AlgorithmHandlers.Transactions, AlgorithmHandlers.RealTime, AlgorithmHandlers.ObjectStore));

                    // set this again now that we've actually added securities
                    AlgorithmHandlers.Results.SetAlgorithm(algorithm, AlgorithmHandlers.Setup.StartingPortfolioValue);

                    // alpha handler needs start/end dates to determine sample step sizes
                    AlgorithmHandlers.Alphas.OnAfterAlgorithmInitialized(algorithm);

                    //If there are any reasons it failed, pass these back to the IDE.
                    if (!initializeComplete || algorithm.ErrorMessages.Count > 0 || AlgorithmHandlers.Setup.Errors.Count > 0)
                    {
                        initializeComplete = false;
                        //Get all the error messages: internal in algorithm and external in setup handler.
                        var errorMessage = string.Join(",", algorithm.ErrorMessages);
                        errorMessage += string.Join(",", AlgorithmHandlers.Setup.Errors.Select(e =>
                        {
                            var message = e.Message;
                            if (e.InnerException != null)
                            {
                                var err  = _exceptionInterpreter.Value.Interpret(e.InnerException, _exceptionInterpreter.Value);
                                message += _exceptionInterpreter.Value.GetExceptionMessageHeader(err);
                            }
                            return(message);
                        }));
                        Log.Error("Engine.Run(): " + errorMessage);
                        AlgorithmHandlers.Results.RuntimeError(errorMessage);
                        SystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, errorMessage);
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    var runtimeMessage = "Algorithm.Initialize() Error: " + err.Message + " Stack Trace: " + err;
                    AlgorithmHandlers.Results.RuntimeError(runtimeMessage, err.ToString());
                    SystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, runtimeMessage);
                }


                // log the job endpoints
                Log.Trace("JOB HANDLERS: ");
                Log.Trace("         DataFeed:     " + AlgorithmHandlers.DataFeed.GetType().FullName);
                Log.Trace("         Setup:        " + AlgorithmHandlers.Setup.GetType().FullName);
                Log.Trace("         RealTime:     " + AlgorithmHandlers.RealTime.GetType().FullName);
                Log.Trace("         Results:      " + AlgorithmHandlers.Results.GetType().FullName);
                Log.Trace("         Transactions: " + AlgorithmHandlers.Transactions.GetType().FullName);
                Log.Trace("         Alpha:        " + AlgorithmHandlers.Alphas.GetType().FullName);
                Log.Trace("         ObjectStore:  " + AlgorithmHandlers.ObjectStore.GetType().FullName);
                if (algorithm?.HistoryProvider != null)
                {
                    Log.Trace("         History Provider:     " + algorithm.HistoryProvider.GetType().FullName);
                }
                if (job is LiveNodePacket)
                {
                    Log.Trace("         Brokerage:      " + brokerage?.GetType().FullName);
                }

                //-> Using the job + initialization: load the designated handlers:
                if (initializeComplete)
                {
                    // notify the LEAN manager that the algorithm is initialized and starting
                    SystemHandlers.LeanManager.OnAlgorithmStart();

                    //-> Reset the backtest stopwatch; we're now running the algorithm.
                    var startTime = DateTime.Now;

                    //Set algorithm as locked; set it to live mode if we're trading live, and set it to locked for no further updates.
                    algorithm.SetAlgorithmId(job.AlgorithmId);
                    algorithm.SetLocked();

                    //Load the associated handlers for transaction and realtime events:
                    AlgorithmHandlers.Transactions.Initialize(algorithm, brokerage, AlgorithmHandlers.Results);
                    AlgorithmHandlers.RealTime.Setup(algorithm, job, AlgorithmHandlers.Results, SystemHandlers.Api, algorithmManager.TimeLimit);

                    // wire up the brokerage message handler
                    brokerage.Message += (sender, message) =>
                    {
                        algorithm.BrokerageMessageHandler.Handle(message);

                        // fire brokerage message events
                        algorithm.OnBrokerageMessage(message);
                        switch (message.Type)
                        {
                        case BrokerageMessageType.Disconnect:
                            algorithm.OnBrokerageDisconnect();
                            break;

                        case BrokerageMessageType.Reconnect:
                            algorithm.OnBrokerageReconnect();
                            break;
                        }
                    };

                    //Send status to user the algorithm is now executing.
                    AlgorithmHandlers.Results.SendStatusUpdate(AlgorithmStatus.Running);

                    //Launch the alpha handler into dedicated thread
                    threadAlphas = new Thread(() => AlgorithmHandlers.Alphas.Run())
                    {
                        IsBackground = true, Name = "Alpha Thread"
                    };
                    threadAlphas.Start(); // Alpha thread for processing algorithm alpha insights

                    // Result manager scanning message queue: (started earlier)
                    AlgorithmHandlers.Results.DebugMessage(
                        $"Launching analysis for {job.AlgorithmId} with LEAN Engine v{Globals.Version}");

                    try
                    {
                        //Create a new engine isolator class
                        var isolator = new Isolator();

                        // Execute the Algorithm Code:
                        var complete = isolator.ExecuteWithTimeLimit(AlgorithmHandlers.Setup.MaximumRuntime, algorithmManager.TimeLimit.IsWithinLimit, () =>
                        {
                            try
                            {
                                //Run Algorithm Job:
                                // -> Using this Data Feed,
                                // -> Send Orders to this TransactionHandler,
                                // -> Send Results to ResultHandler.
                                algorithmManager.Run(job, algorithm, synchronizer, AlgorithmHandlers.Transactions, AlgorithmHandlers.Results, AlgorithmHandlers.RealTime, SystemHandlers.LeanManager, AlgorithmHandlers.Alphas, isolator.CancellationToken);
                            }
                            catch (Exception err)
                            {
                                //Debugging at this level is difficult, stack trace needed.
                                Log.Error(err);
                                algorithm.RunTimeError = err;
                                algorithmManager.SetStatus(AlgorithmStatus.RuntimeError);
                                return;
                            }

                            Log.Trace("Engine.Run(): Exiting Algorithm Manager");
                        }, job.Controls.RamAllocation, workerThread: workerThread);

                        if (!complete)
                        {
                            Log.Error("Engine.Main(): Failed to complete in time: " + AlgorithmHandlers.Setup.MaximumRuntime.ToStringInvariant("F"));
                            throw new Exception("Failed to complete algorithm within " + AlgorithmHandlers.Setup.MaximumRuntime.ToStringInvariant("F")
                                                + " seconds. Please make it run faster.");
                        }

                        // Algorithm runtime error:
                        if (algorithm.RunTimeError != null)
                        {
                            HandleAlgorithmError(job, algorithm.RunTimeError);
                        }
                    }
                    catch (Exception err)
                    {
                        //Error running the user algorithm: purge datafeed, send error messages, set algorithm status to failed.
                        algorithm.RunTimeError = err;
                        algorithm.SetStatus(AlgorithmStatus.RuntimeError);
                        HandleAlgorithmError(job, err);
                    }

                    // notify the LEAN manager that the algorithm has finished
                    SystemHandlers.LeanManager.OnAlgorithmEnd();

                    try
                    {
                        var csvTransactionsFileName = Config.Get("transaction-log");
                        if (!string.IsNullOrEmpty(csvTransactionsFileName))
                        {
                            SaveListOfTrades(AlgorithmHandlers.Transactions, csvTransactionsFileName);
                        }

                        if (!_liveMode)
                        {
                            //Diagnostics Completed, Send Result Packet:
                            var totalSeconds = (DateTime.Now - startTime).TotalSeconds;
                            var dataPoints   = algorithmManager.DataPoints + algorithm.HistoryProvider.DataPointCount;
                            var kps          = dataPoints / (double)1000 / totalSeconds;
                            AlgorithmHandlers.Results.DebugMessage($"Algorithm Id:({job.AlgorithmId}) completed in {totalSeconds:F2} seconds at {kps:F0}k data points per second. Processing total of {dataPoints:N0} data points.");
                        }
                    }
                    catch (Exception err)
                    {
                        Log.Error(err, "Error sending analysis results");
                    }

                    //Before we return, send terminate commands to close up the threads
                    AlgorithmHandlers.Transactions.Exit();
                    AlgorithmHandlers.RealTime.Exit();
                    AlgorithmHandlers.Alphas.Exit();
                    dataManager?.RemoveAllSubscriptions();
                    workerThread?.Dispose();
                }
                // Close data feed. Could be running even if algorithm initialization failed
                AlgorithmHandlers.DataFeed.Exit();

                //Close result handler:
                AlgorithmHandlers.Results.Exit();

                //Wait for the threads to complete:
                var millisecondInterval  = 10;
                var millisecondTotalWait = 0;
                while ((AlgorithmHandlers.Results.IsActive ||
                        (AlgorithmHandlers.Transactions != null && AlgorithmHandlers.Transactions.IsActive) ||
                        (AlgorithmHandlers.DataFeed != null && AlgorithmHandlers.DataFeed.IsActive) ||
                        (AlgorithmHandlers.RealTime != null && AlgorithmHandlers.RealTime.IsActive) ||
                        (AlgorithmHandlers.Alphas != null && AlgorithmHandlers.Alphas.IsActive)) &&
                       millisecondTotalWait < 30 * 1000)
                {
                    Thread.Sleep(millisecondInterval);
                    if (millisecondTotalWait % (millisecondInterval * 10) == 0)
                    {
                        Log.Trace("Waiting for threads to exit...");
                    }
                    millisecondTotalWait += millisecondInterval;
                }

                //Terminate threads still in active state.
                if (threadAlphas != null && threadAlphas.IsAlive)
                {
                    threadAlphas.Abort();
                }

                if (brokerage != null)
                {
                    Log.Trace("Engine.Run(): Disconnecting from brokerage...");
                    brokerage.Disconnect();
                    brokerage.Dispose();
                }
                if (AlgorithmHandlers.Setup != null)
                {
                    Log.Trace("Engine.Run(): Disposing of setup handler...");
                    AlgorithmHandlers.Setup.Dispose();
                }
                Log.Trace("Engine.Main(): Analysis Completed and Results Posted.");
            }
            catch (Exception err)
            {
                Log.Error(err, "Error running algorithm");
            }
            finally
            {
                //No matter what for live mode; make sure we've set algorithm status in the API for "not running" conditions:
                if (_liveMode && algorithmManager.State != AlgorithmStatus.Running && algorithmManager.State != AlgorithmStatus.RuntimeError)
                {
                    SystemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, algorithmManager.State);
                }

                AlgorithmHandlers.Results.Exit();
                AlgorithmHandlers.DataFeed.Exit();
                AlgorithmHandlers.Transactions.Exit();
                AlgorithmHandlers.RealTime.Exit();
            }
        }
コード例 #30
0
ファイル: Function.cs プロジェクト: Chuluunsukh/VS_tabi
        public static void SaveCheckListBox(DevExpress.XtraEditors.CheckedListBoxControl CheckListBox, string Tablename, string LinkFieldvalue, string LinkFieldName, string FieldName, string KeyFieldName, string SeqName, SecurityService.UserInfo userInfo, ref List<string> SqlList)
        {
            try
            {
                if (LinkFieldvalue != null)
                {
                    SqlList.Add("Delete " + Tablename + " Where " + LinkFieldName + " = '" + LinkFieldvalue + "'");
                    int i = 0;

                    while (i < CheckListBox.ItemCount)
                    {
                        if (CheckListBox.GetItemCheckState(i) == CheckState.Checked)
                        {
                            string ID = "";
                            string[] fields = { LinkFieldName, FieldName, LinkFieldvalue, CheckListBox.GetItemValue(i).ToString() };

                            SqlList.Add(Services.Database.SaveTableData(Tablename, KeyFieldName, ref ID, SeqName, userInfo.LoginUserName, fields));
                        }
                        i = i + 1;
                    }
                }
            }
            catch (Exception Err)
            {
                MessageBox.Show("Дараахи алдаа гарлаа : " + Err.Message.ToString(), "Алдаа", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #31
0
ファイル: Function.cs プロジェクト: Chuluunsukh/VS_tabi
 public static bool SaveCheckComboBox(DevExpress.XtraEditors.CheckedComboBoxEdit chLstComboBox, string TableName, string LinkFieldValue, string LinkFieldName, string SeqName, string ConstTableName, string ConstFieldName, SecurityService.UserInfo userInfo, ref List<string> SqlList)
 {
     try
     {
         if (LinkFieldValue != null)
         {
             SqlList.Add("Delete " + TableName + " Where " + LinkFieldName + " = '" + LinkFieldValue + "'");
             string TempName = "", Temp_ID = "", DelTem = ",", ID = "";
             for (int i = 0; i < chLstComboBox.Properties.Items.Count; i++)
                 if (chLstComboBox.Properties.Items[i].CheckState == CheckState.Checked)
                 {
                     TempName = chLstComboBox.Properties.Items[i].ToString().Trim(DelTem.ToCharArray());
                     Temp_ID = Services.Database.SelectFieldValue(ConstTableName, "ID", "Name = '" + TempName + "'");
                     string[] Fields = { LinkFieldName, ConstFieldName, LinkFieldValue, Temp_ID };
                     SqlList.Add(Services.Database.SaveTableData(TableName, "ID", ref ID, SeqName, userInfo.LoginUserName, Fields));
                 }
             return true;
         }
         else
             return false;
     }
     catch
     {
         return false;
     }
 }
コード例 #32
0
        public ResponseModel GetFileUploadLogs()
        {
            ResponseModel         objResponseModel   = new ResponseModel();
            List <FileUploadLogs> objFileUploadModel = new List <FileUploadLogs>();
            int    statusCode    = 0;
            string statusMessage = "";
            int    fileUploadFor = 0;

            try
            {
                //Get token (Double encrypted) and get the tenant id
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromTokenCache(Cache, SecurityService.DecryptStringAES(token));

                SettingsCaller newAlert = new SettingsCaller();

                objFileUploadModel = newAlert.GetFileUploadLogs(new FileUploadService(Cache, Db), authenticate.TenantId, fileUploadFor);
                statusCode         = objFileUploadModel.Count == 0 ? (int)EnumMaster.StatusCode.RecordNotFound : (int)EnumMaster.StatusCode.Success;

                statusMessage = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);

                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = objFileUploadModel;
            }
            catch (Exception)
            {
                throw;
            }

            return(objResponseModel);
        }
コード例 #33
0
        public static void MembersSeed(this ModelBuilder modelBuilder)
        {
            var securityService = new SecurityService();
            var salts           = new List <string>();

            for (int i = 0; i < 20; i++)
            {
                salts.Add(securityService.GenerateSalt());
            }

            modelBuilder.Entity <Member>().HasData(
                new Member
            {
                Id                = 1,
                FirstName         = "Admin",
                LastName          = "Admin",
                Username          = "******",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[0],
                PasswordHash      = securityService.GenerateHash(salts[0], "test"),
                LocalCommitteeId  = 1,
                RoleId            = 1,
                FunctionalFieldId = 1,
                PhoneNumber       = "03355123",
                Gender            = 'M'
            },
                new Member
            {
                Id                = 2,
                FirstName         = "Amel",
                LastName          = "Music",
                Username          = "******",
                Address           = "Dobrinjska 12",
                EmailAddress      = "*****@*****.**",
                PhoneNumber       = "062123344",
                PasswordSalt      = salts[4],
                PasswordHash      = securityService.GenerateHash(salts[4], "test"),
                RoleId            = 2,
                LocalCommitteeId  = 2,
                FunctionalFieldId = 1,
                Gender            = 'M'
            },
                new Member
            {
                Id                = 3,
                FirstName         = "Sulejman",
                LastName          = "Tutnjevic",
                Username          = "******",
                Address           = "Safeta Zajke 298",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[1],
                PasswordHash      = securityService.GenerateHash(salts[1], "test"),
                PhoneNumber       = "062123344",
                RoleId            = 3,
                LocalCommitteeId  = 2,
                FunctionalFieldId = 2,
                Gender            = 'M'
            },
                new Member
            {
                Id                = 4,
                FirstName         = "Tarik",
                LastName          = "Bucan",
                Username          = "******",
                Address           = "Zahira Panjete 298",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[2],
                PasswordHash      = securityService.GenerateHash(salts[2], "test"),
                PhoneNumber       = "062123344",
                RoleId            = 4,
                LocalCommitteeId  = 2,
                FunctionalFieldId = 2,
                Gender            = 'M'
            },
                new Member
            {
                Id                = 5,
                FirstName         = "Selma",
                LastName          = "Idic",
                Username          = "******",
                Address           = "Grbavica 12",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[3],
                PasswordHash      = securityService.GenerateHash(salts[3], "test"),
                PhoneNumber       = "062123344",
                RoleId            = 4,
                LocalCommitteeId  = 2,
                FunctionalFieldId = 2,
                Gender            = 'M'
            },
                new Member
            {
                Id                = 6,
                FirstName         = "Emir",
                LastName          = "Zukic",
                Username          = "******",
                Address           = "Doglodi 12",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[5],
                PasswordHash      = securityService.GenerateHash(salts[5], "test"),
                PhoneNumber       = "062123344",
                RoleId            = 4,
                LocalCommitteeId  = 2,
                FunctionalFieldId = 2,
                Gender            = 'M'
            },
                new Member
            {
                Id                = 7,
                FirstName         = "Dora",
                LastName          = "Glinac",
                Username          = "******",
                Address           = "Grbavica 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[6],
                PasswordHash      = securityService.GenerateHash(salts[6], "test"),
                PhoneNumber       = "062123344",
                RoleId            = 4,
                LocalCommitteeId  = 2,
                FunctionalFieldId = 3,
                Gender            = 'F'
            },
                new Member
            {
                Id                = 8,
                FirstName         = "Nikola",
                LastName          = "Bujak",
                Username          = "******",
                Address           = "Borik 4",
                EmailAddress      = "*****@*****.**",
                PhoneNumber       = "062123344",
                PasswordSalt      = salts[7],
                PasswordHash      = securityService.GenerateHash(salts[7], "test"),
                RoleId            = 3,
                LocalCommitteeId  = 2,
                FunctionalFieldId = 3,
                Gender            = 'M'
            },
                new Member
            {
                Id                = 9,
                FirstName         = "Nevzudin",
                LastName          = "Dosic",
                Username          = "******",
                Address           = "Gospodska 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[8],
                PasswordHash      = securityService.GenerateHash(salts[8], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'M',
                RoleId            = 4,
                LocalCommitteeId  = 2,
                FunctionalFieldId = 3
            },
                new Member
            {
                Id                = 10,
                FirstName         = "Klara",
                LastName          = "Zovko",
                Username          = "******",
                Address           = "Mostar 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[9],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'F',
                RoleId            = 3,
                FunctionalFieldId = 4,
                LocalCommitteeId  = 2
            },
                new Member
            {
                Id                = 11,
                FirstName         = "Hana",
                LastName          = "Kulenovic",
                Username          = "******",
                Address           = "Centar 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[9],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'F',
                RoleId            = 4,
                FunctionalFieldId = 5,
                LocalCommitteeId  = 2
            },
                new Member
            {
                Id                = 12,
                FirstName         = "Haris",
                LastName          = "Brulic",
                Username          = "******",
                Address           = "Test 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[10],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'M',
                RoleId            = 4,
                FunctionalFieldId = 3,
                LocalCommitteeId  = 3
            },
                new Member
            {
                Id                = 13,
                FirstName         = "Ajdin",
                LastName          = "Kahrimanovic",
                Username          = "******",
                Address           = "Test 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[11],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'M',
                RoleId            = 4,
                FunctionalFieldId = 4,
                LocalCommitteeId  = 3
            },
                new Member
            {
                Id                = 14,
                FirstName         = "Denis",
                LastName          = "Music",
                Username          = "******",
                Address           = "Test 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[12],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'M',
                RoleId            = 4,
                FunctionalFieldId = 5,
                LocalCommitteeId  = 3
            },
                new Member
            {
                Id                = 15,
                FirstName         = "Elmir",
                LastName          = "Babovic",
                Username          = "******",
                Address           = "Test 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[13],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'M',
                RoleId            = 4,
                FunctionalFieldId = 4,
                LocalCommitteeId  = 3
            },
                new Member
            {
                Id                = 16,
                FirstName         = "Irma",
                LastName          = "Saric",
                Username          = "******",
                Address           = "Test 6",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[15],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "0621112222",
                Gender            = 'M',
                RoleId            = 4,
                FunctionalFieldId = 2,
                LocalCommitteeId  = 4
            },
                new Member
            {
                Id                = 17,
                FirstName         = "Ajla",
                LastName          = "Brulic",
                Username          = "******",
                Address           = "Dobrinja 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[15],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'M',
                RoleId            = 4,
                FunctionalFieldId = 3,
                LocalCommitteeId  = 4
            },
                new Member
            {
                Id                = 18,
                FirstName         = "Haris",
                LastName          = "Brulic",
                Username          = "******",
                Address           = "Test 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[15],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062123344",
                Gender            = 'M',
                RoleId            = 4,
                FunctionalFieldId = 4,
                LocalCommitteeId  = 4
            },
                new Member
            {
                Id                = 19,
                FirstName         = "Nejira",
                LastName          = "Vrana",
                Username          = "******",
                Address           = "Test 4",
                EmailAddress      = "*****@*****.**",
                PasswordSalt      = salts[15],
                PasswordHash      = securityService.GenerateHash(salts[9], "test"),
                PhoneNumber       = "062567948",
                Gender            = 'Z',
                RoleId            = 4,
                FunctionalFieldId = 3,
                LocalCommitteeId  = 4
            }
                );
        }
コード例 #34
0
        public void FastExitsDoNotThrowUnhandledExceptions()
        {
            var algorithm = new AlgorithmStub();

            // job is used to send into DataQueueHandler
            var job = new LiveNodePacket();

            // result handler is used due to dependency in SubscriptionDataReader
            var resultHandler = new BacktestingResultHandler();

            var feed = new TestableLiveTradingDataFeed();
            var marketHoursDatabase      = MarketHoursDatabase.FromDataFolder();
            var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder();
            var securityService          = new SecurityService(
                algorithm.Portfolio.CashBook,
                marketHoursDatabase,
                symbolPropertiesDataBase,
                algorithm);

            algorithm.Securities.SetSecurityService(securityService);
            var dataManager = new DataManager(feed,
                                              new UniverseSelection(algorithm, securityService),
                                              algorithm,
                                              algorithm.TimeKeeper,
                                              marketHoursDatabase,
                                              true);

            algorithm.SubscriptionManager.SetDataManager(dataManager);
            var synchronizer = new TestableLiveSynchronizer();

            synchronizer.Initialize(algorithm, dataManager);
            algorithm.AddSecurities(Resolution.Tick, Enumerable.Range(0, 20).Select(x => x.ToString()).ToList());
            var getNextTicksFunction = Enumerable.Range(0, 20).Select(x => new Tick {
                Symbol = SymbolCache.GetSymbol(x.ToString())
            }).ToList();

            feed.DataQueueHandler = new FuncDataQueueHandler(handler => getNextTicksFunction);
            var mapFileProvider = new LocalDiskMapFileProvider();
            var fileProvider    = new DefaultDataProvider();

            feed.Initialize(
                algorithm,
                job,
                resultHandler,
                mapFileProvider,
                new LocalDiskFactorFileProvider(mapFileProvider),
                fileProvider,
                dataManager,
                synchronizer);

            var unhandledExceptionWasThrown = false;

            try
            {
                feed.Exit();
            }
            catch (Exception ex)
            {
                QuantConnect.Logging.Log.Error(ex.ToString());
                unhandledExceptionWasThrown = true;
            }

            Thread.Sleep(500);
            Assert.IsFalse(unhandledExceptionWasThrown);
        }
コード例 #35
0
        /// <summary>
        /// Creates an instance of the PortfolioLooper class
        /// </summary>
        /// <param name="startingCash">Equity curve</param>
        /// <param name="orders">Order events</param>
        /// <param name="resolution">Optional parameter to override default resolution (Hourly)</param>
        private PortfolioLooper(double startingCash, List <Order> orders, Resolution resolution = _resolution)
        {
            // Initialize the providers that the HistoryProvider requires
            var factorFileProvider = Composer.Instance.GetExportedValueByTypeName <IFactorFileProvider>("LocalDiskFactorFileProvider");
            var mapFileProvider    = Composer.Instance.GetExportedValueByTypeName <IMapFileProvider>("LocalDiskMapFileProvider");
            var dataCacheProvider  = new ZipDataCacheProvider(new DefaultDataProvider(), false);
            var historyProvider    = Composer.Instance.GetExportedValueByTypeName <IHistoryProvider>("SubscriptionDataReaderHistoryProvider");

            var dataPermissionManager = new DataPermissionManager();

            historyProvider.Initialize(new HistoryProviderInitializeParameters(null, null, null, dataCacheProvider, mapFileProvider, factorFileProvider, (_) => { }, false, dataPermissionManager));
            Algorithm = new PortfolioLooperAlgorithm((decimal)startingCash, orders);
            Algorithm.SetHistoryProvider(historyProvider);

            // Dummy LEAN datafeed classes and initializations that essentially do nothing
            var job  = new BacktestNodePacket(1, 2, "3", null, 9m, $"");
            var feed = new MockDataFeed();

            // Create MHDB and Symbol properties DB instances for the DataManager
            var marketHoursDatabase      = MarketHoursDatabase.FromDataFolder();
            var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder();

            _dataManager = new DataManager(feed,
                                           new UniverseSelection(
                                               Algorithm,
                                               new SecurityService(Algorithm.Portfolio.CashBook,
                                                                   marketHoursDatabase,
                                                                   symbolPropertiesDataBase,
                                                                   Algorithm,
                                                                   RegisteredSecurityDataTypesProvider.Null,
                                                                   new SecurityCacheProvider(Algorithm.Portfolio)),
                                               dataPermissionManager),
                                           Algorithm,
                                           Algorithm.TimeKeeper,
                                           marketHoursDatabase,
                                           false,
                                           RegisteredSecurityDataTypesProvider.Null,
                                           dataPermissionManager);

            _securityService = new SecurityService(Algorithm.Portfolio.CashBook,
                                                   marketHoursDatabase,
                                                   symbolPropertiesDataBase,
                                                   Algorithm,
                                                   RegisteredSecurityDataTypesProvider.Null,
                                                   new SecurityCacheProvider(Algorithm.Portfolio));

            var transactions = new BacktestingTransactionHandler();
            var results      = new BacktestingResultHandler();

            // Initialize security services and other properties so that we
            // don't get null reference exceptions during our re-calculation
            Algorithm.Securities.SetSecurityService(_securityService);
            Algorithm.SubscriptionManager.SetDataManager(_dataManager);

            // Initializes all the proper Securities from the orders provided by the user
            Algorithm.FromOrders(orders);

            // Initialize the algorithm
            Algorithm.Initialize();
            Algorithm.PostInitialize();

            // More initialization, this time with Algorithm and other misc. classes
            results.Initialize(job, new Messaging.Messaging(), new Api.Api(), transactions);
            results.SetAlgorithm(Algorithm, Algorithm.Portfolio.TotalPortfolioValue);
            transactions.Initialize(Algorithm, new BacktestingBrokerage(Algorithm), results);
            feed.Initialize(Algorithm, job, results, null, null, null, _dataManager, null, null);

            // Begin setting up the currency conversion feed if needed
            var coreSecurities = Algorithm.Securities.Values.ToList();

            if (coreSecurities.Any(x => x.Symbol.SecurityType == SecurityType.Forex || x.Symbol.SecurityType == SecurityType.Crypto))
            {
                BaseSetupHandler.SetupCurrencyConversions(Algorithm, _dataManager.UniverseSelection);
                var conversionSecurities = Algorithm.Securities.Values.Where(s => !coreSecurities.Contains(s)).ToList();

                // Skip the history request if we don't need to convert anything
                if (conversionSecurities.Any())
                {
                    // Point-in-time Slices to convert FX and Crypto currencies to the portfolio currency
                    _conversionSlices = GetHistory(Algorithm, conversionSecurities, resolution);
                }
            }
        }
コード例 #36
0
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.IsChildAction)
            {
                return;
            }

            //**************
            // Grab the username from the session. returns null or the username
            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
                //clear the session
                if (filterContext.HttpContext.Session != null)
                {
                    filterContext.HttpContext.Session.Abandon();
                }

                SecurityService.Logout();
                //redirect to the login page if not already going there
                filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Security", action = "Login" }));
            }
            //If the user is authenticated, compare the usernames in the session and forms auth cookie
            //WebSecurity.Initialized is true
            else if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                //Do the usernames match?
                if (filterContext.HttpContext.Session.CurrentUser() != null)
                {
                    //If not, log the user out and clear their session
                    SecurityService.Logout();
                    if (filterContext.HttpContext.Session != null)
                    {
                        filterContext.HttpContext.Session.Abandon();
                    }
                    //redirect to the login page
                    filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Security", action = "Login" }));
                }
            }
            //If the user is not authenticated, but the session contains a username
            //Security.Initialized is true
            //Security.IsAuthenticated is false
            else if (filterContext.HttpContext.Session.CurrentUser() != null)
            {
                //log the user out (just in case) and clear the session
                SecurityService.Logout();
                if (filterContext.HttpContext.Session != null)
                {
                    //Clear session
                    filterContext.HttpContext.Session.Clear();
                    filterContext.HttpContext.Session.Abandon();
                    filterContext.HttpContext.Session.Abandon();

                    //Clears out Session
                    filterContext.HttpContext.Response.Cookies.Clear();

                    // clear authentication cookie
                    filterContext.HttpContext.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                    filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));

                    HttpCookie cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
                    if (cookie != null)
                    {
                        cookie.Expires = DateTime.Now.AddDays(-1);
                        filterContext.HttpContext.Response.Cookies.Add(cookie);
                    }
                }

                //redirect to the login page
                filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Security", action = "Login" }));
            }
            //**************

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            Exception exception = filterContext.Exception;

            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
            // ignore it.


            int httpCode = new HttpException(null, exception).GetHttpCode();

            if (httpCode != 500)
            {
                if (httpCode == 401)
                {
                    HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, "Error", "AccessDenied");
                    filterContext.Result = new ViewResult
                    {
                        ViewName = "AccessDenied",
                        ViewData = new ViewDataDictionary <HandleErrorInfo>(model)
                    };
                    filterContext.ExceptionHandled = true;
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 401;
                }

                if (httpCode == 404)
                {
                    HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, "Error", "NotFound");
                    filterContext.Result = new ViewResult
                    {
                        ViewName = "Not found",
                        ViewData = new ViewDataDictionary <HandleErrorInfo>(model)
                    };
                    filterContext.ExceptionHandled = true;
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 404;
                }
                return;
            }



            if (!ExceptionType.IsInstanceOfType(exception))
            {
                return;
            }

            string          controllerName = (string)filterContext.RouteData.Values["controller"];
            string          actionName     = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model1         = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

            filterContext.Result = new ViewResult
            {
                ViewName   = View,
                MasterName = Master,
                ViewData   = new ViewDataDictionary <HandleErrorInfo>(model1),
                TempData   = filterContext.Controller.TempData
            };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            // Certain versions of IIS will sometimes use their own error page when
            // they detect a server error. Setting this property indicates that we
            // want it to try to render ASP.NET MVC's error page instead.
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
コード例 #37
0
        private RenderPageViewModel CreatePageViewModel(Page renderingPage, List <PageContent> allPageContents, Page page,
                                                        GetPageToRenderRequest request, List <Page> childPagesList)
        {
            if (request.PreviewPageContentId == null && !request.IsAuthenticated && page.Status != PageStatus.Published)
            {
                throw new HttpException(403, "403 Access Forbidden");
            }

            // Preview and published pages can be accessible to users without content managing roles
            // Unpublished pages can be accessible only to content managers
            if (page.Status != PageStatus.Published && page.Status != PageStatus.Preview && !request.HasContentAccess)
            {
                if (!cmsConfiguration.Security.AccessControlEnabled)
                {
                    return(null); // Force 404.
                }
            }

            var renderPageViewModel = new RenderPageViewModel(page);

            renderPageViewModel.CanManageContent   = request.CanManageContent;
            renderPageViewModel.AreRegionsEditable = request.CanManageContent && !childPagesList.Any();

            if (page.Layout != null)
            {
                renderPageViewModel.LayoutPath = page.Layout.LayoutPath;
                renderPageViewModel.Options    = GetMergedOptionValues(page.Layout.LayoutOptions, page.Options, childPagesList);
                renderPageViewModel.Regions    = page.Layout.LayoutRegions
                                                 .Distinct()
                                                 .Select(f => new PageRegionViewModel
                {
                    RegionId         = f.Region.Id,
                    RegionIdentifier = f.Region.RegionIdentifier
                })
                                                 .ToList();
            }
            else if (page.MasterPage != null)
            {
                var masterPage = renderingPage.MasterPages.FirstOrDefault(p => p.Master.Id == page.MasterPage.Id);
                if (masterPage == null)
                {
                    throw new InvalidOperationException(string.Format("Cannot find a master page in master pages path collection for page {0}.", request.PageUrl));
                }

                childPagesList.Insert(0, page);
                renderPageViewModel.MasterPage = CreatePageViewModel(renderingPage, allPageContents, masterPage.Master, request, childPagesList);
                childPagesList.Remove(page);

                var masterOptions = new List <PageOption>();
                foreach (var optionValue in renderingPage.MasterPages
                         .SelectMany(mp => mp.Master.Options.Where(optionValue => !masterOptions.Contains(optionValue))))
                {
                    masterOptions.Add(optionValue);
                }

                renderPageViewModel.Options = GetMergedOptionValues(masterOptions, page.Options, childPagesList);
                renderPageViewModel.Regions = allPageContents
                                              .Where(pc => pc.Page == page.MasterPage)
                                              .SelectMany(pc => pc.Content.ContentRegions.Distinct())
                                              .Select(cr => new PageRegionViewModel
                {
                    RegionId         = cr.Region.Id,
                    RegionIdentifier = cr.Region.RegionIdentifier
                })
                                              .ToList();
            }
            else
            {
                throw new InvalidOperationException(string.Format("Failed to load layout or master page for page {0}.", request.PageUrl));
            }

            var pageContents       = allPageContents.Where(pc => pc.Page.Id == page.Id).Where(pc => pc.Parent == null || allPageContents.All(apc => apc.Id != pc.Parent.Id));
            var contentProjections = pageContents.Distinct()
                                     .Select(f => contentProjectionService.CreatePageContentProjection(request.CanManageContent, f, allPageContents, null, request.PreviewPageContentId, renderPageViewModel.LanguageId))
                                     .Where(c => c != null).ToList();

            renderPageViewModel.Contents = contentProjections;
            renderPageViewModel.Metadata = pageAccessor.GetPageMetaData(page).ToList();

            if (page.AccessRules != null)
            {
                var list = page.AccessRules.Cast <IAccessRule>().ToList();
                list.RemoveDuplicates((a, b) => a.Id == b.Id ? 0 : -1);

                renderPageViewModel.AccessRules = list;
            }

            if (cmsConfiguration.Security.AccessControlEnabled)
            {
                SetIsReadOnly(renderPageViewModel, renderPageViewModel.AccessRules);
            }
            renderPageViewModel.HasEditRole = SecurityService.IsAuthorized(RootModuleConstants.UserRoles.EditContent);

            // Add <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> if current view is in an edit mode.
            if (request.CanManageContent)
            {
                if (renderPageViewModel.Metadata == null)
                {
                    renderPageViewModel.Metadata = new List <IPageActionProjection>();
                }

                renderPageViewModel.Metadata.Insert(0, new MetaDataProjection("X-UA-Compatible", "IE=edge,chrome=1"));
            }

            // Attach styles.
            var styles = new List <IStylesheetAccessor>();

            styles.Add(pageStylesheetProjectionFactory.Create(page, renderPageViewModel.Options));
            styles.AddRange(contentProjections);
            renderPageViewModel.Stylesheets = styles;

            // Attach JavaScript includes.
            var js = new List <IJavaScriptAccessor>();

            js.Add(pageJavaScriptProjectionFactory.Create(page, renderPageViewModel.Options));
            js.AddRange(contentProjections);
            renderPageViewModel.JavaScripts = js;

            // TODO: Fix main.js and processor.js IE cache.
            renderPageViewModel.MainJsPath    = string.Format(RootModuleConstants.AutoGeneratedJsFilePathPattern, "bcms.main.js");
            renderPageViewModel.RequireJsPath = VirtualPath.Combine(rootModuleDescriptor.JsBasePath,
                                                                    cmsConfiguration.UseMinifiedResources
                                                                        ? "bcms.require-2.1.5.min.js"
                                                                        : "bcms.require-2.1.5.js");
            renderPageViewModel.Html5ShivJsPath = VirtualPath.Combine(rootModuleDescriptor.JsBasePath, "html5shiv.js");

            return(renderPageViewModel);
        }
コード例 #38
0
        public ResponseModel DeleteStoreHierarchy(int designationID)
        {
            StoreHierarchyCaller storeHierarchyCaller = new StoreHierarchyCaller();
            ResponseModel        objResponseModel     = new ResponseModel();
            int    statusCode    = 0;
            string statusMessage = "";

            try
            {
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromToken(_radisCacheServerAddress, SecurityService.DecryptStringAES(token));
                int result = storeHierarchyCaller.DeleteStoreHierarchy(new StoreHierarchyService(_connectionSting), designationID, authenticate.UserMasterID, authenticate.TenantId);
                statusCode =
                    result == 0 ?
                    (int)EnumMaster.StatusCode.RecordInUse : (int)EnumMaster.StatusCode.Success;
                statusMessage                 = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);
                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = result;
            }
            catch (Exception)
            {
                throw;
            }
            return(objResponseModel);
        }
コード例 #39
0
 public override void Given()
 {
     Subject = new SecurityService();
 }
コード例 #40
0
ファイル: TokenServicesTest.cs プロジェクト: jpsjph/JP_EroPro
 public void GetToken_Should_Pass_When_Given_Valid_Data()
 {
     //AAA
     const int validKey = 1;
     const string exceptedData = "testtOKEN1";
     _authTokenConfig.SetupMockEntityRepositoryForGetAll(_authTokenList);
     var service = new SecurityService(_authTokenConfig.MockPersistence.Object, _authTokenConfig.MockLog.Object, _authTokenConfig.MockUtility.Object);
     var result = service.GetToken(validKey);
     Assert.IsNotNull(result);
     Assert.AreEqual(result.Token, exceptedData);
 }
コード例 #41
0
 public UserController(DAL.Context context, SecurityService security)
     : base(context)
 {
     this.security = security;
 }
コード例 #42
0
ファイル: TokenServicesTest.cs プロジェクト: jpsjph/JP_EroPro
        public void GenerateToken_Should_Pass_When_Given_Valid_Data()
        {
            //AAA
            var validModel = _tokenModel;
            //_clientLogin.SetupMockEntityRepositoryForGetAll(_clientLoginList);
            var mockRep = new Mock<IRepository<ClientLogin>>();
            mockRep.Setup(x => x.Get()).Returns(_clientLoginList.AsQueryable());
            var mockPersistance = new Mock<IPersistenceService>();
            mockPersistance.Setup(x => x.GetRepository<ClientLogin>()).Returns(mockRep.Object);

            _authTokenConfig.SetupMockEntityRepositoryForGetAll(_authTokenList);
            var service = new SecurityService(_authTokenConfig.MockPersistence.Object, _authTokenConfig.MockLog.Object, _authTokenConfig.MockUtility.Object);
            var result = service.GenerateToken(validModel);
            //_authTokenConfig.MockEntity.VerifyAll();
            _authTokenConfig.MockEntity.Verify(x => x.SaveChanges(true), Times.AtLeastOnce());

        }
コード例 #43
0
        private bool IsValid(string securityToken)
        {
            ISecurity auth = new SecurityService(this._dbContext);

            return(auth.ValidateToken(securityToken));
        }
コード例 #44
0
        public void RunCommand(string server, string vault, string username, string password, string lifecycledef, string state, Boolean force, string comment)
        {
            SecurityService secSrv = new SecurityService();
            secSrv.SecurityHeaderValue = new Autodesk.Connectivity.WebServices.SecuritySvc.SecurityHeader();
            secSrv.Url = "http://" + server + "/AutodeskDM/Services/SecurityService.asmx";

            try 
            {
                secSrv.SignIn(username, password, vault);

                Autodesk.Connectivity.WebServices.DocumentService docSrv = new Autodesk.Connectivity.WebServices.DocumentService();
                docSrv.SecurityHeaderValue = new Autodesk.Connectivity.WebServices.DocumentSvc.SecurityHeader();
                docSrv.SecurityHeaderValue.UserId = secSrv.SecurityHeaderValue.UserId;
                docSrv.SecurityHeaderValue.Ticket = secSrv.SecurityHeaderValue.Ticket;
                docSrv.Url = "http://" + server + "/AutodeskDM/Services/DocumentService.asmx";

                DocumentServiceExtensions docExSrv = new DocumentServiceExtensions();
                docExSrv.Url = "http://" + server + "/AutodeskDM/Services/DocumentServiceExtensions.asmx";
                docExSrv.SecurityHeaderValue = new Autodesk.Connectivity.WebServices.DocumentExSvc.SecurityHeader();
                docExSrv.SecurityHeaderValue.Ticket = secSrv.SecurityHeaderValue.Ticket;
                docExSrv.SecurityHeaderValue.UserId = secSrv.SecurityHeaderValue.UserId;

                LfCycDef[] lcDefs = docExSrv.GetAllLifeCycleDefinitions();
                long lcfound = -1;
                long lcstate = -1;
                if (lcDefs != null)
                {
                    Console.WriteLine("Defined LifeCycles");
                    Console.WriteLine("------------------");
                    foreach (LfCycDef lcDef in lcDefs)
                    {
                        Console.WriteLine("  LifeCycle: " + lcDef.DispName);
                        if (lcDef.DispName == lifecycledef)
                        {
                            lcfound = lcDef.Id;
                            foreach (LfCycState lcState in lcDef.StateArray)
                            {
                                Console.WriteLine("   LifeCycle State: " + lcState.DispName);
                                if (lcState.DispName == state)
                                {
                                    Console.WriteLine("   Overriding LifeCycle State: " + lcState.DispName);
                                    lcstate = lcState.Id;
                                }
                                if ((lcState.IsDflt) && (lcstate == -1))
                                {
                                    Console.WriteLine("   Using Default LifeCycle State: " + lcState.DispName);
                                    lcstate = lcState.Id;
                                }
                            }
                        }
                    }
                }
                if (lcfound != -1)
                {
                    Folder root = docSrv.GetFolderRoot();
                    //root = docSrv.GetFolderByPath("$/Designs/Designs/C690 T3");
                    //root = docSrv.GetFolderByPath("$/Code Numbers");
                    ProcessFilesInFolder(root, docSrv, docExSrv, lifecycledef, state, lcfound, lcstate, force, comment);
                }
                else
                {
                    Console.WriteLine("");
                    Console.WriteLine("ERROR: Requested LifeCycle not defined [" + lifecycledef + "]");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
                return;
            }
        }
コード例 #45
0
        public ResponseModel DeleteCRMRole(int CRMRoleID)
        {
            int           deleteCount      = 0;
            ResponseModel objResponseModel = new ResponseModel();
            int           statusCode       = 0;
            string        statusMessage    = "";

            try
            {
                ////Get token (Double encrypted) and get the tenant id
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromTokenCache(Cache, SecurityService.DecryptStringAES(token));

                SettingsCaller newCRM = new SettingsCaller();
                deleteCount = newCRM.DeleteCRMRole(new CRMRoleService(Cache, Db), authenticate.TenantId, CRMRoleID);

                statusCode =
                    deleteCount == 0 ? (int)EnumMaster.StatusCode.RecordInUse : (int)EnumMaster.StatusCode.RecordDeletedSuccess;

                statusMessage = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);

                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = deleteCount;
            }
            catch (Exception)
            {
                throw;
            }

            return(objResponseModel);
        }
コード例 #46
0
 public AuthenticationService()
 {
     _securityService = new SecurityService();
 }
コード例 #47
0
        public void RunCommand(string server, string vault, string username, string password, string rootfolder, Boolean hidden)
        {
            SecurityService secSrv = new SecurityService();
            secSrv.SecurityHeaderValue = new VaultDump.Security.SecurityHeader();
            secSrv.Url = "http://" + server + "/AutodeskDM/Services/SecurityService.asmx";

            try 
            {
                secSrv.SignIn(username, password, vault);
                DocumentService docSrv = new DocumentService();
                docSrv.SecurityHeaderValue = new VaultDump.Document.SecurityHeader();
                docSrv.SecurityHeaderValue.UserId = secSrv.SecurityHeaderValue.UserId;
                docSrv.SecurityHeaderValue.Ticket = secSrv.SecurityHeaderValue.Ticket;
                docSrv.Url = "http://" + server + "/AutodeskDM/Services/DocumentService.asmx";
                Folder root = docSrv.GetFolderRoot();
                //root = docSrv.GetFolderByPath("$/Designs/Designs/C690 T3");
                //root = docSrv.GetFolderByPath("$/Code Numbers");
                ProcessFilesInFolder(root, docSrv, rootfolder, hidden);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
                return;
            }
        }
コード例 #48
0
ファイル: LogService.cs プロジェクト: foster-hub/box-cms
        public void Log(string actionDescription, string errorDescription = null, bool saveParameters = true)
        {
            string url = "unknow";
            string login = "******";
            string ip = "unknow";
            DateTime when = DateTime.Now.ToUniversalTime();
            Dictionary<string, object> dicParameters = null;

            var httpContext = System.Web.HttpContext.Current;
            if (httpContext != null) {
                url = httpContext.Request.Url.OriginalString;
                ip = httpContext.Request.UserHostAddress;

                // if was not via IMPORT
                if (security == null)
                    security = new SecurityService();

                User user = security.GetSignedUser();

                if (user != null)
                    login = user.Email;

                if (user != null && user.LoginNT != null)
                    login = login + " (" + user.LoginNT + ")";

                if (saveParameters) {

                    dicParameters = new Dictionary<string, object>();

                    //Salvar dados que são enviados no corpo da requisição
                    if (httpContext.Request.InputStream.Length > 0) {
                        httpContext.Request.InputStream.Position = 0;
                        using (StreamReader reader = new StreamReader(httpContext.Request.InputStream)) {
                            if (httpContext.Request.ContentType.ToLower().Contains("application/json;"))
                                dicParameters["body"] = Newtonsoft.Json.JsonConvert.DeserializeObject(reader.ReadToEnd());
                            else
                                dicParameters["body"] = reader.ReadToEnd();
                        }
                    }
                    //Salvar dados que são enviados via GET
                    if (httpContext.Request.QueryString.HasKeys()) {
                        Dictionary<string, string> dicGet = new Dictionary<string, string>();
                        dicParameters["get"] = NameValueCollectionToDictionary(httpContext.Request.QueryString);
                    }
                    //Salvar dados que são enviados via POST
                    if (httpContext.Request.Form.HasKeys()) {
                        dicParameters["post"] = NameValueCollectionToDictionary(httpContext.Request.Form);
                    }
                }
            }

            string parameters = null;

            if (dicParameters != null && dicParameters.Count > 0)
                parameters = Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters);

            short logType = 0;
            if (!string.IsNullOrEmpty(errorDescription)) {
                logType = (short)LogTypes.ERROR;
            }

            Log log = new Log() { LogUId = Guid.NewGuid().ToString(), ActionDescription = actionDescription, ErrorDescription = errorDescription, LogType = logType, SignedUser = login, Url = url, UserIp = ip, When = when, Parameters = parameters };

            try {
                using (var context = new Data.CoreContext()) {
                    context.Logs.Add(log);
                    context.SaveChanges();

                    // delete old records
                    DateTime yearAgo = when.AddYears(-1);
                    context.Database.ExecuteSqlCommand("DELETE FROM Logs WHERE Logs.When < '" + yearAgo.Year + "-" + yearAgo.Month + "-" + yearAgo.Day + " 00:00:00'");
                }
            }
            catch (Exception) { }
        }
コード例 #49
0
        public ResponseModel ValidatePriorityNameExist(string priorityName)
        {
            string        resultMessage    = "";
            ResponseModel objResponseModel = new ResponseModel();
            int           statusCode       = 0;
            string        statusMessage    = "";

            try
            {
                ////Get token (Double encrypted) and get the tenant id
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromToken(radisCacheServerAddress, SecurityService.DecryptStringAES(token));

                StorePriorityCaller storePriorityCaller = new StorePriorityCaller();

                resultMessage = storePriorityCaller.VallidatePriority(new StorePriorityService(connectionString), priorityName, authenticate.TenantId);

                statusCode =
                    string.IsNullOrEmpty(resultMessage) ?
                    (int)EnumMaster.StatusCode.RecordNotFound : (int)EnumMaster.StatusCode.Success;

                statusMessage = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);

                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = resultMessage;
            }
            catch (Exception)
            {
                throw;
            }


            return(objResponseModel);
        }
コード例 #50
0
        public void MyTestInitialize()
        {
            securityService = new SecurityService();

            Mock<ISecurityRulesProvider> securityRuleProviderMock = new Mock<ISecurityRulesProvider>();

            rules = new List<SecurityRule>();

            securityRuleProviderMock.Setup(provider => provider.GetAll())
                .Returns(rules);

            securityService.securityRulesProvider = securityRuleProviderMock.Object;
        }
コード例 #51
0
        public ResponseModel GetPriorityList()
        {
            List <Priority> objPriority      = new List <Priority>();
            ResponseModel   objResponseModel = new ResponseModel();
            int             statusCode       = 0;
            string          statusMessage    = "";

            try
            {
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromToken(radisCacheServerAddress, SecurityService.DecryptStringAES(token));

                StorePriorityCaller storePriorityCaller = new StorePriorityCaller();

                objPriority = storePriorityCaller.GetPriorityList(new StorePriorityService(connectionString), authenticate.TenantId);

                statusCode =
                    objPriority.Count == 0 ?
                    (int)EnumMaster.StatusCode.RecordNotFound : (int)EnumMaster.StatusCode.Success;

                statusMessage = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);

                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = objPriority;
            }
            catch (Exception)
            {
                throw;
            }

            return(objResponseModel);
        }
コード例 #52
0
 public void GetSiteExceptionTest()
 {
     SecurityService securityService = new SecurityService();
     ServiceResponse<SiteDC> site = securityService.GetSite(1);
     Assert.AreNotEqual(site.Status, ResponseStatus.BusinessException);
 }
コード例 #53
0
        public ResponseModel AddPriority(string PriorityName, int status)
        {
            StorePriorityCaller storePriorityCaller = new StorePriorityCaller();
            ResponseModel       objResponseModel    = new ResponseModel();
            int    statusCode    = 0;
            string statusMessage = "";

            try
            {
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromToken(radisCacheServerAddress, SecurityService.DecryptStringAES(token));
                int result = storePriorityCaller.Addpriority(new StorePriorityService(connectionString), PriorityName, status, authenticate.TenantId, authenticate.UserMasterID);
                statusCode =
                    result == 0 ?
                    (int)EnumMaster.StatusCode.RecordAlreadyExists : (int)EnumMaster.StatusCode.Success;
                statusMessage                 = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);
                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = result;
            }
            catch (Exception)
            {
                throw;
            }
            return(objResponseModel);
        }
コード例 #54
0
ファイル: Engine.cs プロジェクト: stan4git/Lean-1
        /// <summary>
        /// Runs a single backtest/live job from the job queue
        /// </summary>
        /// <param name="job">The algorithm job to be processed</param>
        /// <param name="manager"></param>
        /// <param name="assemblyPath">The path to the algorithm's assembly</param>
        public void Run(AlgorithmNodePacket job, AlgorithmManager manager, string assemblyPath)
        {
            var algorithm        = default(IAlgorithm);
            var algorithmManager = manager;

            try
            {
                //Reset thread holders.
                var    initializeComplete = false;
                Thread threadTransactions = null;
                Thread threadResults      = null;
                Thread threadRealTime     = null;
                Thread threadAlphas       = null;

                //-> Initialize messaging system
                _systemHandlers.Notify.SetAuthentication(job);

                //-> Set the result handler type for this algorithm job, and launch the associated result thread.
                _algorithmHandlers.Results.Initialize(job, _systemHandlers.Notify, _systemHandlers.Api, _algorithmHandlers.Setup, _algorithmHandlers.Transactions);

                threadResults = new Thread(_algorithmHandlers.Results.Run, 0)
                {
                    IsBackground = true, Name = "Result Thread"
                };
                threadResults.Start();

                IBrokerage  brokerage    = null;
                DataManager dataManager  = null;
                var         synchronizer = new Synchronizer();
                try
                {
                    // Save algorithm to cache, load algorithm instance:
                    algorithm = _algorithmHandlers.Setup.CreateAlgorithmInstance(job, assemblyPath);

                    // Set algorithm in ILeanManager
                    _systemHandlers.LeanManager.SetAlgorithm(algorithm);

                    // initialize the alphas handler with the algorithm instance
                    _algorithmHandlers.Alphas.Initialize(job, algorithm, _systemHandlers.Notify, _systemHandlers.Api);

                    // Initialize the brokerage
                    IBrokerageFactory factory;
                    brokerage = _algorithmHandlers.Setup.CreateBrokerage(job, algorithm, out factory);

                    var marketHoursDatabase      = MarketHoursDatabase.FromDataFolder();
                    var symbolPropertiesDatabase = SymbolPropertiesDatabase.FromDataFolder();

                    var securityService = new SecurityService(algorithm.Portfolio.CashBook,
                                                              marketHoursDatabase,
                                                              symbolPropertiesDatabase,
                                                              (ISecurityInitializerProvider)algorithm);

                    algorithm.Securities.SetSecurityService(securityService);

                    dataManager = new DataManager(_algorithmHandlers.DataFeed,
                                                  new UniverseSelection(
                                                      algorithm,
                                                      securityService),
                                                  algorithm,
                                                  algorithm.TimeKeeper,
                                                  marketHoursDatabase);

                    _algorithmHandlers.Results.SetDataManager(dataManager);
                    algorithm.SubscriptionManager.SetDataManager(dataManager);

                    synchronizer.Initialize(
                        algorithm,
                        dataManager,
                        _liveMode);

                    // Initialize the data feed before we initialize so he can intercept added securities/universes via events
                    _algorithmHandlers.DataFeed.Initialize(
                        algorithm,
                        job,
                        _algorithmHandlers.Results,
                        _algorithmHandlers.MapFileProvider,
                        _algorithmHandlers.FactorFileProvider,
                        _algorithmHandlers.DataProvider,
                        dataManager,
                        (IDataFeedTimeProvider)synchronizer);

                    // set the order processor on the transaction manager (needs to be done before initializing BrokerageHistoryProvider)
                    algorithm.Transactions.SetOrderProcessor(_algorithmHandlers.Transactions);

                    // set the history provider before setting up the algorithm
                    var historyProvider = GetHistoryProvider(job.HistoryProvider);
                    if (historyProvider is BrokerageHistoryProvider)
                    {
                        (historyProvider as BrokerageHistoryProvider).SetBrokerage(brokerage);
                    }

                    var historyDataCacheProvider = new ZipDataCacheProvider(_algorithmHandlers.DataProvider);
                    historyProvider.Initialize(
                        new HistoryProviderInitializeParameters(
                            job,
                            _systemHandlers.Api,
                            _algorithmHandlers.DataProvider,
                            historyDataCacheProvider,
                            _algorithmHandlers.MapFileProvider,
                            _algorithmHandlers.FactorFileProvider,
                            progress =>
                    {
                        // send progress updates to the result handler only during initialization
                        if (!algorithm.GetLocked() || algorithm.IsWarmingUp)
                        {
                            _algorithmHandlers.Results.SendStatusUpdate(AlgorithmStatus.History,
                                                                        string.Format("Processing history {0}%...", progress));
                        }
                    }
                            )
                        );

                    historyProvider.InvalidConfigurationDetected += (sender, args) => { _algorithmHandlers.Results.ErrorMessage(args.Message); };
                    historyProvider.NumericalPrecisionLimited    += (sender, args) => { _algorithmHandlers.Results.DebugMessage(args.Message); };
                    historyProvider.DownloadFailed      += (sender, args) => { _algorithmHandlers.Results.ErrorMessage(args.Message, args.StackTrace); };
                    historyProvider.ReaderErrorDetected += (sender, args) => { _algorithmHandlers.Results.RuntimeError(args.Message, args.StackTrace); };

                    algorithm.HistoryProvider = historyProvider;

                    // initialize the default brokerage message handler
                    algorithm.BrokerageMessageHandler = factory.CreateBrokerageMessageHandler(algorithm, job, _systemHandlers.Api);

                    //Initialize the internal state of algorithm and job: executes the algorithm.Initialize() method.
                    initializeComplete = _algorithmHandlers.Setup.Setup(new SetupHandlerParameters(dataManager.UniverseSelection, algorithm, brokerage, job, _algorithmHandlers.Results, _algorithmHandlers.Transactions, _algorithmHandlers.RealTime));

                    // set this again now that we've actually added securities
                    _algorithmHandlers.Results.SetAlgorithm(algorithm);

                    // alpha handler needs start/end dates to determine sample step sizes
                    _algorithmHandlers.Alphas.OnAfterAlgorithmInitialized(algorithm);

                    //If there are any reasons it failed, pass these back to the IDE.
                    if (!initializeComplete || algorithm.ErrorMessages.Count > 0 || _algorithmHandlers.Setup.Errors.Count > 0)
                    {
                        initializeComplete = false;
                        //Get all the error messages: internal in algorithm and external in setup handler.
                        var errorMessage = String.Join(",", algorithm.ErrorMessages);
                        errorMessage += String.Join(",", _algorithmHandlers.Setup.Errors.Select(e =>
                        {
                            var message = e.Message;
                            if (e.InnerException != null)
                            {
                                var err  = _exceptionInterpreter.Interpret(e.InnerException, _exceptionInterpreter);
                                message += _exceptionInterpreter.GetExceptionMessageHeader(err);
                            }
                            return(message);
                        }));
                        Log.Error("Engine.Run(): " + errorMessage);
                        _algorithmHandlers.Results.RuntimeError(errorMessage);
                        _systemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, errorMessage);
                    }
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    var runtimeMessage = "Algorithm.Initialize() Error: " + err.Message + " Stack Trace: " + err;
                    _algorithmHandlers.Results.RuntimeError(runtimeMessage, err.ToString());
                    _systemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, AlgorithmStatus.RuntimeError, runtimeMessage);
                }


                // log the job endpoints
                Log.Trace("JOB HANDLERS: ");
                Log.Trace("         DataFeed:     " + _algorithmHandlers.DataFeed.GetType().FullName);
                Log.Trace("         Setup:        " + _algorithmHandlers.Setup.GetType().FullName);
                Log.Trace("         RealTime:     " + _algorithmHandlers.RealTime.GetType().FullName);
                Log.Trace("         Results:      " + _algorithmHandlers.Results.GetType().FullName);
                Log.Trace("         Transactions: " + _algorithmHandlers.Transactions.GetType().FullName);
                Log.Trace("         Alpha:        " + _algorithmHandlers.Alphas.GetType().FullName);
                if (algorithm?.HistoryProvider != null)
                {
                    Log.Trace("         History Provider:     " + algorithm.HistoryProvider.GetType().FullName);
                }
                if (job is LiveNodePacket)
                {
                    Log.Trace("         Brokerage:      " + brokerage?.GetType().FullName);
                }

                //-> Using the job + initialization: load the designated handlers:
                if (initializeComplete)
                {
                    // notify the LEAN manager that the algorithm is initialized and starting
                    _systemHandlers.LeanManager.OnAlgorithmStart();

                    //-> Reset the backtest stopwatch; we're now running the algorithm.
                    var startTime = DateTime.Now;

                    //Set algorithm as locked; set it to live mode if we're trading live, and set it to locked for no further updates.
                    algorithm.SetAlgorithmId(job.AlgorithmId);
                    algorithm.SetLocked();

                    //Load the associated handlers for transaction and realtime events:
                    _algorithmHandlers.Transactions.Initialize(algorithm, brokerage, _algorithmHandlers.Results);
                    _algorithmHandlers.RealTime.Setup(algorithm, job, _algorithmHandlers.Results, _systemHandlers.Api);

                    // wire up the brokerage message handler
                    brokerage.Message += (sender, message) =>
                    {
                        algorithm.BrokerageMessageHandler.Handle(message);

                        // fire brokerage message events
                        algorithm.OnBrokerageMessage(message);
                        switch (message.Type)
                        {
                        case BrokerageMessageType.Disconnect:
                            algorithm.OnBrokerageDisconnect();
                            break;

                        case BrokerageMessageType.Reconnect:
                            algorithm.OnBrokerageReconnect();
                            break;
                        }
                    };

                    //Send status to user the algorithm is now executing.
                    _algorithmHandlers.Results.SendStatusUpdate(AlgorithmStatus.Running);

                    //Launch the data, transaction and realtime handlers into dedicated threads
                    threadTransactions = new Thread(_algorithmHandlers.Transactions.Run)
                    {
                        IsBackground = true, Name = "Transaction Thread"
                    };
                    threadRealTime = new Thread(_algorithmHandlers.RealTime.Run)
                    {
                        IsBackground = true, Name = "RealTime Thread"
                    };
                    threadAlphas = new Thread(() => _algorithmHandlers.Alphas.Run())
                    {
                        IsBackground = true, Name = "Alpha Thread"
                    };

                    //Launch the data feed, result sending, and transaction models/handlers in separate threads.
                    threadTransactions.Start(); // Transaction modeller scanning new order requests
                    threadRealTime.Start();     // RealTime scan time for time based events:
                    threadAlphas.Start();       // Alpha thread for processing algorithm alpha insights

                    // Result manager scanning message queue: (started earlier)
                    _algorithmHandlers.Results.DebugMessage(string.Format("Launching analysis for {0} with LEAN Engine v{1}", job.AlgorithmId, Globals.Version));

                    try
                    {
                        //Create a new engine isolator class
                        var isolator = new Isolator();

                        // Execute the Algorithm Code:
                        var complete = isolator.ExecuteWithTimeLimit(_algorithmHandlers.Setup.MaximumRuntime, algorithmManager.TimeLoopWithinLimits, () =>
                        {
                            try
                            {
                                //Run Algorithm Job:
                                // -> Using this Data Feed,
                                // -> Send Orders to this TransactionHandler,
                                // -> Send Results to ResultHandler.
                                algorithmManager.Run(job, algorithm, synchronizer, _algorithmHandlers.Transactions, _algorithmHandlers.Results, _algorithmHandlers.RealTime, _systemHandlers.LeanManager, _algorithmHandlers.Alphas, isolator.CancellationToken);
                            }
                            catch (Exception err)
                            {
                                //Debugging at this level is difficult, stack trace needed.
                                Log.Error(err);
                                algorithm.RunTimeError = err;
                                algorithmManager.SetStatus(AlgorithmStatus.RuntimeError);
                                return;
                            }

                            Log.Trace("Engine.Run(): Exiting Algorithm Manager");
                        }, job.Controls.RamAllocation);

                        if (!complete)
                        {
                            Log.Error("Engine.Main(): Failed to complete in time: " + _algorithmHandlers.Setup.MaximumRuntime.ToString("F"));
                            throw new Exception("Failed to complete algorithm within " + _algorithmHandlers.Setup.MaximumRuntime.ToString("F")
                                                + " seconds. Please make it run faster.");
                        }

                        // Algorithm runtime error:
                        if (algorithm.RunTimeError != null)
                        {
                            HandleAlgorithmError(job, algorithm.RunTimeError);
                        }
                    }
                    catch (Exception err)
                    {
                        //Error running the user algorithm: purge datafeed, send error messages, set algorithm status to failed.
                        HandleAlgorithmError(job, err);
                    }

                    // notify the LEAN manager that the algorithm has finished
                    _systemHandlers.LeanManager.OnAlgorithmEnd();

                    try
                    {
                        var trades            = algorithm.TradeBuilder.ClosedTrades;
                        var charts            = new Dictionary <string, Chart>(_algorithmHandlers.Results.Charts);
                        var orders            = new Dictionary <int, Order>(_algorithmHandlers.Transactions.Orders);
                        var holdings          = new Dictionary <string, Holding>();
                        var banner            = new Dictionary <string, string>();
                        var statisticsResults = new StatisticsResults();

                        var csvTransactionsFileName = Config.Get("transaction-log");
                        if (!string.IsNullOrEmpty(csvTransactionsFileName))
                        {
                            SaveListOfTrades(_algorithmHandlers.Transactions, csvTransactionsFileName);
                        }

                        try
                        {
                            //Generates error when things don't exist (no charting logged, runtime errors in main algo execution)
                            const string strategyEquityKey   = "Strategy Equity";
                            const string equityKey           = "Equity";
                            const string dailyPerformanceKey = "Daily Performance";
                            const string benchmarkKey        = "Benchmark";

                            // make sure we've taken samples for these series before just blindly requesting them
                            if (charts.ContainsKey(strategyEquityKey) &&
                                charts[strategyEquityKey].Series.ContainsKey(equityKey) &&
                                charts[strategyEquityKey].Series.ContainsKey(dailyPerformanceKey) &&
                                charts.ContainsKey(benchmarkKey) &&
                                charts[benchmarkKey].Series.ContainsKey(benchmarkKey)
                                )
                            {
                                var equity            = charts[strategyEquityKey].Series[equityKey].Values;
                                var performance       = charts[strategyEquityKey].Series[dailyPerformanceKey].Values;
                                var profitLoss        = new SortedDictionary <DateTime, decimal>(algorithm.Transactions.TransactionRecord);
                                var totalTransactions = algorithm.Transactions.GetOrders(x => x.Status.IsFill()).Count();
                                var benchmark         = charts[benchmarkKey].Series[benchmarkKey].Values;

                                statisticsResults = StatisticsBuilder.Generate(trades, profitLoss, equity, performance, benchmark,
                                                                               _algorithmHandlers.Setup.StartingPortfolioValue, algorithm.Portfolio.TotalFees, totalTransactions);

                                //Some users have $0 in their brokerage account / starting cash of $0. Prevent divide by zero errors
                                var netReturn = _algorithmHandlers.Setup.StartingPortfolioValue > 0 ?
                                                (algorithm.Portfolio.TotalPortfolioValue - _algorithmHandlers.Setup.StartingPortfolioValue) / _algorithmHandlers.Setup.StartingPortfolioValue
                                                : 0;

                                //Add other fixed parameters.
                                banner.Add("Unrealized", "$" + algorithm.Portfolio.TotalUnrealizedProfit.ToString("N2"));
                                banner.Add("Fees", "-$" + algorithm.Portfolio.TotalFees.ToString("N2"));
                                banner.Add("Net Profit", "$" + algorithm.Portfolio.TotalProfit.ToString("N2"));
                                banner.Add("Return", netReturn.ToString("P"));
                                banner.Add("Equity", "$" + algorithm.Portfolio.TotalPortfolioValue.ToString("N2"));
                            }
                        }
                        catch (Exception err)
                        {
                            Log.Error(err, "Error generating statistics packet");
                        }

                        //Diagnostics Completed, Send Result Packet:
                        var totalSeconds = (DateTime.Now - startTime).TotalSeconds;
                        var dataPoints   = algorithmManager.DataPoints + algorithm.HistoryProvider.DataPointCount;

                        if (!_liveMode)
                        {
                            var kps = dataPoints / (double)1000 / totalSeconds;
                            _algorithmHandlers.Results.DebugMessage($"Algorithm Id:({job.AlgorithmId}) completed in {totalSeconds:F2} seconds at {kps:F0}k data points per second. Processing total of {dataPoints:N0} data points.");
                        }

                        _algorithmHandlers.Results.SendFinalResult(job, orders, algorithm.Transactions.TransactionRecord, holdings, algorithm.Portfolio.CashBook, statisticsResults, banner);
                    }
                    catch (Exception err)
                    {
                        Log.Error(err, "Error sending analysis results");
                    }

                    //Before we return, send terminate commands to close up the threads
                    _algorithmHandlers.Transactions.Exit();
                    _algorithmHandlers.DataFeed.Exit();
                    _algorithmHandlers.RealTime.Exit();
                    _algorithmHandlers.Alphas.Exit();
                    dataManager?.RemoveAllSubscriptions();
                }

                //Close result handler:
                _algorithmHandlers.Results.Exit();

                //Wait for the threads to complete:
                var ts = Stopwatch.StartNew();
                while ((_algorithmHandlers.Results.IsActive ||
                        (_algorithmHandlers.Transactions != null && _algorithmHandlers.Transactions.IsActive) ||
                        (_algorithmHandlers.DataFeed != null && _algorithmHandlers.DataFeed.IsActive) ||
                        (_algorithmHandlers.RealTime != null && _algorithmHandlers.RealTime.IsActive) ||
                        (_algorithmHandlers.Alphas != null && _algorithmHandlers.Alphas.IsActive)) &&
                       ts.ElapsedMilliseconds < 30 * 1000)
                {
                    Thread.Sleep(100);
                    Log.Trace("Waiting for threads to exit...");
                }

                //Terminate threads still in active state.
                if (threadTransactions != null && threadTransactions.IsAlive)
                {
                    threadTransactions.Abort();
                }
                if (threadResults != null && threadResults.IsAlive)
                {
                    threadResults.Abort();
                }
                if (threadAlphas != null && threadAlphas.IsAlive)
                {
                    threadAlphas.Abort();
                }

                if (brokerage != null)
                {
                    Log.Trace("Engine.Run(): Disconnecting from brokerage...");
                    brokerage.Disconnect();
                    brokerage.Dispose();
                }
                if (_algorithmHandlers.Setup != null)
                {
                    Log.Trace("Engine.Run(): Disposing of setup handler...");
                    _algorithmHandlers.Setup.Dispose();
                }
                Log.Trace("Engine.Main(): Analysis Completed and Results Posted.");
            }
            catch (Exception err)
            {
                Log.Error(err, "Error running algorithm");
            }
            finally
            {
                //No matter what for live mode; make sure we've set algorithm status in the API for "not running" conditions:
                if (_liveMode && algorithmManager.State != AlgorithmStatus.Running && algorithmManager.State != AlgorithmStatus.RuntimeError)
                {
                    _systemHandlers.Api.SetAlgorithmStatus(job.AlgorithmId, algorithmManager.State);
                }

                _algorithmHandlers.Results.Exit();
                _algorithmHandlers.DataFeed.Exit();
                _algorithmHandlers.Transactions.Exit();
                _algorithmHandlers.RealTime.Exit();
            }
        }
コード例 #55
0
        public ResponseModel GetRolesByUserID()
        {
            ResponseModel objResponseModel        = new ResponseModel();
            CRMRoleModel  objCRMRoleResponseModel = new CRMRoleModel();
            int           statusCode    = 0;
            string        statusMessage = "";

            try
            {
                ////Get token (Double encrypted) and get the tenant id
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromTokenCache(Cache, SecurityService.DecryptStringAES(token));

                SettingsCaller newCRM = new SettingsCaller();
                objCRMRoleResponseModel = newCRM.GetCRMRoleByUserID(new CRMRoleService(Cache, Db), authenticate.TenantId, authenticate.UserMasterID);

                statusCode = objCRMRoleResponseModel == null ? (int)EnumMaster.StatusCode.RecordNotFound : (int)EnumMaster.StatusCode.Success;

                statusMessage = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);

                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = objCRMRoleResponseModel;
            }
            catch (Exception)
            {
                throw;
            }

            return(objResponseModel);
        }
コード例 #56
0
        public ResponseModel UpdatePriorityOrder(int selectedPriorityID, int currentPriorityID)
        {
            ResponseModel objResponseModel = new ResponseModel();
            int           statusCode       = 0;
            string        statusMessage    = "";

            try
            {
                string       token        = Convert.ToString(Request.Headers["X-Authorized-Token"]);
                Authenticate authenticate = new Authenticate();
                authenticate = SecurityService.GetAuthenticateDataFromToken(radisCacheServerAddress, SecurityService.DecryptStringAES(token));

                StorePriorityCaller storePriorityCaller = new StorePriorityCaller();
                bool iStatus = storePriorityCaller.UpdatePriorityOrder(new StorePriorityService(connectionString), authenticate.TenantId, selectedPriorityID, currentPriorityID);
                statusCode =
                    iStatus ?
                    (int)EnumMaster.StatusCode.Success : (int)EnumMaster.StatusCode.InternalServerError;

                statusMessage = CommonFunction.GetEnumDescription((EnumMaster.StatusCode)statusCode);

                objResponseModel.Status       = true;
                objResponseModel.StatusCode   = statusCode;
                objResponseModel.Message      = statusMessage;
                objResponseModel.ResponseData = iStatus;
            }
            catch (Exception)
            {
                throw;
            }

            return(objResponseModel);
        }
コード例 #57
0
        public void RunCommand(string server, string vault, string username, string password, string statename, string statehistname, string state, string checkstates, string newstate, string revertstate, string lifecycledefinition)
        {
            long stateid = 0;
            long statehistid = 0;
            SecurityService secSrv = new SecurityService();
            secSrv.SecurityHeaderValue = new Autodesk.Connectivity.WebServices.SecuritySvc.SecurityHeader();
            secSrv.Url = "http://" + server + "/AutodeskDM/Services/SecurityService.asmx";

            try 
            {
                secSrv.SignIn(username, password, vault);
                DocumentService docSrv = new DocumentService();
                docSrv.SecurityHeaderValue = new Autodesk.Connectivity.WebServices.DocumentSvc.SecurityHeader();
                docSrv.SecurityHeaderValue.UserId = secSrv.SecurityHeaderValue.UserId;
                docSrv.SecurityHeaderValue.Ticket = secSrv.SecurityHeaderValue.Ticket;
                docSrv.Url = "http://" + server + "/AutodeskDM/Services/DocumentService.asmx";
                DocumentServiceExtensions docextSrv = new DocumentServiceExtensions();
                docextSrv.SecurityHeaderValue = new Autodesk.Connectivity.WebServices.DocumentExSvc.SecurityHeader();
                docextSrv.SecurityHeaderValue.UserId = secSrv.SecurityHeaderValue.UserId;
                docextSrv.SecurityHeaderValue.Ticket = secSrv.SecurityHeaderValue.Ticket;
                docextSrv.Url  = "http://" + server + "/AutodeskDM/Services/DocumentServiceExtensions.asmx";
                Folder root = docSrv.GetFolderRoot();
                Autodesk.Connectivity.WebServices.PropDef[] defs = docSrv.GetAllPropertyDefinitions();
                foreach (Autodesk.Connectivity.WebServices.PropDef pd in defs)
                {
                    if (pd.DispName.ToString().ToLower() == statename.ToLower())
                    {
                        stateid = pd.Id;
                    }
                    if (pd.DispName.ToString().ToLower() == statehistname.ToLower())
                    {
                        statehistid = pd.Id;
                    }
                }
                long revertstateid = -1;
                long newstateid = -1;
                long newlcdid = -1;
                LfCycDef[] lifecycledefs = docextSrv.GetAllLifeCycleDefinitions();
                foreach (LfCycDef lcd in lifecycledefs)
                {
                    if (lcd.DispName.ToString().ToLower() == lifecycledefinition.ToLower())
                    {
                        newlcdid = lcd.Id;
                    }
                }
                long[] transitionids = docextSrv.GetAllowedFileLifeCycleStateTransitionIds();
                LfCycTrans[] transitions = docextSrv.GetLifeCycleStateTransitionsByIds(transitionids);
                List<long> tostateidlist = new List<long>();
                foreach (LfCycTrans thistransition in transitions)
                {
                    if (!tostateidlist.Contains(thistransition.ToId))
                    {
                        tostateidlist.Add(thistransition.ToId);
                    }
                }
                long[] tostateids = tostateidlist.ToArray();
                LfCycState[] lifecyclestates = docextSrv.GetLifeCycleStatesByIds(tostateids);
                foreach (LfCycState lcs in lifecyclestates)
                {
                    if ((lcs.DispName.ToString().ToLower() == newstate.ToLower()) && (newlcdid == lcs.LfCycDefId))
                    {
                        newstateid = lcs.Id;
                    }
                    if ((lcs.DispName.ToString().ToLower() == revertstate.ToLower()) && (newlcdid == lcs.LfCycDefId))
                    {
                        revertstateid = lcs.Id;
                    }
                }
                if ((statehistid == 0) && (stateid == 0) && (newstateid == -1))
                {
                    if (statehistid == 0)
                        Console.WriteLine("Error: \"State (Historical)\" property undefined");
                    if (stateid == 0)
                        Console.WriteLine("Error: \"State\" property undefined");
                    if (newstateid == -1)
                        Console.WriteLine("Error: State \"" + newstate + "\" not defined for lifecycle \"" + lifecycledefinition + "\"");
                }
                else
                {
                    ProcessFilesInFolder(root, docSrv, docextSrv, statename, state, stateid, statehistid, checkstates, newstateid, newlcdid, newstate, revertstateid, revertstate, lifecycledefinition);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
                return;
            }
        }