Example #1
0
 public Linker(ConnectionStringSettings connectionString)
 {
     if (!DbRegistry.IsDatabaseRegistered(DbId))
     {
         DbRegistry.RegisterDatabase(DbId, connectionString);
     }
 }
Example #2
0
 static ResourceData()
 {
     if (!DbRegistry.IsDatabaseRegistered("tmresource"))
     {
         DbRegistry.RegisterDatabase("tmresource", ConfigurationManager.ConnectionStrings["tmresource"]);
     }
 }
Example #3
0
        public ServerEngine(int serverId, string connectionString)
        {
            var serverDbConnection = string.Format("postfixserver{0}", serverId);

            var connectionStringParser = new PostfixConnectionStringParser(connectionString);

            var cs = new ConnectionStringSettings(serverDbConnection,
                                                  connectionStringParser.PostfixAdminDbConnectionString, "MySql.Data.MySqlClient");

            if (!DbRegistry.IsDatabaseRegistered(cs.Name))
            {
                DbRegistry.RegisterDatabase(cs.Name, cs);
            }

            _csName = cs.Name;

            var json = JObject.Parse(connectionString);

            if (json["Api"] != null)
            {
                _serverApi = new ServerApi
                {
                    server_ip = json["Api"]["Server"].ToString(),
                    port      = Convert.ToInt32(json["Api"]["Port"].ToString()),
                    protocol  = json["Api"]["Protocol"].ToString(),
                    version   = json["Api"]["Version"].ToString(),
                    token     = json["Api"]["Token"].ToString()
                };
            }
        }
Example #4
0
        private List <Tuple <string, string> > SelectTextsForIndex(DateTime date, bool withContent)
        {
            if (!DbRegistry.IsDatabaseRegistered(module.Name))
            {
                DbRegistry.RegisterDatabase(module.Name, module.ConnectionString);
            }

            using (var db = new DbManager(module.Name))
            {
                return(db.Connection
                       .CreateCommand(withContent ? module.Select : ModifySelect(module.Select))
                       .AddParameter("tenant", tenant.TenantId)
                       .AddParameter("lastModified", date)
                       .ExecuteList()
                       .ConvertAll(r =>
                {
                    var text = default(string);
                    if (withContent)
                    {
                        text = (string)r[1];
                        var html = 2 < r.Length && r[2] != null ? Convert.ToBoolean(r[2]) : false;
                        if (html && !string.IsNullOrEmpty(text))
                        {
                            text = HtmlUtil.GetText(text);
                        }
                    }
                    return Tuple.Create(r[0].ToString(), text);
                }));
            }
        }
Example #5
0
        public override List <UsageSpaceStatItem> GetStatData()
        {
            if (!DbRegistry.IsDatabaseRegistered(FileConstant.DatabaseId))
            {
                DbRegistry.RegisterDatabase(FileConstant.DatabaseId, ConfigurationManager.ConnectionStrings[FileConstant.DatabaseId]);
            }

            using (var filedb = new DbManager(FileConstant.DatabaseId))
            {
                var q = new SqlQuery("files_file f")
                        .Select("b.right_node")
                        .SelectSum("f.content_length")
                        .InnerJoin("files_folder_tree t", Exp.EqColumns("f.folder_id", "t.folder_id"))
                        .InnerJoin("files_bunch_objects b", Exp.EqColumns("t.parent_id", "b.left_node"))
                        .Where("b.tenant_id", TenantProvider.CurrentTenantID)
                        .Where(Exp.Like("b.right_node", "crm/crm_common/", SqlLike.StartWith))
                        .GroupBy(1);

                return(filedb.ExecuteList(q)
                       .Select(r => new UsageSpaceStatItem
                {
                    Name = Resources.CRMCommonResource.ProductName,
                    SpaceUsage = Convert.ToInt64(r[1]),
                    Url = VirtualPathUtility.ToAbsolute(PathProvider.StartURL())
                })
                       .ToList());
            }
        }
