Esempio n. 1
0
        public static bool UpdateVendor(TenantUserSession tenantUserSession, Vendor vendor, out Exception exception)
        {
            exception = null;
            bool result = false;

            try
            {
                ContextTenant context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString);
                Vendor        temp    = context.Vendors.Where(x => x.Id == vendor.Id).Select(x => x).FirstOrDefault();
                temp.VendorName    = vendor.VendorName;
                temp.Gst           = vendor.Gst;
                temp.Address       = vendor.Address;
                temp.Phone         = vendor.Phone;
                temp.Email         = vendor.Email;
                temp.ContactPerson = vendor.ContactPerson;
                context.Vendors.Add(temp);
                context.Entry(temp).State = System.Data.Entity.EntityState.Modified;
                context.SaveChanges();
                result = true;
            }
            catch (Exception ex)
            {
                exception = ex;
                result    = false;
            }
            return(result);
        }
Esempio n. 2
0
        public static bool AddDepartment(TenantUserSession tenantUserSession, string departmentName, out Department department, out Exception exception)
        {
            exception  = null;
            department = null;
            bool result = false;

            try
            {
                using (var context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString)) {
                    using (var contextTrans = context.Database.BeginTransaction())
                    {
                        var departmentExist = context.Departments.Where(x => x.Name == departmentName).SingleOrDefault();
                        if (departmentExist != null)
                        {
                            throw (new Exception("Department already exists"));
                        }
                        Department _department = new Department();
                        _department.Name = departmentName;
                        department       = context.Departments.Add(_department);
                        context.SaveChanges();
                        result = true;
                        contextTrans.Commit();
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 3
0
        private static ScanSession CreateScanSessionEntryPrivate(TenantUserSession tenantUserSession, string name, string description, ContextTenant context)
        {
            if (context == null)
            {
                throw (new ArgumentNullException("context"));
            }
            if (string.IsNullOrEmpty(name.Trim()))
            {
                throw (new Exception("Name is required"));
            }
            if (context.ScanSessions.Any(x => x.Name.ToLower().Trim() == name.ToLower().Trim()))
            {
                throw new Exception("Scan Session with same name already exists. Please select a unique name.");
            }

            ScanSession scanSession = new ScanSession();

            scanSession.DateTimeCreated = DateTime.UtcNow;
            scanSession.Description     = description;
            scanSession.Guid            = Guid.NewGuid();
            scanSession.Name            = name;
            scanSession.UserId          = tenantUserSession.User.Id;
            var scan = context.ScanSessions.Add(scanSession);

            context.SaveChanges();
            return(scan);
        }
Esempio n. 4
0
        public static int UpdateTenant(TenantUserSession tenantUserSession, Tenant tenant)
        {
            using (var context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString))
            {
                var tempTenant = new Tenant();

                tempTenant = context.Tenants.FirstOrDefault(t => t.Id == tenant.Id);

                tempTenant.CompanyName                    = tenant.CompanyName;
                tempTenant.Domain                         = tenant.Domain;
                tempTenant.ContactOwnerNameGiven          = tenant.ContactOwnerNameGiven;
                tempTenant.ContactOwnerNameFamily         = tenant.ContactOwnerNameFamily;
                tempTenant.ContactOwnerAddress            = tenant.ContactOwnerAddress;
                tempTenant.ContactOwnerCity               = tenant.ContactOwnerCity;
                tempTenant.ContactOwnerState              = tenant.ContactOwnerState;
                tempTenant.ContactOwnerZipCode            = tenant.ContactOwnerZipCode;
                tempTenant.ContactOwnerCountry            = tenant.ContactOwnerCountry;
                tempTenant.ContactOwnerPhone              = tenant.ContactOwnerPhone;
                tempTenant.ContactOwnerFax                = tenant.ContactOwnerFax;
                tempTenant.ContactOwnerEmail              = tenant.ContactOwnerEmail;
                tempTenant.ContactAdministratorNameGiven  = tenant.ContactAdministratorNameGiven;
                tempTenant.ContactAdministratorNameFamily = tenant.ContactAdministratorNameFamily;
                tempTenant.ContactAdministratorAddress    = tenant.ContactAdministratorAddress;
                tempTenant.ContactAdministratorCity       = tenant.ContactAdministratorCity;
                tempTenant.ContactAdministratorState      = tenant.ContactAdministratorState;
                tempTenant.ContactAdministratorZipCode    = tenant.ContactAdministratorZipCode;
                tempTenant.ContactAdministratorCountry    = tenant.ContactAdministratorCountry;
                tempTenant.ContactAdministratorPhone      = tenant.ContactAdministratorPhone;
                tempTenant.ContactAdministratorFax        = tenant.ContactAdministratorFax;
                tempTenant.ContactAdministratorEmail      = tenant.ContactAdministratorEmail;
                tempTenant.ContactBillingNameGiven        = tenant.ContactBillingNameGiven;
                tempTenant.ContactBillingNameFamily       = tenant.ContactBillingNameFamily;
                tempTenant.ContactBillingAddress          = tenant.ContactBillingAddress;
                tempTenant.ContactBillingCity             = tenant.ContactBillingCity;
                tempTenant.ContactBillingState            = tenant.ContactBillingState;
                tempTenant.ContactBillingZipCode          = tenant.ContactBillingZipCode;
                tempTenant.ContactBillingCountry          = tenant.ContactBillingCountry;
                tempTenant.ContactBillingPhone            = tenant.ContactBillingPhone;
                tempTenant.ContactBillingFax              = tenant.ContactBillingFax;
                tempTenant.ContactBillingEmail            = tenant.ContactBillingEmail;
                tempTenant.ContactTechnicalNameGiven      = tenant.ContactTechnicalNameGiven;
                tempTenant.ContactTechnicalNameFamily     = tenant.ContactTechnicalNameFamily;
                tempTenant.ContactTechnicalAddress        = tenant.ContactTechnicalAddress;
                tempTenant.ContactTechnicalCity           = tenant.ContactTechnicalCity;
                tempTenant.ContactTechnicalState          = tenant.ContactTechnicalState;
                tempTenant.ContactTechnicalZipCode        = tenant.ContactTechnicalZipCode;
                tempTenant.ContactTechnicalCountry        = tenant.ContactTechnicalCountry;
                tempTenant.ContactTechnicalPhone          = tenant.ContactTechnicalPhone;
                tempTenant.ContactTechnicalFax            = tenant.ContactTechnicalFax;
                tempTenant.ContactTechnicalEmail          = tenant.ContactTechnicalEmail;

                context.Tenants.Attach(tempTenant);
                context.Entry(tempTenant).State = System.Data.Entity.EntityState.Modified;
                context.SaveChanges();
            }
            return(Convert.ToInt32(tenant.Id));
        }
Esempio n. 5
0
 public static int SaveSubscription(TenantUserSession tenantUserSession, Subscription subscription)
 {
     using (var context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString))
     {
         if (subscription.Id < 1)
         {
             subscription = context.Subscriptions.Add(subscription);
             context.SaveChanges();
         }
         else
         {
             context.Subscriptions.Attach(subscription);
             context.Entry(subscription).State = System.Data.Entity.EntityState.Modified;
             context.SaveChanges();
         }
     }
     return(Convert.ToInt32(subscription.Id));
 }
Esempio n. 6
0
 public static int AddTenant(TenantUserSession tenantUserSession, Tenant tenant)
 {
     using (var context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString))
     {
         tenant = context.Tenants.Add(tenant);
         context.SaveChanges();
     }
     return(Convert.ToInt32(tenant.Id));
 }