Example #6
0
        public override List <UsageSpaceStatItem> GetStatData()
        {
            if (!DbRegistry.IsDatabaseRegistered(MailDatabaseId))
            {
                DbRegistry.RegisterDatabase(MailDatabaseId, ConfigurationManager.ConnectionStrings[MailDatabaseId]);
            }

            using (var mail_db = new DbManager(MailDatabaseId))
            {
                var query = new SqlQuery("mail_attachment a")
                            .InnerJoin("mail_mail m", Exp.EqColumns("a.id_mail", "m.id"))
                            .Select("m.id_user")
                            .Select("sum(a.size) as size")
                            .Where("m.tenant", TenantProvider.CurrentTenantID)
                            .Where("a.need_remove", 0)
                            .GroupBy(1)
                            .OrderBy(2, false);

                return(mail_db.ExecuteList(query)
                       .Select(r =>
                {
                    var user_id = new Guid(Convert.ToString(r[0]));
                    var user = CoreContext.UserManager.GetUsers(user_id);
                    var item = new UsageSpaceStatItem
                    {
                        Name = DisplayUserSettings.GetFullUserName(user, false),
                        ImgUrl = UserPhotoManager.GetSmallPhotoURL(user.ID),
                        Url = CommonLinkUtility.GetUserProfile(user.ID),
                        SpaceUsage = Convert.ToInt64(r[1])
                    };
                    return item;
                })
                       .ToList());
            }
        }
Example #7
0
        public override List <SpaceUsageStatManager.UsageSpaceStatItem> GetStatData()
        {
            var data = new List <SpaceUsageStatManager.UsageSpaceStatItem>();

            if (!DbRegistry.IsDatabaseRegistered(FILES_DBID))
            {
                DbRegistry.RegisterDatabase(FILES_DBID, ConfigurationManager.ConnectionStrings[FILES_DBID]);
            }
            using (var filedb = new DbManager(FILES_DBID))
            {
                var q = new SqlQuery("files_file f")
                        .Select("b.right_node")
                        .SelectSum("f.content_length")
                        .InnerJoin("files_folder_tree t", Exp.EqColumns("f.folder_id", "t.folder_id"))
                        .InnerJoin("files_bunch_objects b", Exp.EqColumns("t.parent_id", "b.left_node"))
                        .Where("b.tenant_id", CoreContext.TenantManager.GetCurrentTenant().TenantId)
                        .Where(Exp.Like("b.right_node", "crm/crm_common/", SqlLike.StartWith))
                        .GroupBy(1);

                var size = filedb.ExecuteList(q).Select(r => Convert.ToInt64(r[1])).FirstOrDefault();


                data.Add(new UsageSpaceStatItem()
                {
                    Name       = Resources.CRMCommonResource.ProductName,
                    SpaceUsage = size,
                    Url        = VirtualPathUtility.ToAbsolute(PathProvider.StartURL())
                });
            }

            return(data);
        }
Example #8
0
 public TenantsProvider(ConnectionStringSettings connectionString)
 {
     dbid = connectionString.Name;
     if (!DbRegistry.IsDatabaseRegistered(dbid))
     {
         DbRegistry.RegisterDatabase(dbid, connectionString);
     }
     useUserActivity = connectionString.ProviderName == "MySql.Data.MySqlClient";
 }
Example #9
0
        public override List <UsageSpaceStatItem> GetStatData()
        {
            if (!DbRegistry.IsDatabaseRegistered(PROJECTS_DBID))
            {
                DbRegistry.RegisterDatabase(PROJECTS_DBID, ConfigurationManager.ConnectionStrings[PROJECTS_DBID]);
            }
            if (!DbRegistry.IsDatabaseRegistered(FileConstant.DatabaseId))
            {
                DbRegistry.RegisterDatabase(FileConstant.DatabaseId, ConfigurationManager.ConnectionStrings[FileConstant.DatabaseId]);
            }
            using (var db = new DbManager(FileConstant.DatabaseId))
            {
                var q = new SqlQuery("files_file f")
                        .Select("f.create_by")
                        .SelectSum("f.content_length")
                        .InnerJoin("files_folder_tree t", Exp.EqColumns("f.folder_id", "t.folder_id"))
                        .InnerJoin("files_bunch_objects b", Exp.EqColumns("t.parent_id", "b.left_node"))
                        .Where("b.tenant_id", CoreContext.TenantManager.GetCurrentTenant().TenantId)
                        .Where(Exp.Like("b.right_node", "files/my/", SqlLike.StartWith))
                        .GroupBy(1);

                var result = db.ExecuteList(q)
                             .Select(
                    r =>
                    new
                {
                    User = CoreContext.UserManager.GetUsers(new Guid((string)r[0])),
                    Size = Convert.ToInt64(r[1])
                })
                             .GroupBy(r => r.User).ToDictionary(g => g.Key, g => g.Sum(a => a.Size));

                q = new SqlQuery("files_file f")
                    .SelectSum("f.content_length")
                    .InnerJoin("files_folder_tree t", Exp.EqColumns("f.folder_id", "t.folder_id"))
                    .InnerJoin("files_bunch_objects b", Exp.EqColumns("t.parent_id", "b.left_node"))
                    .Where("b.tenant_id", CoreContext.TenantManager.GetCurrentTenant().TenantId)
                    .Where("b.right_node", "files/common/");

                var common = db.ExecuteScalar <long>(q);
                if (result.ContainsKey(Constants.LostUser))
                {
                    result[Constants.LostUser] += common;
                }
                else
                {
                    result.Add(Constants.LostUser, common);
                }
                return(result.Select(i => new UsageSpaceStatItem
                {
                    Name = i.Key.Equals(Constants.LostUser) ? FilesUCResource.CorporateFiles : i.Key.DisplayUserName(false),
                    ImgUrl = i.Key.Equals(Constants.LostUser) ? PathProvider.GetImagePath("corporatefiles_big.png") : i.Key.GetSmallPhotoURL(),
                    Url = i.Key.Equals(Constants.LostUser) ? PathProvider.GetFolderUrl(Global.FolderCommon, false, null) : i.Key.GetUserProfilePageURL(),
                    SpaceUsage = i.Value
                })
                       .OrderByDescending(t => t.SpaceUsage).ToList());
            }
        }
Example #10
0
        private void Initialize()
        {
            if (!initialized)
            {
                lock (locker)
                {
                    if (!initialized)
                    {
                        initialized = true;

                        var find = false;
                        foreach (ConnectionStringSettings cs in ConfigurationManager.ConnectionStrings)
                        {
                            if (cs.Name.StartsWith(dbid + "."))
                            {
                                var name = cs.Name.Substring(dbid.Length + 1);
                                regions[name] = new HostedSolution(cs, name);
                                find          = true;
                            }
                        }
                        if (find)
                        {
                            regions[dbid] = new HostedSolution(ConfigurationManager.ConnectionStrings[dbid]);
                            if (!regions.ContainsKey(string.Empty))
                            {
                                regions[string.Empty] = new HostedSolution(ConfigurationManager.ConnectionStrings[dbid]);
                            }
                        }
                        else
                        {
                            try
                            {
                                using (var db = new DbManager(dbid))
                                {
                                    var q = new SqlQuery("regions")
                                            .Select("region")
                                            .Select("connection_string")
                                            .Select("provider");
                                    db.ExecuteList(q)
                                    .ForEach(r =>
                                    {
                                        var cs = new ConnectionStringSettings((string)r[0], (string)r[1], (string)r[2]);
                                        if (!DbRegistry.IsDatabaseRegistered(cs.Name))
                                        {
                                            DbRegistry.RegisterDatabase(cs.Name, cs);
                                        }
                                        regions[cs.Name] = new HostedSolution(cs, cs.Name);
                                    });
                                }
                            }
                            catch (DbException) { }
                        }
                    }
                }
            }
        }