Esempio n. 7
0
        public static bool SignOut(string domain, string username, string token, out Exception exception)
        {
            var    result = false;
            Tenant tenant = null;

            exception = null;

            try
            {
                if (!MasterTenantManagement.GetTenantByDomain(domain, out tenant, out exception))
                {
                    throw (exception);
                }
                if (tenant == null)
                {
                    throw (new DomainNotFoundException());
                }

                using (var context = new ContextTenant(tenant.DatabaseConnectionString))
                {
                    var user    = context.Users.SingleOrDefault(s => s.UserName == username);
                    var session = context.Sessions.SingleOrDefault(s => s.Token == token);

                    if (user == null)
                    {
                        throw (new TokenInvalidException());
                    }
                    if (session == null)
                    {
                        throw (new TokenInvalidException());
                    }
                    if (session.UserId != user.Id)
                    {
                        throw (new TokenInvalidException());
                    }
                    if (session.TenantId != tenant.Id)
                    {
                        throw (new TokenInvalidException());
                    }

                    session.DateTimeExpiration = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(1));

                    context.SaveChanges();

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 8
0
        public static bool TenantDocumentUpdate(Tenant tenant, Document document, out Exception exception)
        {
            var result = false;

            exception = null;

            try
            {
                var templates         = new List <Template>();
                var documentFragments = new List <DocumentFragment>();

                using (var context = new ContextTenant(tenant.DatabaseConnectionString))
                {
                    templates = context
                                .Templates
                                .AsNoTracking()
                                .Include(t => t.Elements)
                                .ToList();

                    // document
                    // Zones from OCR: Keep in a memory data structure.
                    // Zones to element matching will happen in memory only.
                }

                // Perform OCR and time-consuming tasks.

                using (var context = new ContextTenant(tenant.DatabaseConnectionString))
                {
                    using (var transaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            //context.Templates.Attach(templates[0]);
                            context.SaveChanges();

                            // Do not call this line from anywhere else.
                            transaction.Commit();
                        }
                        catch (Exception e)
                        {
                            transaction.Rollback();
                        }
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 9
0
        private static ScanSession EditScanSessionPrivate(TenantUserSession tenantUserSession, long id, string name, string description, ContextTenant context)
        {
            var scanSession = context.ScanSessions.Where(x => x.Id == id).FirstOrDefault();

            if (scanSession == null)
            {
                throw (new Exception("Unable to find the following scan session"));
            }
            scanSession.Name        = name;
            scanSession.Description = description;
            context.SaveChanges();
            return(scanSession);
        }
Esempio n. 10
0
        public static int SaveTenantSubscription(TenantUserSession tenantUserSession, TenantSubscription subscribtion)
        {
            using (var context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString))
            {
                subscribtion.Subscription             = context.Subscriptions.Where(s => s.Id == subscribtion.Subscription.Id).FirstOrDefault();
                subscribtion.NumberOfFormsAllowed     = subscribtion.Subscription.NumberOfFormsAllowed;
                subscribtion.NumberOfFormsUsed        = subscribtion.Subscription.NumberOfFormsUsed;
                subscribtion.NumberOfPagesAllowed     = subscribtion.Subscription.NumberOfPagesAllowed;
                subscribtion.NumberOfPagesUsed        = subscribtion.Subscription.NumberOfPagesUsed;
                subscribtion.NumberOfTemplatesAllowed = subscribtion.Subscription.NumberOfTemplatesAllowed;
                subscribtion.NumberOfUsersAllowed     = subscribtion.Subscription.NumberOfUsersAllowed;
                subscribtion.NumberOfUsersUsed        = subscribtion.Subscription.NumberOfUsersUsed;

                subscribtion = context.TenantSubscriptions.Add(subscribtion);
                context.SaveChanges();
            }
            return(Convert.ToInt32(subscribtion.TenantId));
        }
Esempio n. 11
0
        public static bool TenantDocumentGet(Tenant tenant, out Document document, out Exception exception)
        {
            var result = false;

            document  = null;
            exception = null;

            try
            {
                using (var context = new ContextTenant(tenant.DatabaseConnectionString))
                {
                    var documentTemp = context
                                       .Documents
                                       .Where(d => (((d.State == DocumentState.QueuedAuto) || (d.State == DocumentState.QueuedManual)) && (d.CountAttemptOcr <= 3) && (d.LatestCheckedOutByUserId <= 0)))
                                       .FirstOrDefault();

                    if (documentTemp != null)
                    {
                        documentTemp.CountAttemptOcr++;
                        if (documentTemp.Confidence == null)
                        {
                            documentTemp.Confidence = 0;
                        }
                        context.SaveChanges();

                        document = context
                                   .Documents
                                   .AsNoTracking()
                                   .Include(d => d.User)
                                   .Include(d => d.Folder)
                                   .Single(d => d.Id == documentTemp.Id);
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                exception = e;
                document  = null;
            }

            return(result);
        }
Esempio n. 12
0
        public static bool DeleteVendor(TenantUserSession tenantUserSession, Vendor vendor, out Exception exception)
        {
            exception = null;
            bool result = false;

            try
            {
                ContextTenant context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString);
                Vendor        temp    = context.Vendors.Where(x => x.Id == vendor.Id).Select(x => x).FirstOrDefault();
                context.Vendors.Remove(temp);
                context.SaveChanges();
                result = true;
            }
            catch (Exception ex)
            {
                exception = ex;
                result    = false;
            }
            return(result);
        }
Esempio n. 13
0
        public static bool UpdateBlobbatchstatus(TenantUserSession tenantUserSession, azureblob azureblob, out Exception exception)
        {
            exception = null;
            bool result = false;

            try
            {
                ContextTenant context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString);
                azureblob     temp    = context.azureblobs.Where(x => x.batchno == azureblob.batchno).Select(x => x).FirstOrDefault();
                temp.status = azureblob.status;
                context.azureblobs.Add(temp);
                context.SaveChanges();
                result = true;
            }
            catch (Exception ex)
            {
                exception = ex;
                result    = false;
            }
            return(result);
        }
Esempio n. 14
0
        private static ScanSession ScanSessionEntryFinalizePrivate(TenantUserSession tenantUserSession, long scanSessionId, ContextTenant context)
        {
            if (context == null)
            {
                throw (new ArgumentNullException("context"));
            }
            if (scanSessionId <= 0)
            {
                throw (new Exception("Unable to find the following scan session"));
            }

            ScanSession scanSession = context.ScanSessions.Where(x => x.Id == scanSessionId).FirstOrDefault();

            if (scanSession != null)
            {
                throw (new Exception("Unable to find the following scan session"));
            }
            scanSession.Finalized = true;
            scanSession           = context.ScanSessions.Add(scanSession);
            context.SaveChanges();
            return(scanSession);
        }
Esempio n. 15
0
        public static void Seed(ContextTenant contextTenant)
        {
            try
            {
                contextTenant.SaveChanges();
            }
            catch (Exception exception)
            {
                if (AffinityConfiguration.IsConfigurationDebug)
                {
                    Debugger.Break();

                    if (AffinityConfiguration.DeploymentLocation != DeploymentLocation.Live)
                    {
                        Debug.Print(exception.ToString());
                    }
                }
                else
                {
                    throw;
                }
            }
        }
Esempio n. 16
0
        public static bool AddVendor(TenantUserSession tenantUserSession, Vendor vendor, out Exception exception)
        {
            exception = null;
            bool result = false;

            try
            {
                using (var context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString))
                {
                    if (vendor != null)
                    {
                        context.Vendors.Add(vendor);
                        context.SaveChanges();

                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 17
0
        public static bool AddLog(TenantUserSession tenantUserSession, Log auditlog, out Exception exception)
        {
            exception = null;
            bool result = false;

            try
            {
                using (var context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString))
                {
                    if (auditlog != null)
                    {
                        context.Logs.Add(auditlog);
                        context.SaveChanges();

                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 18
0
        public static bool AddBlob(TenantUserSession tenantUserSession, azureblob azureblob, out Exception exception)
        {
            exception = null;
            bool result = false;

            try
            {
                using (var context = new ContextTenant(tenantUserSession.Tenant.DatabaseConnectionString))
                {
                    if (azureblob != null)
                    {
                        context.azureblobs.Add(azureblob);
                        context.SaveChanges();

                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            return(result);
        }
Esempio n. 19
0
        private static void UpdateLiveTenantDatabases(IEnumerable <string> productionDomainsToBeUpdated)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"----------------------------------------------------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"UpdateLiveTenantDatabases.");

            Uri uri;
            var encoding           = Encoding.UTF8;
            var tenantsMasterLive  = new List <Tenant>();
            var tenantsMasterLocal = new List <Tenant>();
            // var builderTenantLive = new SqlConnectionStringBuilder();
            var builderTenantLocal = new SqlConnectionStringBuilder();
            //var builderMasterLive = AffinityConfigurationMaster.GetDatabaseConnectionStringBuilder(DeploymentLocation.Live);
            var builderMasterLocal = AffinityConfigurationMaster.GetDatabaseConnectionStringBuilder(AffinityConfiguration.DeploymentLocation);

            if
            (
                (productionDomainsToBeUpdated.Any())
                &&
                (
                    productionDomainsToBeUpdated.All
                    (
                        d =>
                        (!string.IsNullOrWhiteSpace(d)) &&
                        (Uri.CheckHostName(d) == UriHostNameType.Dns) &&
                        (Uri.TryCreate(d, UriKind.RelativeOrAbsolute, out uri)) &&
                        (!uri.IsAbsoluteUri) &&
                        (!uri.UserEscaped)
                    )
                )
            )
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Domains selected to be updated:");
                Console.WriteLine();
                Console.Write(string.Join(Environment.NewLine, productionDomainsToBeUpdated.Select(d => $" - {d}")));
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Either no domains were passed in, or at least one of the domains");
                Console.WriteLine();
                Console.Write($"was empty, null or invalid. Domains should be in the form of: [xyz.com].");
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"The utility will now return.");

                return;
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"WARNING: This action cannot be undone!");
            Console.WriteLine();
            Console.Write($"Press [Y] to run the action, any other key to cancel: ");

            var consoleKeyInfo = Console.ReadKey(intercept: true);

            if (consoleKeyInfo.Key == ConsoleKey.Y)
            {
                Console.Write("Y");
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"WARNING: Once again, this action cannot be undone!");
                Console.WriteLine();
                Console.Write($"Press [Y] to run the action, any other key to cancel: ");

                consoleKeyInfo = Console.ReadKey(intercept: true);

                if (consoleKeyInfo.Key == ConsoleKey.Y)
                {
                    Console.Write("Y");
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.Write($"Well, you WERE warned! Continuing script execution...");
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.Write($"Script execution cancelled. Phew!!!");

                    return;
                }
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Script execution cancelled. Phew!!!");

                return;
            }

            Program.InitializeLocalDatabases();

            var fileScript = new FileInfo(Assembly.GetExecutingAssembly().Location);

            fileScript = new FileInfo(Path.Combine(fileScript.Directory.FullName, @"..\..\..\HouseOfSynergy.AffinityDms.Library\Database\Script Schema Drop Create Data Insert.sql"));
            if (!fileScript.Exists)
            {
                throw (new FileNotFoundException($"File not found: {fileScript.FullName}.", fileScript.FullName));
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Getting live tenants from master...");
            using (var contextMasterLive = new ContextMaster(deploymentLocation: DeploymentLocation.Live))
            {
                tenantsMasterLive = contextMasterLive.Tenants.ToList();
            }

            var validDomains   = tenantsMasterLive.ConvertAll(t => t.Domain);
            var invalidDomains = productionDomainsToBeUpdated.Where(d => !validDomains.Contains(d));

            Console.WriteLine();
            Console.Write($"Domains found in the master database:");
            Console.WriteLine();
            Console.Write(string.Join(Environment.NewLine, validDomains.Select(d => $" - {d}")));

            if (invalidDomains.Any())
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"The following domains do not exist in the master database:");
                Console.WriteLine();
                Console.Write(string.Join(Environment.NewLine, invalidDomains.Select(d => $" - {d}")));
                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"The utility will now return.");

                return;
            }

            tenantsMasterLive = tenantsMasterLive.Where(t => productionDomainsToBeUpdated.Contains(t.Domain)).ToList();

            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Updating live tenants...");
            foreach (var tenantMasterLive in tenantsMasterLive)
            {
                var tenantTenantLive       = tenantMasterLive.Clone();
                var databaseNameTenantLive = new SqlConnectionStringBuilder(tenantMasterLive.DatabaseConnectionString).InitialCatalog;

                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Tenant: [{tenantMasterLive.Domain}].");

                using (var contextMasterLocal = new ContextMaster())
                {
                    var tenantMasterLocal = contextMasterLocal.Tenants.SingleOrDefault(t => t.Domain.ToLower() == tenantMasterLive.Domain.ToLower());

                    builderTenantLocal = new SqlConnectionStringBuilder(tenantMasterLocal.DatabaseConnectionString);
                }

                // Generate Drop, Create & Seed Script.
                //builderTenantLocal = new SqlConnectionStringBuilder()
                //{
                //    DataSource = @"BENZFARAZ-PC\SQLEXPRESS",
                //    InitialCatalog = "AffinityDmsTenant_0000000000000000002",
                //    IntegratedSecurity = true,
                //    UserID = @"sa",
                //    Password = @"123456",
                //    MultipleActiveResultSets = false,
                //    PersistSecurityInfo = true
                //};

                // Generate Drop, Create & Seed Script.
                builderTenantLocal = new SqlConnectionStringBuilder()
                {
                    DataSource = @"Lenovo",
                    //DataSource = @"HOSLAPTOPHP\MSSQLS2016EXP",
                    InitialCatalog     = "AffinityDmsTenant_0000000000000000001",
                    IntegratedSecurity = true,
                    //UserID = @"",
                    //Password = @"",
                    //MultipleActiveResultSets = false,
                    PersistSecurityInfo = true
                };

                Program.GenerateScript(builderTenantLocal, databaseNameTenantLive, fileScript, encoding);

                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Execute script against the respective live tenant.");
                using (var contextTenantLive = new ContextTenant(tenantTenantLive.DatabaseConnectionString))
                {
                    var script = File.ReadAllText(fileScript.FullName, encoding);

                    var t = contextTenantLive.Tenants.ToList();

                    contextTenantLive.Database.CommandTimeout = 30 * 60;
                    contextTenantLive.Database.ExecuteSqlCommand(script);
                }

                Console.WriteLine();
                Console.WriteLine();
                Console.Write($"Correcting script parameters.");
                using (var contextTenantLive = new ContextTenant(tenantTenantLive.DatabaseConnectionString))
                {
                    tenantTenantLive.Id         = 1; // To update the single tenant row.
                    tenantTenantLive.TenantType = EntityMasterTenantType.Tenant;

                    contextTenantLive.Tenants.Attach(tenantTenantLive);
                    contextTenantLive.SaveChanges();
                }
            }
        }
Esempio n. 20
0
        public static void ThrowOnInvalidToken
        (
            string token,
            SessionType sessionType,
            string domain,
            string username,
            string clientIpAddress,
            string userAgent,
            long ticks,
            string sessionId,
            out TenantUserSession tenantUserSession
        )
        {
            User      userDatabase    = null;
            Exception exception       = null;
            Tenant    tenantDatabase  = null;
            Session   sessionDatabase = null;

            tenantUserSession = null;
            if ((clientIpAddress != null) && (!clientIpAddress.Contains("::1")))
            {
                if (clientIpAddress.Contains(":"))
                {
                    clientIpAddress = clientIpAddress.Split(new string[] { ":" }, StringSplitOptions.None)[0];
                }
            }
            if (!MasterTenantManagement.GetTenantByDomain(domain, out tenantDatabase, out exception))
            {
                throw (exception);
            }
            if (tenantDatabase == null)
            {
                throw (new DomainNotFoundException());
            }

            if (!tenantDatabase.TenantSubscriptions.Any(ts => ts.IsActive))
            {
                throw (new TenantNotAuthorizedException());
            }

            using (var context = new ContextTenant(tenantDatabase.DatabaseConnectionString))
            {
                var now = DateTime.UtcNow;
                var sessionsDatabase = context
                                       .Sessions
                                       .Include(p => p.User)
                                       .Where
                                       (
                    s =>
                    (
                        // TODO: Add checks.
                        (s.DateTimeCreated < now) &&
                        (s.DateTimeExpiration > now) &&
                        (s.SessionId == sessionId) &&
                        (s.Token == token) &&
                        (s.UserAgent == userAgent) &&
                        (s.IPAddressString == clientIpAddress) &&
                        (s.SessionType == sessionType)
                    )
                                       )
                                       .ToList();

                var lines = new List <string>();
                lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
                lines.Add($"VALIDATE TOKEN");
                lines.Add($"Session Found: {sessionDatabase != null}");
                lines.Add($"now: {now}");
                lines.Add($"SessionId: {sessionId}");
                lines.Add($"token: {token}");
                lines.Add($"useragent: {userAgent}");
                lines.Add($"ipAddressString: {clientIpAddress}");
                lines.Add($"sessionType: {sessionType}");
                lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
                AffinityConfiguration.Messages.Add(string.Join("<br />", lines));

                if (sessionsDatabase.Count > 1)
                {
                    // Order by Id (descending).
                    sessionsDatabase.Sort((x, y) => x.Id.CompareTo(y.Id));

                    do
                    {
                        context.Sessions.Remove(sessionsDatabase.First());
                        context.SaveChanges();
                        sessionsDatabase.Remove(sessionsDatabase.First());
                    }while (sessionsDatabase.Count > 1);

                    context.SaveChanges();
                }

                if (sessionsDatabase.Count < 1)
                {
                    throw (new TokenInvalidException());
                }
                else if (sessionsDatabase.Count > 1)
                {
                    throw (new Exception("Multiple session matches were found. This is a dev bug!"));
                }

                sessionDatabase = sessionsDatabase.Single();
                sessionDatabase = context.Sessions.AsNoTracking().Include(s => s.User).Single(s => s.Id == sessionDatabase.Id);
                userDatabase    = context.Users.AsNoTracking().Include(u => u.Roles).Include(u => u.UserRoles).Single(u => u.Id == sessionDatabase.User.Id);

                userDatabase.PasswordHash   = "";
                userDatabase.PasswordSalt   = "";
                sessionDatabase.RijndaelKey = "";
                sessionDatabase.RijndaelInitializationVector = "";
                sessionDatabase.RsaKeyPublic             = (sessionType == SessionType.Api) ? sessionDatabase.RsaKeyPublic : "";
                sessionDatabase.RsaKeyPrivate            = "";
                tenantDatabase.RsaKeyPublic              = (sessionType == SessionType.Api) ? tenantDatabase.RsaKeyPublic : "";
                tenantDatabase.RsaKeyPrivate             = "";
                tenantDatabase.StorageAccessKeyPrimary   = "";
                tenantDatabase.StorageAccessKeySecondary = "";
                //tenantDatabase.StorageConnectionStringPrimary = "";
                //tenantDatabase.StorageConnectionStringSecondary = "";

                if (sessionType == SessionType.Api)
                {
                    // Remove circular references for DTO Serialization.
                    foreach (var ts in tenantDatabase.TenantSubscriptions)
                    {
                        ts.Tenant = null;
                    }
                    foreach (var r in userDatabase.Roles)
                    {
                        r.Users.Clear(); r.UserRoles.Clear();
                    }
                }

                // The out parameter [tenantUserSession] should not be assigned until
                //	the objects passed to its constructor are fully populated and scrubbed.
                tenantUserSession = new TenantUserSession(tenantDatabase, userDatabase, sessionDatabase);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Authentication using: [Salted password hashing with PBKDF2-SHA1].
        /// Implementation available at: [HouseOfSynergy.PowerTools.Library.Security.Cryptography.PasswordHash].
        /// The password should never reach here in plain text. It should be hashed using Sha512 in TypeScript or JavaScript.
        /// A C# implementation of Sha512 is available at: [HouseOfSynergy.PowerTools.Library.Security.Cryptography.Sha].
        /// </summary>
        /// <param name="sessionType">The origin of the request.</param>
        /// <param name="domain">The domain of the requested tenant.</param>
        /// <param name="username">Username in plain text.</param>
        /// <param name="passwordHash">Password from client hashed using Sha512.</param>
        /// <param name="clientIpAddress">The IP Address the request originated from.</param>
        /// <param name="userAgent">The User Agent of the request.</param>
        /// <param name="ticks">The user's timestamp in ticks.</param>
        /// <param name="ticks">The requests server Session Id.</param>
        /// <param name="tenantUserSession">Populates the out tenantUserSession if the function succeeds.</param>
        /// <param name="exception">Populates the out exception where applicable.</param>
        /// <returns>Returns true if sign-in succeeds. Otherwise, populates the out exception parameter.</returns>
        public static bool SignIn
        (
            SessionType sessionType,
            string domain,
            string username,
            string passwordHash,
            string clientIpAddress,
            string userAgent,
            long ticks,
            string sessionId,
            out TenantUserSession tenantUserSession,
            out Exception exception
        )
        {
            var     result          = false;
            User    userDatabase    = null;
            var     now             = DateTime.UtcNow;
            Tenant  tenantDatabase  = null;
            Session sessionDatabase = null;

            exception         = null;
            tenantUserSession = null;

            try
            {
                if (!MasterTenantManagement.GetTenantByDomain(domain, out tenantDatabase, out exception))
                {
                    throw (exception);
                }
                if (tenantDatabase == null)
                {
                    throw (new DomainNotFoundException());
                }

                // ContextTenant.Initialize(tenantDatabase.DatabaseConnectionString);

                using (var context = new ContextTenant(tenantDatabase.DatabaseConnectionString))
                {
                    tenantDatabase = context.Tenants.SingleOrDefault();
                    if (tenantDatabase == null)
                    {
                        throw (new DomainNotFoundException());
                    }

                    // TODO: Use a single exception for unmatched username/password scenarios.
                    userDatabase = context.Users.SingleOrDefault(u => (u.UserName == username));
                    if (userDatabase == null)
                    {
                        throw (new AuthenticationException(isValidDomain: true, isValidUsername: false, isValidPassword: null));
                    }

                    if (!PasswordHash.ValidatePassword(passwordHash, userDatabase.PasswordHash))
                    {
                        throw (new AuthenticationException(isValidDomain: true, isValidUsername: true, isValidPassword: false));
                    }

                    var token
                        = tenantDatabase.Id.ToString()
                          + EntityConstants.TokenDelimiter
                          + tenantDatabase.Domain
                          + EntityConstants.TokenDelimiter
                          + userDatabase.Id.ToString()
                          + EntityConstants.TokenDelimiter
                          + userDatabase.UserName
                          + EntityConstants.TokenDelimiter
                          + userDatabase.AuthenticationType.ToString()
                          + EntityConstants.TokenDelimiter
                          + (userDatabase.ActiveDirectory_ObjectId.ToString(GuidUtilities.EnumGuidFormat.N.ToString())).Trim()
                          + EntityConstants.TokenDelimiter
                          + ""
                          + EntityConstants.TokenDelimiter
                          + sessionType.ToString()
                          + EntityConstants.TokenDelimiter
                          + EntityConstants.TokenDelimiter
                          + EntityConstants.TokenDelimiter;

                    // TODO: Remove for production.
                    if (AffinityConfiguration.DeploymentLocation == DeploymentLocation.BtsSaleem)
                    {
                        now = now.Add(TimeSpan.FromHours(1));
                    }

                    //clientIpAddress.r

                    sessionDatabase = userDatabase.Sessions.SingleOrDefault
                                      (
                        s =>
                        (
                            (s.DateTimeCreated < now) &&
                            (s.DateTimeExpiration > now) &&
                            (s.SessionId == sessionId) &&
                            (s.Token == token) &&
                            (s.UserAgent == userAgent) &&
                            (s.IPAddressString == clientIpAddress) &&
                            (s.SessionType == sessionType)
                        )
                                      );

                    var lines = new List <string>();
                    lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
                    lines.Add($"SIGNIN TOKEN");
                    lines.Add($"Session Found: {sessionDatabase != null}");
                    lines.Add($"now: {now}");
                    lines.Add($"SessionId: {sessionId}");
                    lines.Add($"token: {token}");
                    lines.Add($"useragent: {userAgent}");
                    lines.Add($"ipAddressString: {clientIpAddress}");
                    lines.Add($"sessionType: {sessionType}");
                    lines.Add($"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
                    AffinityConfiguration.Messages.Add(string.Join("<br />", lines));

                    // TODO: Remove for production.
                    if (AffinityConfiguration.DeploymentLocation == DeploymentLocation.BtsSaleem)
                    {
                        now = now.Subtract(TimeSpan.FromHours(2));
                    }

                    if (sessionDatabase == null)
                    {
                        var guid        = Guid.NewGuid();
                        var rijndaelKey = new byte[GlobalConstants.AlgorithmSymmetricKeySize];
                        var rijndaelInitializationVector = new byte[GlobalConstants.AlgorithmSymmetricInitializationVectorSize];
                        var rsaKeyPair = Rsa.GenerateKeyPair(GlobalConstants.AlgorithmAsymmetricKeySize);

                        using (var randomNumberGenerator = RandomNumberGenerator.Create())
                        {
                            randomNumberGenerator.GetBytes(rijndaelKey);
                            randomNumberGenerator.GetBytes(rijndaelInitializationVector);
                        }

                        do
                        {
                            guid = Guid.NewGuid();
                        } while (context.Sessions.Any(s => s.Guid == guid));

                        sessionDatabase                              = new Session();
                        sessionDatabase.Guid                         = guid;
                        sessionDatabase.CultureName                  = "en";
                        sessionDatabase.Token                        = token;
                        sessionDatabase.SessionId                    = sessionId;
                        sessionDatabase.SessionType                  = sessionType;
                        sessionDatabase.UserAgent                    = userAgent;
                        sessionDatabase.IPAddressString              = clientIpAddress;
                        sessionDatabase.DeviceType                   = DeviceType.Unknown;
                        sessionDatabase.DateTimeCreated              = now;
                        sessionDatabase.DateTimeExpiration           = sessionDatabase.DateTimeCreated.Add(TimeSpan.FromDays(1));
                        sessionDatabase.RijndaelKey                  = Convert.ToBase64String(rijndaelKey);
                        sessionDatabase.RijndaelInitializationVector = Convert.ToBase64String(rijndaelInitializationVector);
                        sessionDatabase.RsaKeyPublic                 = rsaKeyPair.KeyPublic.KeyToString();
                        sessionDatabase.RsaKeyPrivate                = rsaKeyPair.KeyPrivate.KeyToString();
                        sessionDatabase.User                         = userDatabase;
                        sessionDatabase.UserId                       = userDatabase.Id;
                        sessionDatabase.Tenant                       = tenantDatabase;
                        sessionDatabase.TenantId                     = tenantDatabase.Id;
                        context.Sessions.Add(sessionDatabase);
                        context.SaveChanges();
                    }
                    else
                    {
                        sessionDatabase.DateTimeExpiration = now.Add(TimeSpan.FromDays(1));
                        context.SaveChanges();
                    }

                    var sessions = userDatabase.Sessions.Where(s => s.DateTimeExpiration < now.Subtract(TimeSpan.FromDays(30)));
                    foreach (var s in sessions)
                    {
                        context.Sessions.Remove(s);
                    }
                    context.SaveChanges();

                    sessionDatabase = context.Sessions.AsNoTracking().Single(s => s.Id == sessionDatabase.Id);
                    userDatabase    = context.Users.AsNoTracking().Include(p => p.Roles).AsNoTracking().Single(u => u.Id == userDatabase.Id);
                    tenantDatabase  = context.Tenants.AsNoTracking().Include(t => t.TenantSubscriptions).Single(t => t.Id == tenantDatabase.Id);

                    userDatabase.PasswordHash   = "";
                    userDatabase.PasswordSalt   = "";
                    sessionDatabase.RijndaelKey = "";
                    sessionDatabase.RijndaelInitializationVector = "";
                    sessionDatabase.RsaKeyPrivate                   = "";
                    sessionDatabase.RsaKeyPublic                    = (sessionType == SessionType.Api) ? sessionDatabase.RsaKeyPublic : "";
                    tenantDatabase.RsaKeyPrivate                    = "";
                    tenantDatabase.RsaKeyPublic                     = (sessionType == SessionType.Api) ? tenantDatabase.RsaKeyPublic : "";
                    tenantDatabase.StorageAccessKeyPrimary          = "";
                    tenantDatabase.StorageAccessKeySecondary        = "";
                    tenantDatabase.StorageConnectionStringPrimary   = (sessionType == SessionType.Mvc) ? tenantDatabase.StorageConnectionStringPrimary : "";
                    tenantDatabase.StorageConnectionStringSecondary = (sessionType == SessionType.Mvc) ? tenantDatabase.StorageConnectionStringSecondary : "";

                    if (sessionType == SessionType.Api)
                    {
                        foreach (var ts in tenantDatabase.TenantSubscriptions)
                        {
                            ts.Tenant = null;
                        }
                        foreach (var r in userDatabase.Roles)
                        {
                            r.Users.Clear(); r.UserRoles.Clear();
                        }
                    }

                    // The out parameter [tenantUserSession] should not be assigned until
                    //	the objects passed to its constructor are fully populated and scrubbed.
                    tenantUserSession = new TenantUserSession(tenantDatabase, userDatabase, sessionDatabase);

                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }
Esempio n. 22
0
        private static void GenerateDocuments()
        {
            Tenant tenant = null;
            var    random = new System.Random();

            try
            {
                using (var contextMaster = new ContextMaster())
                {
                    tenant = contextMaster
                             .Tenants
                             .AsNoTracking()
                             .Include(t => t.Users)
                             .First();
                }

                using (var context = new ContextTenant(tenant.DatabaseConnectionString))
                {
                    using (var transaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            //var countTemplates = 10;

                            //for (int i = 0; i < countTemplates; i++)
                            //{
                            //	var elements = new List<TemplateElement> ();
                            //	var template = new Template () { Title = "", Description = "", };
                            //	context.Templates.Add (template);
                            //	context.SaveChanges ();
                            //	template.Title = "Template " + template.Id.ToString ().PadLeft (long.MaxValue.ToString ().Length, '0');
                            //	context.SaveChanges ();

                            //	var file = PathUtilities.GetTempFile (".png", false);
                            //	using (var bitmap = new Bitmap (random.Next (500, 1000), random.Next (500, 1000), PixelFormat.Format32bppArgb))
                            //	{
                            //		using (var graphics = Graphics.FromImage (bitmap))
                            //		{
                            //			graphics.SetQualityHighest ();
                            //			graphics.Clear (Color.White);

                            //			var size = SizeF.Empty;
                            //			TemplateElement element = null;
                            //			var font = new Font (FontFamily.GenericMonospace, 12F);

                            //			element = new TemplateElement () { Name = "", Description = "", X = 0, Y = 0, X2 = 0, Y2 = 0, Width = "", Height = "", TemplateId = template.Id, };
                            //			template.Elements.Add (element);
                            //			context.SaveChanges ();
                            //			element.Name = "Element " + element.Id.ToString ().PadLeft (long.MaxValue.ToString ().Length, '0');
                            //			context.SaveChanges ();
                            //			element.Value = "INVOICE";
                            //			element.ElementIndexType = 1;
                            //			element.ElementType = (int) ElementType.Label;
                            //			size = graphics.MeasureString (element.Value, font);
                            //			element.X = 10;
                            //			element.Y = 10;
                            //			element.X2 = element.X + size.Width;
                            //			element.Y2 = element.X + size.Height;
                            //			//element.Width
                            //			context.SaveChanges ();
                            //			elements.Add (element);
                            //			graphics.DrawRectangle (Pens.Black, RectangleF.FromLTRB (element.X, element.Y, element.X2, element.Y2));
                            //			graphics.DrawString (element.Value, font, Brushes.Black, element.X, element.Y);

                            //			element = new TemplateElement () { Name = "", Description = "", X = 0, Y = 0, X2 = 0, Y2 = 0, Width = "", Height = "", TemplateId = template.Id, };
                            //			template.Elements.Add (element);
                            //			context.SaveChanges ();
                            //			element.Name = "Element " + element.Id.ToString ().PadLeft (long.MaxValue.ToString ().Length, '0');
                            //			context.SaveChanges ();
                            //			element.Value = "INV #:";
                            //			element.ElementIndexType = 1;
                            //			element.ElementType = (int) ElementType.Label;
                            //			size = graphics.MeasureString (element.Value, font);
                            //			element.X = 100;
                            //			element.Y = 50;
                            //			element.X2 = element.X + size.Width;
                            //			element.Y2 = element.X + size.Height;
                            //			//element.Width
                            //			context.SaveChanges ();
                            //			elements.Add (element);
                            //			graphics.DrawRectangle (Pens.Black, RectangleF.FromLTRB (element.X, element.Y, element.X2, element.Y2));
                            //			graphics.DrawString (element.Value, font, Brushes.Black, element.X, element.Y);
                            //		}

                            //		bitmap.Save (file.FullName, ImageFormat.Png);
                            //		Program.TemplateUpload (tenant, template, file);
                            //		//OcrTest.CreateTemplateFiles (tenant, template, file, elements);
                            //	}
                            //}

                            context.SaveChanges();
                            transaction.Commit();
                        }
                        catch (Exception exception)
                        {
                            transaction.Rollback();
                            Debug.Write(exception);
                            Debugger.Break();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Debug.Write(exception);
                Debugger.Break();
            }
        }
        public static bool CreateTenantSubscriptionAndDeactivateExistingTenantSubscription(MasterUserSession MasterUserSession, long existingtenantsubscriptionid, Subscription subscriptionMaster, TenantSubscription tenantsubscriptionMaster, out Exception exception)
        {
            var result = false;

            exception = null;
            //System.Data.Common.DbTransaction Tran = null;
            //ContextMaster context = new ContextMaster();
            //context.ObjectContext.Connection.Open();
            //Tran = context.ObjectContext.Connection.BeginTransaction();
            DbContextTransaction masterTrans = null;
            DbContextTransaction tenantTrans = null;

            using (var contextMaster = new ContextMaster())
            {
                try
                {
                    using (masterTrans = contextMaster.Database.BeginTransaction())
                    {
                        try
                        {
                            var existingSubscriptions = contextMaster.TenantSubscriptions.Where(x => (x.TenantId == existingtenantsubscriptionid) && (x.IsActive == true)).ToList();

                            foreach (var existingSubnscription in existingSubscriptions)
                            {
                                existingSubnscription.IsActive = false;
                                contextMaster.SaveChanges();
                            }

                            contextMaster.TenantSubscriptions.Add(tenantsubscriptionMaster);
                            contextMaster.SaveChanges();
                            tenantsubscriptionMaster.MasterTenantSubscriptionId = tenantsubscriptionMaster.Id;
                            contextMaster.Entry(tenantsubscriptionMaster).State = EntityState.Modified;
                            contextMaster.SaveChanges();

                            var tenant = contextMaster.Tenants.SingleOrDefault(x => x.Id == tenantsubscriptionMaster.TenantId);

                            if (tenant == null)
                            {
                                throw (new Exception("Unable to Find Tenant in the Master DB."));
                            }

                            using (var contextTenant = new ContextTenant(tenant.DatabaseConnectionString))
                            {
                                try
                                {
                                    using (tenantTrans = contextTenant.Database.BeginTransaction())
                                    {
                                        var existingtenantsubscriptionstenant = contextTenant.TenantSubscriptions.Where(x => (x.IsActive == true)).ToList();

                                        foreach (var existingSubscriptionTenant in existingtenantsubscriptionstenant)
                                        {
                                            existingSubscriptionTenant.IsActive = false;
                                            contextTenant.SaveChanges();
                                        }

                                        var subscriptionTenant = contextTenant.Subscriptions.SingleOrDefault(s => s.MasterSubscriptionId == subscriptionMaster.Id);

                                        if (subscriptionTenant == null)
                                        {
                                            subscriptionTenant    = subscriptionMaster.Clone();
                                            subscriptionTenant.Id = 0;
                                            subscriptionTenant.MasterSubscriptionId = subscriptionMaster.Id;
                                            subscriptionTenant.SubscriptionType     = EntityMasterTenantType.Tenant;
                                            contextTenant.Subscriptions.Add(subscriptionTenant);
                                            contextTenant.SaveChanges();
                                        }
                                        else
                                        {
                                            //subscriptionTenant = subscription.Clone();
                                            //subscriptionTenant.MasterTenantId = subscription.Id;//Yeh Maam Nay kerwaya hai.
                                            //contextTenant.Entry(subscriptionTenant).State = EntityState.Modified;
                                            //contextTenant.SaveChanges();
                                        }

                                        var count = contextTenant.Tenants.Count();
                                        if (count != 1)
                                        {
                                            throw (new Exception($"The number of tenant entries found in the Tenant database was {count} instead of 1."));
                                        }
                                        var tenantTenant = contextTenant.Tenants.Single();

                                        var tenantsubscriptionTenant   = tenantsubscriptionMaster;
                                        var masterTenantSubscriptionId = contextMaster.TenantSubscriptions.AsNoTracking().Where(x => x.IsActive == true).FirstOrDefault().Id;
                                        tenantsubscriptionTenant.MasterTenantSubscriptionId = tenantsubscriptionMaster.Id;
                                        tenantsubscriptionTenant.Id                     = 0;
                                        tenantsubscriptionTenant.SubscriptionId         = subscriptionTenant.Id;
                                        tenantsubscriptionTenant.Tenant                 = null;
                                        tenantsubscriptionTenant.TenantId               = tenantTenant.Id;
                                        tenantsubscriptionTenant.TenantSubscriptionType = EntityMasterTenantType.Tenant;
                                        contextTenant.TenantSubscriptions.Add(tenantsubscriptionTenant);
                                        contextTenant.SaveChanges();



                                        try

                                        {
                                            tenantTrans.Commit();
                                            masterTrans.Commit();
                                        }
                                        catch
                                        {
                                            tenantTrans.Rollback();
                                            masterTrans.Rollback();
                                        }

                                        result = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    exception = ex;
                                    throw;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            exception = ex;
                            throw;
                            //Tran.Rollback();
                            //Tran.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = ex;
                    masterTrans.Rollback();
                    tenantTrans.Rollback();
                    masterTrans.Dispose();
                    tenantTrans.Dispose();
                }
            }

            return(result);
        }
        public static bool CreateTenantSubscription(MasterUserSession MasterUserSession, TenantSubscription tenantsubscription, out TenantSubscription outtenantsubscription, out Exception exception)
        {
            var result = false;

            //tenant = null;
            outtenantsubscription = null;
            exception             = null;

            try
            {
                using (var context = new ContextMaster())
                {
                    DbContextTransaction mastertrans = null;
                    DbContextTransaction tenanttrans = null;
                    try
                    {
                        using (mastertrans = context.Database.BeginTransaction())
                        {
                            outtenantsubscription = context.TenantSubscriptions.Add(tenantsubscription);
                            context.SaveChanges();
                            var tenant       = context.Tenants.Where(x => x.Id == tenantsubscription.TenantId).FirstOrDefault();
                            var subscription = context.Subscriptions.Where(x => x.Id == tenantsubscription.SubscriptionId).FirstOrDefault();
                            using (var contexttenant = new ContextTenant(tenant.DatabaseConnectionString))
                            {
                                try
                                {
                                    using (tenanttrans = contexttenant.Database.BeginTransaction())
                                    {
                                        var mastersubscriptionid = subscription.Id;
                                        subscription.Id = 0;
                                        contexttenant.Subscriptions.Add(subscription);
                                        contexttenant.SaveChanges();
                                        tenantsubscription.SubscriptionId = subscription.Id;
                                        contexttenant.TenantSubscriptions.Add(tenantsubscription);
                                        contexttenant.SaveChanges();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    exception = ex;
                                    throw ex;
                                }
                            }
                            tenanttrans.Commit();
                            mastertrans.Commit();
                        }
                    }
                    catch (Exception ex)
                    {
                        if (mastertrans != null)
                        {
                            mastertrans.Rollback();
                            mastertrans.Dispose();
                        }
                        if (tenanttrans != null)
                        {
                            tenanttrans.Rollback();
                            tenanttrans.Dispose();
                        }
                        exception = ex;
                        throw ex;
                    }
                }
                result = true;
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            return(result);
        }
Esempio n. 25
0
        public static bool TenantDocumentPerformOcr(Tenant tenant, Document document, WorkerRoleParameters workerRoleParameters, out Exception exception)
        {
            var      result      = false;
            Document ocrDocument = null;
            List <DocumentTemplate> ocrDocumentTemplate = null;
            List <DocumentFragment> ocrDocumentFragment = null;

            exception = null;

            try
            {
                List <Template>        allTemplates = null;
                List <TemplateElement> allElements  = null;

                using (var context = new ContextTenant(tenant.DatabaseConnectionString))
                {
                    allTemplates = context
                                   .Templates
                                   .AsNoTracking()
                                   .Include(t => t.Elements)
                                   .Include(t => t.Elements.Select(x => x.ElementDetails))
                                   .Where(t => (t.IsActive == true) && (t.IsFinalized == true))
                                   .ToList();

                    if (allTemplates.Count <= 0)
                    {
                        throw (new Exception("No templates found."));
                    }
                }

                // workerRoleParameters???

                // Download file from azure.
                Stream stream = null;
                List <OcrResultInfo> ocrresultinfos = new List <OcrResultInfo> ();

                if (WorkerRoleSimulation.GetTenantDocumentFileStream(tenant, document, out stream, out exception))
                {
                    Image documentImage = null;

                    using (var image = Image.FromStream(stream))
                    {
                        documentImage = (Image)image.Clone();
                        // LeadTools code.
                        // Stream and image available.
                    }

                    // TODO: Replace with Server.MapPath.
                    //LeadToolsOCR leadtoolsocr = new LeadToolsOCR (workerRoleParameters.OcrEngineSettings.GetPathData().FullName, tenant.Id.ToString (), string.Empty, out exception);
                    //if (exception != null) { throw exception; }

                    List <LeadtoolsBarcodeData> barcodedata = null;
                    bool foundbarcode = false;                     // leadtoolsocr.ReadBarcode (documentImage, out barcodedata, out exception);
                    //if (exception != null) { throw exception; }

                    if (foundbarcode)
                    {
                        //What to do if multiple barcodes are found.
                        int  templateid = 0;
                        bool foundId    = int.TryParse(barcodedata.First().Value, out templateid);
                        if (!(foundId) || templateid <= 0)
                        {
                        }                          //What to do if Form Id is Not Found by the barcode
                        Template template = allTemplates.Where(t => t.Id == ((long)templateid)).ToArray().FirstOrDefault();
                        if (template.TemplateType == TemplateType.Form)
                        {
                            double _computeddifference = 0.0;
                            if ((documentImage.Width <= documentImage.Height) && (!(documentImage.Height <= 0)))
                            {
                                _computeddifference = ((Convert.ToDouble(documentImage.Width)) / (Convert.ToDouble(documentImage.Height)));
                            }
                            else
                            {
                                if (!(documentImage.Width <= 0))
                                {
                                    _computeddifference = documentImage.Height / documentImage.Width;
                                }
                            }
                            var elements = allElements.Where(e => e.TemplateId == (long)templateid).ToList();
                            List <ComputeCoordinates> cordlistlist = new List <ComputeCoordinates> ();
                            //cordlistlist = leadtoolsocr.GetAllZoneData (elements, _computeddifference, documentImage);

                            //what to do with form matched results


                            //foreach (ComputeCoordinates cordata in cordlistlist)
                            //{
                            //    returnedresult += cordata.Text;
                            //}
                        }
                    }
                    else
                    {
                        result = AutoOCR(workerRoleParameters.OcrEngineSettings, tenant, documentImage, document, allTemplates, out ocrDocument, out ocrDocumentFragment, out ocrDocumentTemplate, out exception);
                        if (exception != null)
                        {
                            throw exception;
                        }
                    }

                    // Perform OCR and time-consuming tasks.
                }
                else
                {
                    throw (exception);
                }

                using (var context = new ContextTenant(tenant.DatabaseConnectionString))
                {
                    using (var transaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            if (ocrDocument != null)
                            {
                                context.Documents.Attach(ocrDocument);
                                context.Entry(ocrDocument).State = EntityState.Modified;
                                context.SaveChanges();
                            }
                            if (ocrDocumentFragment != null)
                            {
                                foreach (var documentfragment in ocrDocumentFragment)
                                {
                                    context.DocumentFragments.Add(documentfragment);
                                    context.SaveChanges();
                                }
                            }
                            if (ocrDocumentTemplate != null)
                            {
                                foreach (var documenttemplate in ocrDocumentTemplate)
                                {
                                    context.DocumentTemplate.Add(documenttemplate);
                                    context.SaveChanges();
                                }
                            }
                            //context.Templates.Attach(templates[0]);
                            context.SaveChanges();

                            // Do not call this line from anywhere else.
                            transaction.Commit();
                        }
                        catch (Exception e)
                        {
                            transaction.Rollback();
                        }
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                exception = e;
            }

            return(result);
        }