Example #11
0
        public DbWorker()
        {
            var connectionString = NotifyServiceCfg.ConnectionString;

            dbid = connectionString.Name;
            if (!DbRegistry.IsDatabaseRegistered(dbid))
            {
                DbRegistry.RegisterDatabase(dbid, connectionString);
            }
        }
Example #12
0
        public StorageCleanerService()
        {
            CanStop = true;
            AutoLog = true;

            if (!DbRegistry.IsDatabaseRegistered(DbId))
            {
                DbRegistry.RegisterDatabase(DbId, StorageCleanerCfg.ConnectionString);
            }
        }
        private DbManager GetDbManager(string connectionStringName)
        {
            var cs = ConfigurationManager.ConnectionStrings[connectionStringName];

            if (!DbRegistry.IsDatabaseRegistered(connectionStringName))
            {
                DbRegistry.RegisterDatabase(connectionStringName, cs);
            }
            return(new DbManager(connectionStringName));
        }
Example #14
0
 static GetResource()
 {
     if (!DbRegistry.IsDatabaseRegistered("tmresource"))
     {
         DbRegistry.RegisterDatabase("tmresource", ConfigurationManager.ConnectionStrings["tmresource"]);
     }
     if (!DbRegistry.IsDatabaseRegistered("tmresourceTrans") && ConfigurationManager.ConnectionStrings["tmresourceTrans"] != null)
     {
         DbRegistry.RegisterDatabase("tmresourceTrans", ConfigurationManager.ConnectionStrings["tmresourceTrans"]);
     }
 }
Example #15
0
        protected TestBase()
        {
            if (!DbRegistry.IsDatabaseRegistered(DbId))
            {
                DbRegistry.RegisterDatabase(DbId, ConfigurationManager.ConnectionStrings[DbId]);
            }
            Db = new DbManager(DbId);

            XmlConfigurator.Configure();
            Log = LogManager.GetLogger("ASC.Projects.Tests");
        }
Example #16
0
        public override List <UsageSpaceStatItem> GetStatData()
        {
            if (!DbRegistry.IsDatabaseRegistered(FileConstant.DatabaseId))
            {
                DbRegistry.RegisterDatabase(FileConstant.DatabaseId, ConfigurationManager.ConnectionStrings[FileConstant.DatabaseId]);
            }

            using (var db = new DbManager(FileConstant.DatabaseId))
            {
                var myFiles = new SqlQuery("files_file f")
                              .Select("f.create_by")
                              .Select("sum(f.content_length) as size")
                              .InnerJoin("files_folder_tree t", Exp.EqColumns("f.folder_id", "t.folder_id"))
                              .InnerJoin("files_bunch_objects b", Exp.EqColumns("f.tenant_id", "b.tenant_id") & Exp.EqColumns("t.parent_id", "b.left_node"))
                              .Where("b.tenant_id", TenantProvider.CurrentTenantID)
                              .Where(Exp.Like("b.right_node", "files/my/", SqlLike.StartWith) | Exp.Like("b.right_node", "files/trash/", SqlLike.StartWith))
                              .GroupBy(1);

                var commonFiles = new SqlQuery("files_file f")
                                  .Select("'" + Constants.LostUser.ID + "'")
                                  .Select("sum(f.content_length) as size")
                                  .InnerJoin("files_folder_tree t", Exp.EqColumns("f.folder_id", "t.folder_id"))
                                  .InnerJoin("files_bunch_objects b", Exp.EqColumns("f.tenant_id", "b.tenant_id") & Exp.EqColumns("t.parent_id", "b.left_node"))
                                  .Where("b.tenant_id", TenantProvider.CurrentTenantID)
                                  .Where("b.right_node", "files/common/");

                var query = myFiles.UnionAll(commonFiles);

                return(db.ExecuteList(query)
                       .GroupBy(r => CoreContext.UserManager.GetUsers(new Guid(Convert.ToString(r[0]))),
                                r => Convert.ToInt64(r[1]),
                                (user, items) =>
                {
                    var item = new UsageSpaceStatItem {
                        SpaceUsage = items.Sum()
                    };
                    if (user.Equals(Constants.LostUser))
                    {
                        item.Name = FilesUCResource.CorporateFiles;
                        item.ImgUrl = PathProvider.GetImagePath("corporatefiles_big.png");
                        item.Url = PathProvider.GetFolderUrl(Global.FolderCommon);
                    }
                    else
                    {
                        item.Name = user.DisplayUserName(false);
                        item.ImgUrl = user.GetSmallPhotoURL();
                        item.Url = user.GetUserProfilePageURL();
                    }
                    return item;
                })
                       .OrderByDescending(i => i.SpaceUsage)
                       .ToList());
            }
        }
Example #17
0
 public DeviceDao(ConnectionStringSettings connectionString)
 {
     if (connectionString == null)
     {
         throw new ArgumentNullException("connectionString");
     }
     if (!DbRegistry.IsDatabaseRegistered(connectionString.Name))
     {
         DbRegistry.RegisterDatabase(connectionString.Name, connectionString);
     }
     _databaseID = connectionString.Name;
 }
        public override List <SpaceUsageStatManager.UsageSpaceStatItem> GetStatData()
        {
            var data = new List <SpaceUsageStatManager.UsageSpaceStatItem>();

            if (!DbRegistry.IsDatabaseRegistered(PROJECTS_DBID))
            {
                DbRegistry.RegisterDatabase(PROJECTS_DBID, ConfigurationManager.ConnectionStrings[PROJECTS_DBID]);
            }
            if (!DbRegistry.IsDatabaseRegistered(FILES_DBID))
            {
                DbRegistry.RegisterDatabase(FILES_DBID, ConfigurationManager.ConnectionStrings[FILES_DBID]);
            }

            using (var filedb = new DbManager(FILES_DBID))
                using (var projdb = new DbManager(PROJECTS_DBID))
                {
                    var q = new SqlQuery("files_file f")
                            .Select("b.right_node")
                            .SelectSum("f.content_length")
                            .InnerJoin("files_folder_tree t", Exp.EqColumns("f.folder_id", "t.folder_id"))
                            .InnerJoin("files_bunch_objects b", Exp.EqColumns("t.parent_id", "b.left_node"))
                            .Where("b.tenant_id", CoreContext.TenantManager.GetCurrentTenant().TenantId)
                            .Where(Exp.Like("b.right_node", "projects/project/", SqlLike.StartWith))
                            .GroupBy(1);

                    var sizes = filedb.ExecuteList(q)
                                .Select(r => new { ProjectId = Convert.ToInt32(((string)r[0]).Substring(17)), Size = Convert.ToInt64(r[1]) })
                                .GroupBy(r => r.ProjectId)
                                .ToDictionary(g => g.Key, g => g.Sum(a => a.Size));

                    q = new SqlQuery("projects_projects")
                        .Select("id", "title")
                        .Where("tenant_id", CoreContext.TenantManager.GetCurrentTenant().TenantId)
                        .Where(Exp.In("id", sizes.Keys));

                    var dbData = projdb.ExecuteList(q)
                                 .Select(r => Tuple.Create(Convert.ToInt32(r[0]), (string)r[1], sizes[Convert.ToInt32(r[0])]))
                                 .OrderByDescending(t => t.Item3)
                                 .ToList();

                    foreach (var row in dbData)
                    {
                        data.Add(new UsageSpaceStatItem()
                        {
                            Name       = row.Item2,
                            SpaceUsage = row.Item3,
                            Url        = String.Concat(PathProvider.BaseAbsolutePath, "projects.aspx?prjID=" + row.Item1.ToString())
                        });
                    }
                }

            return(data);
        }
Example #19
0
        protected string RegisterDatabase(int id, string connectionString)
        {
            connectionString = connectionString + ";convert zero datetime=True";
            var connectionSettings = new ConnectionStringSettings("mailservice-" + id, connectionString, "MySql.Data.MySqlClient");

            if (DbRegistry.IsDatabaseRegistered(connectionSettings.Name))
            {
                DbRegistry.UnRegisterDatabase(connectionSettings.Name);
            }

            DbRegistry.RegisterDatabase(connectionSettings.Name, connectionSettings);
            return(connectionSettings.Name);
        }
        private static DbManager GetDb(string dbid, string connectionString)
        {
            var connectionSettings = new ConnectionStringSettings(dbid, connectionString, "MySql.Data.MySqlClient");

            if (DbRegistry.IsDatabaseRegistered(connectionSettings.Name))
            {
                DbRegistry.UnRegisterDatabase(connectionSettings.Name);
            }

            DbRegistry.RegisterDatabase(connectionSettings.Name, connectionSettings);

            return(new DbManager(connectionSettings.Name));
        }
Example #21
0
        private DbManager GetDb(string dbid, string connectionString)
        {
            var connectionSettings = new System.Configuration.ConnectionStringSettings(dbid, connectionString, "MySql.Data.MySqlClient");

            if (DbRegistry.IsDatabaseRegistered(connectionSettings.Name))
            {
                DbRegistry.UnRegisterDatabase(connectionSettings.Name);
            }

            DbRegistry.RegisterDatabase(connectionSettings.Name, connectionSettings);

            return(DbOptions.Get(connectionSettings.Name));
        }
Example #22
0
        public DbExecuter(ConnectionStringSettings connectionString)
        {
            if (connectionString == null)
            {
                throw new ArgumentNullException("connectionString");
            }

            dbid = connectionString.Name;
            if (!DbRegistry.IsDatabaseRegistered(dbid))
            {
                DbRegistry.RegisterDatabase(dbid, connectionString);
            }
        }
        public DbManager GetAdminDb()
        {
            var serverDbConnection = String.Format("postfixserver{0}", _serverId);
            //Todo: Rewrite with naive implementation of DbRegistry. If we change value in db we can't update it without restarting.
            var cs = new ConnectionStringSettings(serverDbConnection,
                                                  _connectionStringParser.PostfixAdminDbConnectionString, "MySql.Data.MySqlClient");

            if (!DbRegistry.IsDatabaseRegistered(cs.Name))
            {
                DbRegistry.RegisterDatabase(cs.Name, cs);
            }

            return(new DbManager(cs.Name));
        }
 public CommentRepository(string dbId, ConnectionStringSettings connectionString)
 {
     _dbId = dbId;
     if (!DbRegistry.IsDatabaseRegistered(dbId))
     {
         lock (_registerLock)
         {
             Thread.MemoryBarrier();
             if (!DbRegistry.IsDatabaseRegistered(dbId))
             {
                 DbRegistry.RegisterDatabase(dbId, connectionString);
             }
         }
     }
 }
Example #25
0
        public DBResourceReader(string fileName, CultureInfo culture)
        {
            _fileName = fileName;
            _language = culture.Name;

            if (_language == "")
            {
                _language = "Neutral";
            }

            if (!DbRegistry.IsDatabaseRegistered("tmresource"))
            {
                DbRegistry.RegisterDatabase("tmresource", ConfigurationManager.ConnectionStrings["tmresource"]);
            }
        }
Example #26
0
        internal static List <BaseCalendar> GetUserCalendars(Guid userId)
        {
            if (!DbRegistry.IsDatabaseRegistered(CRMConstants.DatabaseId))
            {
                DbRegistry.RegisterDatabase(CRMConstants.DatabaseId, WebConfigurationManager.ConnectionStrings[CRMConstants.DatabaseId]);
            }

            var tenantId      = CoreContext.TenantManager.GetCurrentTenant().TenantId;
            var crmDaoFactory = new DaoFactory(tenantId, CRMConstants.DatabaseId);

            var cals = new List <BaseCalendar>();

            cals.Add(new CRMCalendar(crmDaoFactory, userId));
            return(cals);
        }
Example #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InMemoryTokenManager"/> class.
        /// </summary>
        /// <param name="consumerKey">The consumer key.</param>
        /// <param name="consumerSecret">The consumer secret.</param>
        public DbTokenManager(string consumerKey, string consumerSecret, string dbId, ConnectionStringSettings connectionString)
        {
            _dbId = dbId;
            if (String.IsNullOrEmpty(consumerKey))
            {
                throw new ArgumentNullException("consumerKey");
            }

            this.ConsumerKey    = consumerKey;
            this.ConsumerSecret = consumerSecret;

            if (!DbRegistry.IsDatabaseRegistered(dbId))
            {
                DbRegistry.RegisterDatabase(dbId, connectionString);
            }
        }
Example #28
0
        public void Configure()
        {
            if (!DbRegistry.IsDatabaseRegistered(FileConstant.DatabaseId))
            {
                DbRegistry.RegisterDatabase(FileConstant.DatabaseId, WebConfigurationManager.ConnectionStrings[FileConstant.DatabaseId]);
            }


            if (!FilesIntegration.IsRegisteredFileSecurityProvider("crm", "crm_common"))
            {
                FilesIntegration.RegisterFileSecurityProvider("crm", "crm_common", new FileSecurityProvider());
            }

            //Register prodjects' calendar events
            CalendarManager.Instance.RegistryCalendarProvider(CRMApi.GetUserCalendars);
        }
Example #29
0
        /// <summary>
        /// </summary>
        /// <param name="context"></param>
        /// <param name="fileStorageService"></param>
        public DocumentsApi(ApiContext context, IFileStorageService fileStorageService)
        {
            _context            = context;
            _fileStorageService = fileStorageService;
            //TODO: Why not to move this code to DAO???
            if (!DbRegistry.IsDatabaseRegistered(FileConstant.DatabaseId))
            {
                DbRegistry.RegisterDatabase(FileConstant.DatabaseId,
                                            WebConfigurationManager.ConnectionStrings[FileConstant.DatabaseId]);
            }

            if (!FilesIntegration.IsRegisteredFileSecurityProvider("crm", "crm_common"))
            {
                FilesIntegration.RegisterFileSecurityProvider("crm", "crm_common", new FileSecurityProvider());
            }
        }
        public List <int> GetCrmContactsId(int tenant_id, string user_id, string[] emails)
        {
            var ids = new List <int>();

            try
            {
                #region Set up connection to CRM sequrity
                CoreContext.TenantManager.SetCurrentTenant(tenant_id);
                SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(new Guid(user_id)));
                if (!DbRegistry.IsDatabaseRegistered("crm"))
                {
                    DbRegistry.RegisterDatabase("crm", ConfigurationManager.ConnectionStrings["crm"]);
                }
                #endregion

                using (var db = new DbManager("crm"))
                {
                    #region If CRM contact
                    var q = new SqlQuery("crm_contact c")
                            .Select("c.id", "c.is_company")
                            .InnerJoin("crm_contact_info i", Exp.EqColumns("c.tenant_id", "i.tenant_id") & Exp.EqColumns("c.id", "i.contact_id"))
                            .Where("c.tenant_id", tenant_id)
                            .Where("i.type", (int)ContactInfoType.Email)
                            .Where(Exp.In("i.data", emails));

                    var result = db.ExecuteList(q)
                                 .ConvertAll(r => new { Id = Convert.ToInt32(r[0]), Company = Convert.ToBoolean(r[1]) });

                    foreach (var r in result)
                    {
                        var contact = r.Company ? new Company() : (Contact) new Person();
                        contact.ID = r.Id;
                        if (CRMSecurity.CanAccessTo(contact))
                        {
                            ids.Add(r.Id);
                        }
                    }
                    #endregion
                }
            }
            catch (Exception e)
            {
                _log.Warn("GetCrmContactsId(tenandId='{0}', userId='{1}', emails='{2}') Exception:\r\n{3}\r\n",
                          tenant_id, user_id, string.Join(",", emails), e.ToString());
            }
            return(ids);
        }