/////////////////////////////////////////////////////////////////////////////////
        // Register Contact / User
        /////////////////////////////////////////////////////////////////////////////////

        // GET: Register/Contact
        public async Task <ActionResult> Contact(Guid organizationId, Guid contactId)
        {
            GNOrganization organization = await organizationService.Find(organizationId);

            GNContact contact = await contactService.Find(contactId);

            if (contact != null && contact.IsInviteAccepted.HasValue && contact.IsInviteAccepted.Value)
            {
                return(RedirectToAction("ContactComplete", new { id = contact.Id }));
            }

            RegisterContactViewModel model = new RegisterContactViewModel
            {
                OrgId          = organization.Id,
                OrgName        = organization.Name,
                ContactId      = contact.Id,
                Email          = contact.Email,
                FirstName      = contact.FirstName,
                LastName       = contact.LastName,
                Title          = contact.Title,
                Phone          = contact.Phone,
                Fax            = contact.Fax,
                Website        = contact.Website,
                StreetAddress1 = contact.StreetAddress1,
                StreetAddress2 = contact.StreetAddress2,
                City           = contact.City,
                State          = contact.State,
                Zip            = contact.Zip,
            };

            return(View(model));
        }
Ejemplo n.º 2
0
        public ActionResult MyOrganization()
        {
            auditResult = audit.LogEvent(UserContact, UserContact.Id, this.ENTITY, this.Request.UserHostAddress, "VIEW_MY_ORGANIZATION");

            var            contact      = (GNContact)ViewBag.ContactForUser;
            GNOrganization organization = db.GNOrganizations.Find(contact.GNOrganizationId);

            if (organization == null)
            {
                return(HttpNotFound());
            }

            //eval CanInvite
            GNContact contactObj = new GNContact
            {
                GNOrganizationId = UserContact.GNOrganizationId
            };

            contactObj        = contactService.EvalEntitySecurity(UserContact, contactObj);
            ViewBag.CanInvite = contactObj.CanCreate;

            EvalCanViewContact();

            return(View(organization));
        }
        private async Task <GNOrganization> InsertNewOrganization(RegisterAccountViewModel model)
        {
            GNOrganization org = null;

            try
            {
                //insert new Org
                org = new GNOrganization
                {
                    Name = model.OrgName,
                    UTCOffsetDescription = model.UTCOffsetDescription,
                    AWSConfigId          = base.db.AWSConfigs.FirstOrDefault().Id,
                    CreateDateTime       = DateTime.Now,
                };
                org = await organizationService.Insert(org);
            }
            catch (Exception ex)
            {
                var ex2 = new Exception("Unable to add Organization.", ex);
                LogUtil.Error(logger, ex2.Message, ex2);
                throw ex2;
            }

            return(org);
        }
        public async Task <ActionResult> AccountComplete(Guid?id)
        {
            GNOrganization org = await organizationService.Find(id);

            ViewBag.userForMainOrgContact = this.identityDB.AspNetUsers.Find(org.OrgMainContact.AspNetUserId);

            return(View(org));
        }
        public void NotifyError(Sequencer sequencerMsg)
        {
            Guid           OrgId        = Guid.Parse("82ff6451-dac6-4a88-a967-cdaf5f9a3599");
            GNOrganization Organization = db.GNOrganizations.Find(OrgId);

            //NOTIFY USER
            bool notifyError =
                new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                    "SEQUENCER_JOB_ERROR",
                    "*****@*****.**",
                    "SequencerJobError",
                    new Dictionary <string, string>
            {
                { "Message", sequencerMsg.message },
                { "CreateDateTime", DateTime.Now.ToString() }
            });
        }
        public override async Task <ActionResult> Index()
        {
            EvalCanCreate();

            auditResult = audit.LogEvent(UserContact, Guid.Empty, this.ENTITY, this.Request.UserHostAddress, EVENT_LOAD_INDEX_UI);

            List <GNContact> contacts = null;

            GNTeam team = null;

            if (!string.IsNullOrEmpty(Request["teamId"]))
            {
                team         = entityService.db.GNTeams.Find(Guid.Parse(Request["teamId"]));
                ViewBag.Team = team;
            }

            GNOrganization org = null;

            if (!string.IsNullOrEmpty(Request["organizationId"]) || team != null)
            {
                if (team != null)
                {
                    org = team.Organization;
                }
                else
                {
                    org = entityService.db.GNOrganizations.Find(Guid.Parse(Request["organizationId"]));
                }

                ViewBag.Organization = org;

                contacts = await((ContactService)this.entityService).FindAllByOrg(UserContact, IndexStart(), IndexEnd(), IndexFilters(), org.Id);
            }
            else
            {
                contacts = await this.entityService.FindAll(UserContact, IndexStart(), IndexEnd(), IndexFilters());
            }

            return(View(contacts));
        }
        private async Task <GNAccount> InsertNewOrgAccount(GNOrganization org, GNContact mainOrgContact,
                                                           double maxBalanceAllowed = 0.0, bool validBillingAgreementRequired = true)
        {
            GNAccount acct = null;

            try
            {
                acct = new GNAccount
                {
                    Id                            = Guid.NewGuid(),
                    Organization                  = org,
                    GNAccountTypeId               = this.db.GNAccountTypes.Where(t => t.Name == "INDUSTRY").Select(t => t.Id).FirstOrDefault(),
                    AccountOwner                  = mainOrgContact,
                    BillingContact                = mainOrgContact,
                    MailingContact                = mainOrgContact,
                    CreateDateTime                = DateTime.Now,
                    CreatedBy                     = mainOrgContact.Id,
                    DefaultDiscountAmount         = 0.0,
                    DefaultDiscountType           = GNAccount.DiscountType.FLAT.GetCode(),
                    BillingMode                   = GNAccount.BillingModeType.INVOICE.GetCode(),
                    TotalAmountOwed               = 0,
                    TotalAmountPaid               = 0,
                    MaxBalanceAllowed             = maxBalanceAllowed,
                    ValidBillingAgreementRequired = validBillingAgreementRequired
                };

                acct = this.db.GNAccounts.Add(acct);
                int result = await this.db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                var ex2 = new Exception("Unable to add Account for Organization.", ex);
                LogUtil.Error(logger, ex2.Message, ex2);
                throw ex2;
            }

            return(acct);
        }
        private async Task <GNContact> InsertMainOrgContact(RegisterAccountViewModel model, AspNetUser aspNetUser, GNOrganization org)
        {
            GNContact mainOrgContact = null;

            try
            {
                //find ORG_MANAGER role
                AspNetRole aspNetRole = base.identityDB.AspNetRoles.Where(r => r.Name == "ORG_MANAGER").FirstOrDefault();

                //insert Main Org Contact with ORG_MANAGER role
                mainOrgContact = new GNContact
                {
                    AspNetUserId                = aspNetUser.Id,
                    Email                       = model.Email,
                    FirstName                   = model.FirstName,
                    LastName                    = model.LastName,
                    Title                       = model.Title,
                    Phone                       = model.Phone,
                    Fax                         = model.Fax,
                    Website                     = model.Website,
                    StreetAddress1              = model.StreetAddress1,
                    StreetAddress2              = model.StreetAddress2,
                    City                        = model.City,
                    State                       = model.State,
                    Zip                         = model.Zip,
                    TermsAcceptDateTime         = DateTime.Now,
                    PrivacyPolicyAcceptDateTime = DateTime.Now,
                    CreateDateTime              = DateTime.Now,
                    GNOrganizationId            = org.Id,
                    IsSubscribedForNewsletters  = model.SignUpForNewsAndProducts
                };
                mainOrgContact = await contactService.Insert(mainOrgContact);

                //Update Org
                org.GNContactId = mainOrgContact.Id;
                org.CreatedBy   = mainOrgContact.Id;
                org             = await organizationService.Update(org);

                if (org != null)
                {
                    mainOrgContact.CreatedBy        = mainOrgContact.Id;
                    mainOrgContact.GNOrganizationId = org.Id;
                    mainOrgContact.GNContactRoles   = new List <GNContactRole>();
                    mainOrgContact.GNContactRoles.Add(new GNContactRole
                    {
                        AspNetRoleId   = aspNetRole.Id,
                        CreatedBy      = mainOrgContact.Id,
                        CreateDateTime = DateTime.Now
                    });

                    mainOrgContact = await contactService.Update(org.OrgMainContact);
                }
            }
            catch (Exception ex)
            {
                var ex2 = new Exception("Unable to add Main Organization Contact.", ex);
                LogUtil.Error(logger, ex2.Message, ex2);
                throw ex2;
            }

            return(mainOrgContact);
        }
        public async Task <ActionResult> AccountSubmit(RegisterAccountViewModel model)
        {
            if (ModelState.IsValid)
            {
                GNInviteCode inviteCodeRedemption = null;

                try
                {
                    //redeem invite code
                    inviteCodeRedemption = inviteCodeService.RedeemInviteCode(model.InviteCode);

                    if (inviteCodeRedemption != null)
                    {
                        //Auth or Create User
                        AspNetUser aspNetUser = await AuthCreateUser(model.Email, model.Password, model.IsExistingUser,
                                                                     verifyEmail : true, signUpForNews : model.SignUpForNewsAndProducts, organizationId : null);

                        if (ModelState.IsValid && aspNetUser != null)
                        {
                            //Insert New Org
                            GNOrganization org = await InsertNewOrganization(model);

                            if (org != null)
                            {
                                //Insert Main Org Contact
                                GNContact mainOrgContact = await InsertMainOrgContact(model, aspNetUser, org);

                                if (mainOrgContact != null)
                                {
                                    double maxBalanceAllowed             = 0.0;
                                    bool   validBillingAgreementRequired = false;

                                    //set free credit allowance based on invite code redemption
                                    if (inviteCodeRedemption.FreeCreditAllowance > 0.0)
                                    {
                                        maxBalanceAllowed = inviteCodeRedemption.FreeCreditAllowance;
                                    }

                                    GNAccount orgAccount =
                                        await InsertNewOrgAccount(org, mainOrgContact, maxBalanceAllowed, validBillingAgreementRequired);



                                    if (inviteCodeRedemption.InviteCode.Equals("GENandGEN2015"))
                                    {
                                        org.GNSettingsTemplate = db.GNSettingsTemplates.Where(a => a.Name == "GN_GENOMICS2015").FirstOrDefault();
                                        db.SaveChanges();
                                    }



                                    if (orgAccount != null)
                                    {
                                        if (model.IsExistingUser)
                                        {
                                            //send notification
                                            bool notifySuccess =
                                                new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                                                    "ORG_ACCOUNT_REGISTRATION_COMPLETE",
                                                    mainOrgContact.Email,
                                                    "Account:" + mainOrgContact.Id.ToString(),
                                                    new Dictionary <string, string>
                                            {
                                                { "OrganizationName", orgAccount.Organization.Name },
                                                { "FirstName", mainOrgContact.FirstName },
                                                { "LastName", mainOrgContact.LastName }
                                            });
                                        }

                                        return(RedirectToAction("AccountComplete", new { id = org.Id }));
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("InviteCode", "Unable to redeem Invite Code.");
                    }
                }
                catch (Exception ex)
                {
                    LogUtil.Error(logger, "Unable to perform Account Registration", ex);
                    ModelState.AddModelError("", "Unable to perform Account Registration");
                }

                if (inviteCodeRedemption != null)
                {
                    inviteCodeService.UnRedeemInviteCode(model.InviteCode);
                }
            }

            return(View(model));
        }
Ejemplo n.º 10
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(GNIdentityDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // JLS: Ensure that, by default, the system will authenticate requests with our configured CookieAuthentication.
            app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ApplicationCookie);


            //JLS: ***********************************************

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
            {
                AuthenticationType = "Sanford",
                Wtrealm            = ConfigurationManager.AppSettings["Sanford:Wtrealm"],
                MetadataAddress    = ConfigurationManager.AppSettings["Sanford:Metadata"],
                Notifications      = new WsFederationAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        //JLS: ToDo: Replace this target of this redirect with the appropriate URL for the GenomeNext application.
                        context.Response.Redirect("Home/Error?message=" + context.Exception.Message);
                        return(Task.FromResult(-1));
                    },
                    //SecurityTokenReceived
                    SecurityTokenValidated = context =>
                    {
                        var userEmail = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Email).Value;

                        var identityDB = new IdentityModelContainer();
                        var db         = new GNEntityModelContainer();
                        GNContact contact;

                        AspNetUser user = identityDB.AspNetUsers.Where(a => a.Email.ToLower().Equals(userEmail.ToLower())).FirstOrDefault();
                        if (user != null)
                        {
                            //exists
                            contact = db.GNContacts.Where(a => a.User.Id.Equals(user.Id) && a.IsInviteAccepted == true).FirstOrDefault();
                        }
                        else
                        {
                            //create new
                            String ssoEmail             = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Email).Value;
                            GNOrganization organization = db.GNOrganizations.Where(a => a.Name.Contains("Sanford")).FirstOrDefault();
                            AspNetUser newUser          = new AspNetUser
                            {
                                Id             = Guid.NewGuid().ToString(),
                                Email          = ssoEmail,
                                IsAdmin        = false,
                                Password       = "******",
                                UserName       = ssoEmail,
                                EmailConfirmed = true
                            };
                            identityDB.AspNetUsers.Add(newUser);

                            contact = new GNContact
                            {
                                Id             = Guid.NewGuid(),
                                AspNetUserId   = newUser.Id,
                                CreateDateTime = DateTime.Now,
                                Email          = ssoEmail,
                                FirstName      = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.GivenName).Value
                            };

                            db.GNContacts.Add(contact);
                            identityDB.SaveChanges();
                            db.SaveChanges();
                        }


                        var applicationUserIdentity = new ClaimsIdentity();
                        applicationUserIdentity.AddClaim(new Claim(ClaimTypes.Name, contact.FullName, ""));
                        applicationUserIdentity.AddClaim(new Claim(ClaimTypes.Email, user.Email, ""));
                        context.OwinContext.Authentication.User.AddIdentity(applicationUserIdentity);

                        context.Response.Redirect("Home");
                        return(Task.FromResult(0));
                    }
                }
            }
                );
            //JLS: ***********************************************


            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                ExpireTimeSpan     = TimeSpan.FromMinutes(30),
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
        }
        public override bool ProcessMessage(Sequencer sequencerMsg, object queueMessage)
        {
            System.Console.WriteLine("***\n ****** bucket Name: " + sequencerMsg.bucket);
            System.Console.WriteLine("***\n ****** project name: " + sequencerMsg.project_name);
            bool success = false;

            try
            {
                System.Console.WriteLine("***\n  Searching for Org " + sequencerMsg.bucket);
                GNOrganization organization = db.GNOrganizations.Where(a => a.Repository.Equals(sequencerMsg.bucket)).FirstOrDefault();
                System.Console.WriteLine("***\n ****** organization: " + organization.Name);

                if (organization == null)
                {
                    System.Console.WriteLine("***\n  NO ORG FOUND!!!!");
                    return(success);
                }

                System.Console.WriteLine("***\n  organization: " + organization.Id);
                if (sequencerMsg.bucket.Equals("ERROR") && sequencerMsg.project_name.Equals("UNDEFINED"))
                {
                    this.NotifyError(sequencerMsg);
                    return(true);
                }


                //check if a project is already undergoing for the same Org and same name (repeated message)
                int seqJobsRunning = db.GNSequencerJobs.Where(a => a.GNOrganizationId.Equals(organization.Id) && a.Project.Equals(sequencerMsg.project_name.Trim())).Count();
                //if none exists, create
                if (seqJobsRunning == 0)
                {
                    string datetimeString = DateTime.Now.ToString("MM-dd 0:HH:mm:ss");

                    /**
                     * 1. Create a Team
                     * 2. Create a Project
                     */
                    GNContact contact = db.GNContacts.Find(organization.GNContactId);

                    GNTeam newTeam = new GNTeam
                    {
                        Id             = Guid.NewGuid(),
                        CreateDateTime = DateTime.Now,
                        CreatedBy      = organization.GNContactId,
                        Name           = "Batch " + datetimeString,
                        GNContactId    = contact.Id,
                        Organization   = organization,
                        OrganizationId = organization.Id,
                        TeamLead       = contact
                    };

                    System.Console.WriteLine("***\n  New newTeam Created: " + newTeam.Id);

                    Guid newProjectId = Guid.NewGuid();

                    System.Console.WriteLine("*********************************\n  Contact for project: " + contact.FullName);
                    System.Console.WriteLine("*********************************\n  Contact for project: " + newProjectId);

                    GNProject newProject = new GNProject
                    {
                        Id             = newProjectId,
                        CreateDateTime = DateTime.Now,
                        CreatedBy      = organization.GNContactId,
                        ProjectLead    = contact,
                        ProjectLeadId  = contact.Id.ToString(),
                        Name           = sequencerMsg.project_name, //name assigned to the project
                        TeamId         = newTeam.Id.ToString(),
                        StartDate      = DateTime.Now,
                        EndDate        = DateTime.Now.AddDays(30),
                        Description    = "Created automatically from the Sample Batch Process"
                    };

                    newTeam.Projects.Add(newProject);
                    newProject.Teams.Add(newTeam);
                    db.GNTeams.Add(newTeam);
                    db.GNProjects.Add(newProject);

                    System.Console.WriteLine("*********************************\n  Contact for project: " + newProjectId);
                    GNSequencerJob sequencerJob = new GNSequencerJob
                    {
                        Id               = Guid.NewGuid(),
                        CreateDateTime   = DateTime.Now,
                        Project          = sequencerMsg.project_name,
                        Status           = "STARTED",
                        GNOrganization   = organization,
                        GNOrganizationId = organization.Id,
                        GNProject        = newProject
                    };

                    db.GNSequencerJobs.Add(sequencerJob);
                    System.Console.WriteLine("***\n  New sequencerJob Created: " + sequencerJob.Id);

                    try
                    {
                        db.SaveChanges();
                        //NOTIFY USER
                        bool notifySuccess =
                            new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                                "SEQUENCER_JOB_STARTED",
                                "*****@*****.**",
                                "SequencerJob:" + sequencerJob.Id.ToString(),
                                new Dictionary <string, string>
                        {
                            { "JobId", sequencerJob.Id.ToString() },
                            { "ProjectName", sequencerJob.Project },
                            { "CreateDateTime", DateTime.Now.ToString() }
                        });
                        success = true;
                    }
                    catch (Exception eRDS)
                    {
                        System.Console.WriteLine("***\n  EXCEPCION!!! " + eRDS.Message + eRDS.StackTrace + eRDS.InnerException);

                        success = false;
                    }
                }
            }
            catch (Exception e1)
            {
                Exception e2 = new Exception("Unable to process Sequencer Job Message.", e1);
                System.Console.WriteLine("***\n  EXCEPCION!!! " + e1.Message + e1.StackTrace);
                LogUtil.Warn(logger, e2.Message, e2);
                success = false;
            }
            return(success);
        }
Ejemplo n.º 12
0
        public override bool ProcessMessage(NewSampleBatch newSampleMessage, object queueMessage)
        {
            System.Console.WriteLine("***\n ****** Batch Id: " + newSampleMessage.batchId);
            System.Console.WriteLine("***\n ****** Sample type: " + newSampleMessage.type);
            System.Console.WriteLine("***\n ****** Sample repository: " + newSampleMessage.repository);

            SampleResponseService sampleResponseService = new SampleResponseService();

            List <GNSample> listOfSamples = new List <GNSample>();
            List <GNNewSampleBatchSamples> listOfBatchSamples = new List <GNNewSampleBatchSamples>();
            List <String> listOfAnalysisNames = new List <String>();

            GNOrganization Organization = db.GNOrganizations.Where(a => a.Repository.Equals(newSampleMessage.repository)).FirstOrDefault();

            System.Console.WriteLine("***\n  Organization " + Organization.Name);
            System.Console.WriteLine("***\n  Organization Id " + Organization.Id);
            System.Console.WriteLine("***\n  Project " + newSampleMessage.project);


            bool success = false;

            try
            {
                System.Console.WriteLine("***\n  Searching sequencerJob ");

                //Find sequencer job
                GNSequencerJob sequencerJob = db.GNSequencerJobs.Where(a => a.GNOrganizationId.Equals(Organization.Id) && a.Project.Equals(newSampleMessage.project)).FirstOrDefault();
                if (sequencerJob == null)
                {
                    throw new Exception("Unable to find Sequencer Job!");
                }

                sequencerJob.Status = "PROCESSING SAMPLES";

                System.Console.WriteLine("***\n  Starting.  sequencerJob project: " + sequencerJob.Project);

                GNProject newProject = sequencerJob.GNProject;
                GNTeam    newTeam    = newProject.Teams.FirstOrDefault();

                GNNewSampleBatch newSampleBatch = new GNNewSampleBatch
                {
                    Id                      = Guid.NewGuid(),
                    BatchId                 = newSampleMessage.batchId,
                    GNSequencerJobId        = sequencerJob.Id,
                    GNSequencerJob          = sequencerJob,
                    Project                 = newSampleMessage.project,
                    AutoStartAnalysis       = (newSampleMessage.autoStartAnalysis.ToLower().Equals("true")),
                    CreateAnalysisPerSample = (newSampleMessage.createAnalysisPerSample.ToLower().Equals("true")),
                    Qualifier               = newSampleMessage.qualifier,
                    Type                    = newSampleMessage.type,
                    Repository              = newSampleMessage.repository,
                    ReadType                = newSampleMessage.read,
                    TotalSamples            = newSampleMessage.samples.Count(),
                    TotalSamplesCompleted   = 0,
                    TotalNumberOfFastqFiles = 0,
                    CreateDateTime          = DateTime.Now
                };

                db.GNNewSampleBatches.Add(newSampleBatch);

                GNSampleType type = db.GNSampleTypes.Where(a => a.Name.Equals(newSampleMessage.type.ToUpper())).FirstOrDefault();
                System.Console.WriteLine("***\n  type " + type.Name);

                string datetimeString = DateTime.Now.ToString("MM-dd 0:HH:mm:ss");

                GNAnalysisType analysisType = null;
                String         AnalysisCode = newSampleMessage.qualifier;
                if (newSampleBatch.CreateAnalysisPerSample)
                {
                    /**
                     * 1. Create a Team
                     * 2. Create a Project
                     */
                    GNContact contact = db.GNContacts.Find(Organization.GNContactId);

                    if (newSampleMessage.qualifier.Equals("TUMOR"))
                    {
                        AnalysisCode = "TUMORNORMAL";
                    }
                    analysisType = db.GNAnalysisTypes.Where(a => a.Name.Equals(newSampleMessage.type.ToUpper())).FirstOrDefault();
                }

                int i = 0;
                GNAnalysisRequest newAnalysis = null;

                /**
                 * Loop samples
                 */

                GNNewSampleBatchStatus batchStatus = new GNNewSampleBatchStatus
                {
                    Id                 = Guid.NewGuid(),
                    CreateDateTime     = DateTime.Now,
                    GNNewSampleBatch   = newSampleBatch,
                    GNNewSampleBatchId = newSampleBatch.Id,
                    IsError            = false,
                    PercentComplete    = 0,
                    Status             = "STARTING PROCESS",
                    Repository         = newSampleMessage.repository
                };
                db.GNNewSampleBatchStatus.Add(batchStatus);
                System.Console.WriteLine("***\n  New batchStatus Created: " + batchStatus.Id);

                foreach (SampleBatch sampleBatch in newSampleMessage.samples)
                {
                    String newSampleName = sampleBatch.name;
                    //tfrege 2016.12.07 do not append family id to sample name anymore

                    /*
                     * if(sampleBatch.familyId != "")
                     * {
                     *  newSampleName = newSampleName + " (" + sampleBatch.familyId + ")";
                     *  System.Console.WriteLine("***\n ------------->  newSampleName: " + newSampleName);
                     * }
                     */

                    GNSample sampleExist     = db.GNSamples.Where(a => a.Name.Equals(sampleBatch.name) && a.GNOrganizationId.Equals(Organization.Id)).FirstOrDefault();
                    bool     createNewSample = false;


                    //Since BCL2FASTQ is not passing gender for now, figure it out based on the family relation
                    String sampleBatchgender = "U";
                    switch (sampleBatch.familyRelation)
                    {
                    case "F":
                    case "S":
                        sampleBatchgender = "M";
                        break;

                    case "M":
                    case "D":
                        sampleBatchgender = "F";
                        break;

                    default:
                        sampleBatchgender = "F";
                        break;
                    }

                    if (sampleExist != null)
                    {
                        if (sampleExist.IsReady)
                        {
                            //the sample is ready, let's create a new one with a suffix of (1)
                            newSampleName   = sampleBatch.name + " (1)";
                            createNewSample = true;
                        }
                        else
                        {
                            //the sample is in the middle of being created, so ignore the message
                            createNewSample = false;
                            //tfrege remove this control just for testing purposes, create new sample always
                            newSampleName   = sampleBatch.name + " (1)"; //remove this after validation is put back in
                            createNewSample = true;
                        }
                    }
                    else
                    {
                        createNewSample = true;
                    }

                    try
                    {
                        if (createNewSample)
                        {
                            GNReplicate replicate = db.GNReplicates.Where(a => a.Name.Equals("NO")).FirstOrDefault();

                            GNSample newSample = new GNSample
                            {
                                Id = Guid.NewGuid(),
                                GNOrganizationId      = Organization.Id,
                                Name                  = newSampleName,
                                Gender                = sampleBatchgender,
                                GNSampleTypeId        = type.Id,
                                GNSampleQualifierCode = newSampleMessage.qualifier,
                                IsReady               = false,
                                IsPairEnded           = (newSampleMessage.read == "paired-end"),
                                GNReplicateCode       = "0",
                                GNReplicate           = replicate,
                                CreateDateTime        = DateTime.Now,
                                CreatedBy             = CreatedBy
                            };

                            db.GNSamples.Add(newSample);
                            System.Console.WriteLine("***\n  New Sample Created: " + newSample.Id);


                            string analysisName = sampleBatch.name;
                            if (sampleBatch.familyId != null)
                            {
                                analysisName = sampleBatch.familyId;
                            }

                            GNNewSampleBatchSamples batchSample = new GNNewSampleBatchSamples {
                                Id                 = Guid.NewGuid(),
                                GNSample           = newSample,
                                CreateDateTime     = DateTime.Now,
                                GNNewSampleBatch   = newSampleBatch,
                                GNNewSampleBatchId = newSampleBatch.Id,
                                Name               = sampleBatch.name,
                                Affected           = sampleBatch.affected,
                                Proband            = sampleBatch.proband,
                                FamilyId           = sampleBatch.familyId,
                                RelationId         = sampleBatch.familyRelation,
                                Gender             = sampleBatchgender,
                                AnalysisName       = analysisName
                            };
                            db.GNNewSampleBatchSamples.Add(batchSample);
                            System.Console.WriteLine("***\n  New batchSample Created: " + batchSample.Id);
                            System.Console.WriteLine("***\n  ====>>>>> Adding to listOfAnalysisNames: " + analysisName);

                            if (!listOfAnalysisNames.Contains(analysisName))
                            {
                                listOfAnalysisNames.Add(analysisName);
                            }

                            db.SaveChanges();
                            System.Console.WriteLine("***\n  DB CHANGES SAVED.");

                            System.Console.WriteLine("***\n  Sample Name: " + sampleBatch.name);

                            //Build list to notify the BCL2FASTQ service later
                            listOfSamples.Add(newSample);
                            listOfBatchSamples.Add(batchSample);
                        }
                    }
                    catch (Exception e1)
                    {
                        System.Console.WriteLine("***\n  Exception: " + e1.Message + e1.StackTrace + e1.InnerException);
                    }
                    i++;
                }

                /**
                 * Update pedigrees, if applies
                 */
                int maxPedigreeId = db.GNSampleRelationships.Max(a => a.Id);
                System.Console.WriteLine("***\n  Updating pedigrees for families ");

                foreach (GNNewSampleBatchSamples pedigreeSample in listOfBatchSamples.Where(a => a.Gender != "U" && a.RelationId != ""))
                {
                    switch (pedigreeSample.RelationId)
                    {
                    case "F":
                    case "M":
                    {
                        GNSampleRelationshipType relationshipType = db.GNSampleRelationshipTypes.Where(a => a.Name.Equals("SON")).FirstOrDefault();

                        //find sons and daughters
                        List <GNNewSampleBatchSamples> sons = listOfBatchSamples.Where(a => a.FamilyId.Equals(pedigreeSample.FamilyId) && a.RelationId.Equals("S")).ToList();
                        foreach (GNNewSampleBatchSamples son in sons)
                        {
                            GNSampleRelationship sampleRelationship = new GNSampleRelationship
                            {
                                Id                         = maxPedigreeId++,
                                GNLeftSample               = pedigreeSample.GNSample,
                                GNLeftSampleId             = pedigreeSample.GNSample.Id,
                                GNRightSample              = son.GNSample,
                                GNRightSampleId            = son.GNSample.Id,
                                GNSampleRelationshipType   = relationshipType,
                                GNSampleRelationshipTypeId = relationshipType.Id,
                                CreateDateTime             = DateTime.Now,
                                CreatedBy                  = CreatedBy
                            };
                            db.GNSampleRelationships.Add(sampleRelationship);
                            System.Console.WriteLine("***\n  Added Son " + son.GNSample.Id + " to Parent Sample : " + pedigreeSample.GNSample.Id);
                        }

                        relationshipType = db.GNSampleRelationshipTypes.Where(a => a.Name.Equals("DAUGHTER")).FirstOrDefault();

                        //find sons and daughters
                        List <GNNewSampleBatchSamples> daughters = listOfBatchSamples.Where(a => a.FamilyId.Equals(pedigreeSample.FamilyId) && a.RelationId.Equals("D")).ToList();
                        foreach (GNNewSampleBatchSamples daughter in daughters)
                        {
                            GNSampleRelationship sampleRelationship = new GNSampleRelationship
                            {
                                Id                         = maxPedigreeId++,
                                GNLeftSample               = pedigreeSample.GNSample,
                                GNLeftSampleId             = pedigreeSample.GNSample.Id,
                                GNRightSample              = daughter.GNSample,
                                GNRightSampleId            = daughter.GNSample.Id,
                                GNSampleRelationshipType   = relationshipType,
                                GNSampleRelationshipTypeId = relationshipType.Id,
                                CreateDateTime             = DateTime.Now,
                                CreatedBy                  = CreatedBy
                            };
                            db.GNSampleRelationships.Add(sampleRelationship);
                            System.Console.WriteLine("***\n  Added Daughter " + daughter.GNSample.Id + " to Parent Sample : " + pedigreeSample.GNSample.Id);
                        }
                    } break;

                    case "S":
                    case "D":
                    {
                        GNSampleRelationshipType relationshipType = db.GNSampleRelationshipTypes.Where(a => a.Name.Equals("FATHER")).FirstOrDefault();

                        //find sons and daughters
                        List <GNNewSampleBatchSamples> fathers = listOfBatchSamples.Where(a => a.FamilyId.Equals(pedigreeSample.FamilyId) && a.RelationId.Equals("F")).ToList();
                        foreach (GNNewSampleBatchSamples dad in fathers)
                        {
                            GNSampleRelationship sampleRelationship = new GNSampleRelationship
                            {
                                Id                         = maxPedigreeId++,
                                GNLeftSample               = pedigreeSample.GNSample,
                                GNLeftSampleId             = pedigreeSample.GNSample.Id,
                                GNRightSample              = dad.GNSample,
                                GNRightSampleId            = dad.GNSample.Id,
                                GNSampleRelationshipType   = relationshipType,
                                GNSampleRelationshipTypeId = relationshipType.Id,
                                CreateDateTime             = DateTime.Now,
                                CreatedBy                  = CreatedBy
                            };
                            db.GNSampleRelationships.Add(sampleRelationship);
                            System.Console.WriteLine("***\n  Added Dad " + dad.GNSample.Id + " to Child Sample : " + pedigreeSample.GNSample.Id);
                        }

                        relationshipType = db.GNSampleRelationshipTypes.Where(a => a.Name.Equals("MOTHER")).FirstOrDefault();

                        //find sons and daughters
                        List <GNNewSampleBatchSamples> mothers = listOfBatchSamples.Where(a => a.FamilyId.Equals(pedigreeSample.FamilyId) && a.RelationId.Equals("M")).ToList();
                        foreach (GNNewSampleBatchSamples mom in mothers)
                        {
                            GNSampleRelationship sampleRelationship = new GNSampleRelationship
                            {
                                Id                         = maxPedigreeId++,
                                GNLeftSample               = pedigreeSample.GNSample,
                                GNLeftSampleId             = pedigreeSample.GNSample.Id,
                                GNRightSample              = mom.GNSample,
                                GNRightSampleId            = mom.GNSample.Id,
                                GNSampleRelationshipType   = relationshipType,
                                GNSampleRelationshipTypeId = relationshipType.Id,
                                CreateDateTime             = DateTime.Now,
                                CreatedBy                  = CreatedBy
                            };
                            db.GNSampleRelationships.Add(sampleRelationship);
                            System.Console.WriteLine("***\n  Added Mom " + mom.GNSample.Id + " to Child Sample : " + pedigreeSample.GNSample.Id);
                        }
                    } break;

                    case "U":
                    default:
                        //don't do a thing.
                        System.Console.WriteLine("***\n  Relation is undefined, do not add anything.");
                        break;
                    }
                }

                /******************************************************************************************************/
                //SAVE ALL CHANGES (new team, new project, new samples, new analyses, new batch records, new pedigrees)
                /******************************************************************************************************/

                try
                {
                    db.SaveChanges();
                }
                catch (Exception eRDS)
                {
                    System.Console.WriteLine("***EXCEPTION DB!!! " + eRDS.Message + " " + eRDS.StackTrace + " " + eRDS.InnerException);
                }


                try
                {
                    if (newSampleMessage.autoStartAnalysis.ToLower().Equals("true"))
                    {
                        System.Console.WriteLine("***\n  Elements: " + listOfAnalysisNames.Count());

                        foreach (String anName in listOfAnalysisNames)
                        {
                            List <GNNewSampleBatchSamples> samplesForAnalysis = new List <GNNewSampleBatchSamples>();

                            newAnalysis = new GNAnalysisRequest
                            {
                                Id                        = Guid.NewGuid(),
                                Project                   = newProject,
                                GNProjectId               = newProject.Id,
                                CreateDateTime            = DateTime.Now,
                                CreatedBy                 = CreatedBy,
                                AnalysisType              = analysisType,
                                RequestProgress           = 0,
                                RequestDateTime           = DateTime.Now,
                                GNAnalysisRequestTypeCode = AnalysisCode,
                                Description               = anName,
                                GNAnalysisAdaptorCode     = "NONE",
                                AnalysisTypeId            = analysisType.Id.ToString(),
                                AutoStart                 = (newSampleMessage.autoStartAnalysis.ToLower().Equals("true")),
                                AWSRegionSystemName       = db.AWSRegions.FirstOrDefault().AWSRegionSystemName
                            };
                            db.GNAnalysisRequests.Add(newAnalysis);
                            System.Console.WriteLine("***\n  ========================\n New newAnalysis Created: " + newAnalysis.Id);

                            samplesForAnalysis = db.GNNewSampleBatchSamples.Where(a => a.GNNewSampleBatchId.Equals(newSampleBatch.Id) && a.AnalysisName.Equals(anName)).ToList();
                            foreach (GNNewSampleBatchSamples sample in samplesForAnalysis)
                            {
                                GNAnalysisRequestGNSample newAnalysisSample = new GNAnalysisRequestGNSample
                                {
                                    AffectedIndicator   = sample.Affected,
                                    TargetIndicator     = sample.Proband,
                                    GNAnalysisRequest   = newAnalysis,
                                    GNSample            = sample.GNSample,
                                    GNAnalysisRequestId = newAnalysis.Id,
                                    GNSampleId          = sample.GNSample.Id
                                };
                                db.GNAnalysisRequestGNSamples.Add(newAnalysisSample);
                                System.Console.WriteLine("***\n  Sample Added to New newAnalysis: " + sample.GNSample.Name);
                            }
                        }
                    } //end of "if(newSampleBatch.CreateAnalysisPerSample)"
                }
                catch (Exception eAnalysis)
                {
                    System.Console.WriteLine("***\n  Exception: " + eAnalysis.Message + eAnalysis.StackTrace + eAnalysis.InnerException);
                }


                db.SaveChanges();

                //Notify BCL2FASTQ service
                sampleResponseService.NotifyBcl2FastqSystem(listOfBatchSamples);

                System.Console.WriteLine("***\n  EVERYTHING WORKED!");

                //NOTIFY USER
                bool notifySuccess =
                    new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                        "SAMPLE_CREATION",
                        Organization.OrgMainContact.Email,
                        "Sample Creation",
                        new Dictionary <string, string>
                {
                    { "BatchId", newSampleMessage.batchId },
                    { "TotalSamples", newSampleBatch.TotalSamples.ToString() },
                    { "CreatorName", Organization.OrgMainContact.FullName },
                    { "JobId", sequencerJob.Id.ToString() },
                    { "ProjectName", sequencerJob.Project },
                    { "CreateDateTime", DateTime.Now.ToString() }
                });
                success = true;
            }
            catch (Exception e1)
            {
                Exception e2 = new Exception("Unable to Create New Sample.", e1);
                LogUtil.Warn(logger, e2.Message, e2);
                success = false;
            }
            return(success);
        }
        public override bool ProcessMessage(NewSampleBatchStatus newSampleMessageStatus, object queueMessage)
        {
            System.Console.WriteLine("***\n newSampleMessageStatus Batch Name: " + newSampleMessageStatus.batchId);

            if (newSampleMessageStatus.batchId.Equals("NO_SAMPLE_FOUND"))
            {
                //processSpecialCases();
            }

            if (newSampleMessageStatus.status.Equals("QC-COMPLETED"))
            {
                // ProcessQCMessage(newSampleMessageStatus);
                return(true);
            }

            bool success = false;

            try
            {
                GNOrganization   Organization = db.GNOrganizations.Where(a => a.Repository.Equals(newSampleMessageStatus.repositoryId)).FirstOrDefault();
                GNNewSampleBatch Batch        = db.GNNewSampleBatches.Where(a => a.BatchId.Equals(newSampleMessageStatus.batchId)).FirstOrDefault();

                bool isError = false;
                if (newSampleMessageStatus.isError.Equals("true"))
                {
                    isError = true;
                }


                GNNewSampleBatchStatus batchStatus = new GNNewSampleBatchStatus
                {
                    Id                 = Guid.NewGuid(),
                    CreateDateTime     = DateTime.Now,
                    GNNewSampleBatch   = Batch,
                    GNNewSampleBatchId = Batch.Id,
                    IsError            = isError,
                    PercentComplete    = newSampleMessageStatus.percentComplete,
                    Status             = newSampleMessageStatus.status,
                    RepositoryId       = newSampleMessageStatus.repositoryId,
                    FilesBucket        = newSampleMessageStatus.filesBucket,
                    Message            = newSampleMessageStatus.message
                };
                db.GNNewSampleBatchStatus.Add(batchStatus);
                db.SaveChanges();


                /*
                 * var tx = db.Database.BeginTransaction();
                 *
                 * string insertSQL =
                 *  "INSERT INTO [gn].[GNSampleStatus]" +
                 *  "([Id],[GNSampleId],[SampleName],[Repository],[Message],[PercentComplete],[IsError],[CreatedBy],[CreateDateTime])" +
                 *  "VALUES " +
                 *  "(@Id, @GNSampleId, @SampleName, @Repository, @Message, @PercentComplete, @IsError, @CreatedBy, @CreateDateTime)";
                 *
                 * db.Database.ExecuteSqlCommand(
                 *  insertSQL,
                 *  new SqlParameter("@Id", Guid.NewGuid()),
                 *  new SqlParameter("@GNSampleId", sample.Id),
                 *  new SqlParameter("@SampleName", newSampleMessageStatus.name),
                 *  new SqlParameter("@Repository", newSampleMessageStatus.repositoryId),
                 *  new SqlParameter("@Message", newSampleMessageStatus.message),
                 *  new SqlParameter("@PercentComplete", newSampleMessageStatus.percentComplete),
                 *  new SqlParameter("@IsError", isError),
                 *  new SqlParameter("@CreatedBy", Guid.Parse("0750f896-e7d6-48d4-a1b9-007059f62784")),
                 *  new SqlParameter("@CreateDateTime", DateTime.Now));
                 *
                 * LogUtil.Warn(logger, insertSQL);
                 * tx.Commit();
                 */



                if (newSampleMessageStatus.filesBucket != null && newSampleMessageStatus.filesBucket != "")
                {
                    System.Console.WriteLine("&&&&& \n Will copy files &&&&&&& ");

                    try
                    {
                        /*
                         * IQueryable<GNSample> listOfSamples = db.GNSamples.Where(a => a.GNNewSampleBatchSample.GNNewSampleBatchId.Equals(Batch.Id));
                         *
                         * GNCloudStorageService st = new GNCloudStorageService();
                         * string originBucket = newSampleMessageStatus.filesBucket;
                         * originBucket = "tfrege-test-20140711"; //testing purposes
                         * Dictionary<String, long> listOfFiles = st.ListingObjects(originBucket);
                         *
                         * string s3BucketName = st.FetchAWSS3Bucket().ARN;
                         *
                         * /*
                         * //string volume = newSampleMessageStatus.filesBucket.Substring(newSampleMessageStatus.filesBucket.IndexOf("/")+1, )
                         * string folderPath1 = newSampleMessageStatus.filesBucket.Replace("http://", "");
                         * folderPath1 = folderPath1.Replace("https://", "");
                         * int idxSlash = folderPath1.IndexOf("/");
                         * int strLen = folderPath1.Length;
                         *
                         * //string volume = folderPath1.Substring(0, idxSlash);
                         * //string folderPath = folderPath1.Substring(idxSlash + 1, strLen - idxSlash - 1);
                         * GNCloudFileCategory fileCategory = db.GNCloudFileCategories.Where(a => a.Id == 1).FirstOrDefault();
                         *
                         *
                         * string volume = s3BucketName;
                         *
                         * foreach (GNSample sample in listOfSamples)
                         * {
                         *  Guid fileId = Guid.NewGuid();
                         *
                         *  //Create new folder in S3
                         *  st.PutObjectOnBucket(s3BucketName + "fastq/", sample.Id.ToString(), sample.Id.ToString());
                         *  st.PutObjectOnBucket(s3BucketName + "fastq/", sample.Id.ToString() + "/" + fileId.ToString(), sample.Id.ToString() + "/" + fileId.ToString());
                         *
                         *  string folderPath = "fastq/" + sample.Id.ToString() + "/" + fileId.ToString();
                         *
                         *
                         *  var subList = listOfFiles.Where(a => a.Key.Contains(sample.Name));
                         *  foreach (var file in subList)
                         *  {
                         *      System.Console.WriteLine("&&&&& \n Will copy files &&&&&&& "+file.Key);
                         *
                         *      string fileURL = "https://dev-gn-s3-01.s3.amazonaws.com/" + folderPath + file.Key;
                         *
                         *      GNCloudFile newFile = new GNCloudFile
                         *      {
                         *          Id = fileId,
                         *          GNCloudFileCategoryId = fileCategory.Id, //FASTQ
                         *          CloudFileCategory = fileCategory,
                         *          FileName = folderPath + file.Key,
                         *          FileURL = fileURL,
                         *          FolderPath = folderPath,
                         *          Volume = volume,
                         *          Description = file.Key,
                         *          FileSize = file.Value,
                         *          AWSRegionSystemName = db.AWSRegions.FirstOrDefault().AWSRegionSystemName,
                         *          CreateDateTime = DateTime.Now,
                         *          CreatedBy = Guid.Parse("0750f896-e7d6-48d4-a1b9-007059f62784"),
                         *          SampleId = sample.Id.ToString()
                         *      };
                         *      db.GNCloudFiles.Add(newFile);
                         *
                         *   //   st.CopyS3Object(originBucket, fileURL, file.Key);
                         *  }
                         *  db.SaveChanges()
                         *
                         * }*/
                    }
                    catch (Exception filesUpdateExc)
                    {
                        System.Console.WriteLine("***\n Unable to Read the Files from S3: " + newSampleMessageStatus.batchId + "\n" + filesUpdateExc.Message + filesUpdateExc.InnerException + filesUpdateExc.StackTrace);

                        Exception e2 = new Exception("Unable to Read the Files from S3 for this batch New Sample: ", filesUpdateExc);
                        LogUtil.Warn(logger, filesUpdateExc.Message, filesUpdateExc);
                        success = false;
                    }

                    success = true;
                }
                ////////////////////////////END OF READING FILES FROM S3 AND UPDATING RDS //////////////



                if (isError)
                {
                    Batch.GNSequencerJob.Status = "ERROR";
                    db.SaveChanges();

                    //NOTIFY USER
                    bool notifySuccess =
                        new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                            "SAMPLE_STATUS_UPDATE_ERROR",
                            "*****@*****.**",
                            "Sample Status Update",
                            new Dictionary <string, string>
                    {
                        { "BatchId", newSampleMessageStatus.batchId },
                        { "CreatorName", Organization.OrgMainContact.FullName },
                        { "ErrorMessage", newSampleMessageStatus.message },
                        { "CreateDateTime", DateTime.Now.ToString() }
                    });
                }

                if (newSampleMessageStatus.percentComplete == 100 || newSampleMessageStatus.percentComplete.Equals("100"))
                {
                    Batch.GNSequencerJob.Status = "COMPLETED";
                    db.SaveChanges();


                    if (Batch.AutoStartAnalysis)
                    {
                        //loop through all the samples, look for their analyses, and start them.
                        List <GNNewSampleBatchSamples> ListOfSamples = Batch.GNNewSampleBatchSamples.ToList();

                        foreach (GNNewSampleBatchSamples batchSample in ListOfSamples)
                        {
                            GNSample sample = batchSample.GNSample;
                            var      result = this.AutostartAnalysis(sample);
                        }
                    }


                    try
                    {
                        //NOTIFY USER
                        bool notifySuccess =
                            new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                                "SAMPLE_STATUS_UPDATE_COMPLETE",
                                "*****@*****.**",
                                "Sample Status Update",
                                new Dictionary <string, string>
                        {
                            { "BatchId", Batch.Id.ToString() },
                            { "TotalSamples", Batch.TotalSamples.ToString() },
                            { "CreatorName", Organization.OrgMainContact.FullName },
                            { "ErrorMessage", newSampleMessageStatus.message },
                            { "CreateDateTime", DateTime.Now.ToString() }
                        });
                    }
                    catch (Exception e2)
                    {
                        System.Console.WriteLine("***Message " + e2.Message + e2.StackTrace + " **********************************");
                    }
                }
            }
            catch (Exception e1)
            {
                Exception e2 = new Exception("Unable to Update Status of New Sample.", e1);
                LogUtil.Warn(logger, e2.Message, e2);
                success = false;
            }
            return(success);
        }
        public override bool ProcessMessage(NewSampleResponse newSampleMessage, object queueMessage)
        {
            System.Console.WriteLine("***\n ****** Sample Name: " + newSampleMessage.name);
            System.Console.WriteLine("***\n ****** Sample type: " + newSampleMessage.type);
            System.Console.WriteLine("***\n ****** Sample repositoryId: " + newSampleMessage.repositoryId);

            bool success = false;

            try
            {
                GNSampleType type = db.GNSampleTypes.Where(a => a.Name.Equals(newSampleMessage.type.ToUpper())).FirstOrDefault();

                System.Console.WriteLine("***\n  type " + type.Name);

                GNOrganization Organization = db.GNOrganizations.Where(a => a.Repository.Equals(newSampleMessage.repositoryId)).FirstOrDefault();

                System.Console.WriteLine("***\n  Organization " + Organization.Name);
                GNSample sampleExist = db.GNSamples.Where(a => a.Name.Equals(newSampleMessage.name) && a.GNOrganizationId.Equals(Organization.Id)).FirstOrDefault();

                bool createNewSample = false;
                if (sampleExist != null)
                {
                    if (sampleExist.IsReady)
                    {
                        //the sample is ready, let's create a new one with a suffix of (1)
                        newSampleMessage.name = newSampleMessage.name + " (1)";
                        createNewSample       = true;
                    }
                    else
                    {
                        //the sample is in the middle of being created, so ignore the message
                        createNewSample = false;
                    }
                }
                else
                {
                    createNewSample = true;
                }

                try
                {
                    if (createNewSample)
                    {
                        GNSample newSample = new GNSample
                        {
                            Id = Guid.NewGuid(),
                            GNOrganizationId      = Organization.Id,
                            Name                  = newSampleMessage.name,
                            Gender                = newSampleMessage.gender,
                            GNSampleTypeId        = type.Id,
                            GNSampleQualifierCode = newSampleMessage.qualifier,
                            IsReady               = false,
                            IsPairEnded           = (newSampleMessage.read == "paired-end"),
                            CreateDateTime        = DateTime.Now,
                            CreatedBy             = Guid.Parse("0750f896-e7d6-48d4-a1b9-007059f62784")
                        };

                        db.GNSamples.Add(newSample);

                        db.SaveChanges();

                        System.Console.WriteLine("***\n  Sample Name: " + newSampleMessage.name);

                        //NOTIFY USER
                        bool notifySuccess =
                            new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                                "SAMPLE_CREATION",
                                "*****@*****.**",
                                "Sample Creation",
                                new Dictionary <string, string>
                        {
                            { "SampleName", newSample.Name },
                            { "SampleId", newSample.Id.ToString() },
                            { "CreatorName", Organization.OrgMainContact.FullName },
                            { "CreateDateTime", DateTime.Now.ToString() }
                        });
                    }
                }
                catch (Exception e1)
                {
                    System.Console.WriteLine("***\n  Exception: " + e1.Message + e1.InnerException + e1.StackTrace);
                }


                success = true;
            }
            catch (Exception e1)
            {
                Exception e2 = new Exception("Unable to Create New Sample.", e1);
                LogUtil.Warn(logger, e2.Message, e2);
                success = false;
            }
            return(success);
        }
        public override bool ProcessMessage(NewSampleBatch newSampleMessage, object queueMessage)
        {
            System.Console.WriteLine("***\n ****** Batch Id: " + newSampleMessage.batchId);
            System.Console.WriteLine("***\n ****** Sample type: " + newSampleMessage.type);
            System.Console.WriteLine("***\n ****** Sample repositoryId: " + newSampleMessage.repositoryId);

            SampleResponseService sampleResponseService = new SampleResponseService();

            GNOrganization Organization = db.GNOrganizations.Where(a => a.Repository.Equals(newSampleMessage.repositoryId)).FirstOrDefault();

            //Find sequencer job
            GNSequencerJob sequencerJob = db.GNSequencerJobs.Where(a => a.GNOrganizationId.Equals(Organization.Id) && a.Project.Equals(newSampleMessage.project)).FirstOrDefault();

            sequencerJob.Status = "PROCESSING SAMPLES";

            GNNewSampleBatch newSampleBatch = new GNNewSampleBatch {
                Id                      = Guid.NewGuid(),
                BatchId                 = newSampleMessage.batchId,
                GNSequencerJobId        = sequencerJob.Id,
                GNSequencerJob          = sequencerJob,
                Project                 = newSampleMessage.project,
                AutoStartAnalysis       = (newSampleMessage.autoStartAnalysis.Equals("true")),
                CreateAnalysisPerSample = (newSampleMessage.createAnalysisPerSample.Equals("true")),
                Qualifier               = newSampleMessage.qualifier,
                Type                    = newSampleMessage.type,
                RepositoryId            = newSampleMessage.repositoryId,
                Gender                  = newSampleMessage.gender,
                ReadType                = newSampleMessage.read,
                TotalSamples            = newSampleMessage.samples.Count(),
                TotalSamplesCompleted   = 0,
                CreateDateTime          = DateTime.Now
            };

            db.GNNewSampleBatches.Add(newSampleBatch);

            db.SaveChanges();

            bool success = false;

            try
            {
                GNSampleType type = db.GNSampleTypes.Where(a => a.Name.Equals(newSampleMessage.type.ToUpper())).FirstOrDefault();

                System.Console.WriteLine("***\n  type " + type.Name);

                System.Console.WriteLine("***\n  Organization " + Organization.Name);

                GNTeam         newTeam      = null;
                GNProject      newProject   = null;
                GNAnalysisType analysisType = null;
                String         AnalysisCode = newSampleMessage.qualifier;
                if (newSampleBatch.CreateAnalysisPerSample)
                {
                    /**
                     * 1. Create a Team
                     * 2. Create a Project
                     */
                    GNContact contact = db.GNContacts.Find(Organization.GNContactId);

                    newTeam = new GNTeam
                    {
                        Id             = Guid.NewGuid(),
                        CreateDateTime = DateTime.Now,
                        CreatedBy      = Guid.Parse("0750f896-e7d6-48d4-a1b9-007059f62784"),
                        Name           = "TeamBatch" + newSampleBatch.BatchId.Substring(0, 15),
                        GNContactId    = contact.Id,
                        Organization   = Organization,
                        OrganizationId = Organization.Id,
                        TeamLead       = contact
                    };
                    db.GNTeams.Add(newTeam);
                    db.SaveChanges();
                    System.Console.WriteLine("***\n  New newTeam Created: " + newTeam.Id);

                    newProject = new GNProject
                    {
                        Id             = Guid.NewGuid(),
                        CreateDateTime = DateTime.Now,
                        CreatedBy      = Guid.Parse("0750f896-e7d6-48d4-a1b9-007059f62784"),
                        ProjectLead    = contact,
                        ProjectLeadId  = contact.Id.ToString(),
                        Name           = "ProjectBatch-" + newSampleBatch.BatchId.Substring(0, 15),
                        TeamId         = newTeam.Id.ToString(),
                        StartDate      = DateTime.Now,
                        EndDate        = DateTime.Now.AddDays(30),
                        Description    = "Created automatically from the Sample Batch Process"
                    };

                    System.Console.WriteLine("***\n  New newProject Created: " + newProject.Id);

                    newTeam.Projects.Add(newProject);
                    newProject.Teams.Add(newTeam);
                    db.GNProjects.Add(newProject);

                    db.SaveChanges();

                    if (newSampleMessage.qualifier.Equals("TUMOR"))
                    {
                        AnalysisCode = "TUMORNORMAL";
                    }
                    analysisType = db.GNAnalysisTypes.Where(a => a.Name.Equals(newSampleMessage.type.ToUpper())).FirstOrDefault();
                }

                foreach (String sampleName in newSampleMessage.samples)
                {
                    String   newSampleName   = sampleName;
                    GNSample sampleExist     = db.GNSamples.Where(a => a.Name.Equals(sampleName) && a.GNOrganizationId.Equals(Organization.Id)).FirstOrDefault();
                    bool     createNewSample = false;
                    if (sampleExist != null)
                    {
                        if (sampleExist.IsReady)
                        {
                            //the sample is ready, let's create a new one with a suffix of (1)
                            newSampleName   = sampleName + " (1)";
                            createNewSample = true;
                        }
                        else
                        {
                            //the sample is in the middle of being created, so ignore the message
                            createNewSample = false;
                        }
                    }
                    else
                    {
                        createNewSample = true;
                    }

                    try
                    {
                        if (createNewSample)
                        {
                            GNSample newSample = new GNSample
                            {
                                Id = Guid.NewGuid(),
                                GNOrganizationId      = Organization.Id,
                                Name                  = newSampleName,
                                Gender                = newSampleMessage.gender,
                                GNSampleTypeId        = type.Id,
                                GNSampleQualifierCode = newSampleMessage.qualifier,
                                IsReady               = false,
                                IsPairEnded           = (newSampleMessage.read == "paired-end"),
                                CreateDateTime        = DateTime.Now,
                                CreatedBy             = Guid.Parse("0750f896-e7d6-48d4-a1b9-007059f62784")
                            };

                            db.GNSamples.Add(newSample);

                            db.SaveChanges();
                            System.Console.WriteLine("***\n  New Sample Created: " + newSample.Id);

                            GNNewSampleBatchSamples batchSample = new GNNewSampleBatchSamples {
                                Id                 = Guid.NewGuid(),
                                GNSample           = newSample,
                                CreateDateTime     = DateTime.Now,
                                GNNewSampleBatch   = newSampleBatch,
                                GNNewSampleBatchId = newSampleBatch.Id,
                                Name               = sampleName
                            };
                            db.GNNewSampleBatchSamples.Add(batchSample);

                            db.SaveChanges();
                            System.Console.WriteLine("***\n  New batchSample Created: " + batchSample.Id);

                            GNNewSampleBatchStatus batchStatus = new GNNewSampleBatchStatus {
                                Id                 = Guid.NewGuid(),
                                CreateDateTime     = DateTime.Now,
                                GNNewSampleBatch   = newSampleBatch,
                                GNNewSampleBatchId = newSampleBatch.Id,
                                IsError            = false,
                                PercentComplete    = 0,
                                Status             = "STARTING PROCESS",
                                RepositoryId       = newSampleMessage.repositoryId
                            };
                            db.GNNewSampleBatchStatus.Add(batchStatus);
                            db.SaveChanges();
                            System.Console.WriteLine("***\n  New batchStatus Created: " + batchStatus.Id);


                            if (newSampleBatch.CreateAnalysisPerSample)
                            {
                                GNAnalysisRequest newAnalysis = new GNAnalysisRequest {
                                    Id                        = Guid.NewGuid(),
                                    Project                   = newProject,
                                    GNProjectId               = newProject.Id,
                                    CreateDateTime            = DateTime.Now,
                                    CreatedBy                 = Guid.Parse("0750f896-e7d6-48d4-a1b9-007059f62784"),
                                    AnalysisType              = analysisType,
                                    RequestProgress           = 0, RequestDateTime = DateTime.Now,
                                    GNAnalysisRequestTypeCode = AnalysisCode,
                                    Description               = newSampleName,
                                    GNAnalysisAdaptorCode     = "NONE",
                                    AnalysisTypeId            = analysisType.Id.ToString(),
                                    AutoStart                 = newSampleBatch.AutoStartAnalysis,
                                    AWSRegionSystemName       = db.AWSRegions.FirstOrDefault().AWSRegionSystemName
                                };
                                db.GNAnalysisRequests.Add(newAnalysis);

                                db.SaveChanges();
                                System.Console.WriteLine("***\n  New newAnalysis Created: " + newAnalysis.Id);


                                GNAnalysisRequestGNSample newAnalysisSample = new GNAnalysisRequestGNSample {
                                    AffectedIndicator   = "N",
                                    TargetIndicator     = "N",
                                    GNAnalysisRequest   = newAnalysis,
                                    GNSample            = newSample,
                                    GNAnalysisRequestId = newAnalysis.Id,
                                    GNSampleId          = newSample.Id
                                };
                                db.GNAnalysisRequestGNSamples.Add(newAnalysisSample);
                            } //end of "if(newSampleBatch.CreateAnalysisPerSample)"

                            System.Console.WriteLine("***\n  Sample Name: " + sampleName);

                            //Notify BCL2FASTQ service
                            sampleResponseService.NotifyBcl2FastqSystem(newSample, newSampleBatch.RepositoryId);
                        }

                        db.SaveChanges();
                    }
                    catch (Exception e1)
                    {
                        System.Console.WriteLine("***\n  Exception: " + e1.Message + e1.InnerException);
                    }
                }

                System.Console.WriteLine("***\n  EVERYTHING WORKED!");

                //NOTIFY USER
                bool notifySuccess =
                    new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                        "SAMPLE_CREATION",
                        "*****@*****.**",
                        "Sample Creation",
                        new Dictionary <string, string>
                {
                    { "BatchId", newSampleMessage.batchId },
                    { "TotalSamples", newSampleBatch.TotalSamples.ToString() },
                    { "CreatorName", Organization.OrgMainContact.FullName },
                    { "CreateDateTime", DateTime.Now.ToString() }
                });
                success = true;
            }
            catch (Exception e1)
            {
                Exception e2 = new Exception("Unable to Create New Sample.", e1);
                LogUtil.Warn(logger, e2.Message, e2);
                success = false;
            }
            return(success);
        }
        public override bool ProcessMessage(NewSampleStatus newSampleMessageStatus, object queueMessage)
        {
            System.Console.WriteLine("***\n newSampleMessageStatus Sample Name: " + newSampleMessageStatus.name);

            if (newSampleMessageStatus.batchId.Equals("NO_SAMPLE_FOUND"))
            {
                //processSpecialCases();
            }

            bool success = false;

            try
            {
                GNOrganization Organization = db.GNOrganizations.Where(a => a.Repository.Equals(newSampleMessageStatus.repositoryId)).FirstOrDefault();
                GNSample       sample       = db.GNSamples.Where(a => a.Name.Equals(newSampleMessageStatus.name.ToUpper()) && a.GNOrganizationId.Equals(Organization.Id)).FirstOrDefault();

                bool isError = false;
                if (newSampleMessageStatus.isError.Equals("true"))
                {
                    isError = true;
                }

                var tx = db.Database.BeginTransaction();

                string insertSQL =
                    "INSERT INTO [gn].[GNSampleStatus]" +
                    "([Id],[GNSampleId],[SampleName],[Repository],[Message],[PercentComplete],[IsError],[CreatedBy],[CreateDateTime])" +
                    "VALUES " +
                    "(@Id, @GNSampleId, @SampleName, @Repository, @Message, @PercentComplete, @IsError, @CreatedBy, @CreateDateTime)";

                db.Database.ExecuteSqlCommand(
                    insertSQL,
                    new SqlParameter("@Id", Guid.NewGuid()),
                    new SqlParameter("@GNSampleId", sample.Id),
                    new SqlParameter("@SampleName", newSampleMessageStatus.name),
                    new SqlParameter("@Repository", newSampleMessageStatus.repositoryId),
                    new SqlParameter("@Message", newSampleMessageStatus.message),
                    new SqlParameter("@PercentComplete", newSampleMessageStatus.percentComplete),
                    new SqlParameter("@IsError", isError),
                    new SqlParameter("@CreatedBy", Guid.Parse("0750f896-e7d6-48d4-a1b9-007059f62784")),
                    new SqlParameter("@CreateDateTime", DateTime.Now));

                LogUtil.Warn(logger, insertSQL);
                tx.Commit();

                success = true;

                if (newSampleMessageStatus.filesBucket != null && newSampleMessageStatus.filesBucket != "")
                {
                    //update files in Sample
                }

                if (isError)
                {
                    //NOTIFY USER
                    bool notifySuccess =
                        new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                            "SAMPLE_STATUS_UPDATE_ERROR",
                            "*****@*****.**",
                            "Sample Status Update",
                            new Dictionary <string, string>
                    {
                        { "SampleName", sample.Name },
                        { "SampleId", sample.Id.ToString() },
                        { "CreatorName", Organization.OrgMainContact.FullName },
                        { "ErrorMessage", newSampleMessageStatus.message },
                        { "CreateDateTime", DateTime.Now.ToString() }
                    });
                }

                if (newSampleMessageStatus.percentComplete == 100 || newSampleMessageStatus.percentComplete.Equals("100"))
                {
                    sample.IsReady = true;

                    db.SaveChanges();

                    try
                    {
                        //NOTIFY USER
                        bool notifySuccess =
                            new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                                "SAMPLE_STATUS_UPDATE_COMPLETE",
                                "*****@*****.**",
                                "Sample Status Update",
                                new Dictionary <string, string>
                        {
                            { "SampleName", sample.Name },
                            { "SampleId", sample.Id.ToString() },
                            { "CreatorName", Organization.OrgMainContact.FullName },
                            { "ErrorMessage", newSampleMessageStatus.message },
                            { "CreateDateTime", DateTime.Now.ToString() }
                        });
                    }
                    catch (Exception e2)
                    {
                        System.Console.WriteLine("***Message " + e2.Message + e2.StackTrace + " **********************************");
                    }
                }
            }
            catch (Exception e1)
            {
                Exception e2 = new Exception("Unable to Update Status of New Sample.", e1);
                LogUtil.Warn(logger, e2.Message, e2);
                success = false;
            }
            return(success);
        }
Ejemplo n.º 17
0
        public override bool ProcessMessage(NewSampleBatchStatus newSampleMessageStatus, object queueMessage)
        {
            System.Console.WriteLine("***\n newSampleMessageStatus Batch Name: " + newSampleMessageStatus.batchId);

            if (newSampleMessageStatus.batchId.Equals("NO_SAMPLE_FOUND"))
            {
                //processSpecialCases();
            }

            if (newSampleMessageStatus.status.Equals("QC-COMPLETED"))
            {
                // ProcessQCMessage(newSampleMessageStatus);
                return(true);
            }

            bool success = false;

            try
            {
                GNOrganization   Organization = db.GNOrganizations.Where(a => a.Repository.Equals(newSampleMessageStatus.repository)).FirstOrDefault();
                GNNewSampleBatch Batch        = db.GNNewSampleBatches.Where(a => a.BatchId.Trim().Equals(newSampleMessageStatus.batchId)).FirstOrDefault();

                if (Batch == null)
                {
                    throw new Exception("Batch not found!");
                }

                System.Console.WriteLine("\n --==========================---------> Batch " + Batch.Id);

                try
                {
                    Batch.TotalNumberOfFastqFiles = Int32.Parse(newSampleMessageStatus.numberOfFastqFiles);
                }
                catch (Exception numberNull)
                {
                    Batch.TotalNumberOfFastqFiles = 0;
                }

                System.Console.WriteLine("\n -----------> Organization " + Organization.Name);


                bool isError = false;
                if (newSampleMessageStatus.isError.Equals("true"))
                {
                    isError = true;
                }

                string status = newSampleMessageStatus.status;
                if (newSampleMessageStatus.percentComplete > 89)
                {
                    //higher percentages will be dealt by the Portal during the Quality Control step
                    return(true);
                }


                //check if the status has been already recorded
                int alreadyExists = db.GNNewSampleBatchStatus.Where(a => a.GNNewSampleBatch.BatchId.Equals(newSampleMessageStatus.batchId) && a.PercentComplete == newSampleMessageStatus.percentComplete && a.Status.Equals(status)).Count();

                if (alreadyExists == 0)
                {
                    GNNewSampleBatchStatus batchStatus = new GNNewSampleBatchStatus
                    {
                        Id                 = Guid.NewGuid(),
                        CreateDateTime     = DateTime.Now,
                        GNNewSampleBatch   = Batch,
                        GNNewSampleBatchId = Batch.Id,
                        IsError            = isError,
                        PercentComplete    = newSampleMessageStatus.percentComplete,
                        Status             = status,
                        Repository         = newSampleMessageStatus.repository,
                        Message            = newSampleMessageStatus.message
                    };
                    db.GNNewSampleBatchStatus.Add(batchStatus);
                    db.SaveChanges();

                    System.Console.WriteLine("\n -----------> Added status " + newSampleMessageStatus.status + " " + newSampleMessageStatus.percentComplete + "%");

                    if (isError)
                    {
                        Batch.GNSequencerJob.Status = "ERROR";
                        db.SaveChanges();

                        //NOTIFY USER
                        bool notifySuccess =
                            new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                                "SAMPLE_STATUS_UPDATE_ERROR",
                                Organization.OrgMainContact.Email,
                                "Sample Status Update",
                                new Dictionary <string, string>
                        {
                            { "BatchId", newSampleMessageStatus.batchId },
                            { "CreatorName", Organization.OrgMainContact.FullName },
                            { "ErrorMessage", newSampleMessageStatus.message },
                            { "CreateDateTime", DateTime.Now.ToString() }
                        });
                    }

                    /*
                     * if (newSampleMessageStatus.percentComplete == 100 || newSampleMessageStatus.percentComplete.Equals("100"))
                     * {
                     *  Batch.GNSequencerJob.Status = "COMPLETED";
                     *
                     *
                     *  //loop through all the samples, look for their analyses, and start them.
                     *  foreach (GNNewSampleBatchSamples sampleBatch in Batch.GNNewSampleBatchSamples)
                     *  {
                     *      sampleBatch.GNSample.IsReady = true;
                     *  }
                     *
                     *  db.SaveChanges();
                     *
                     *
                     *  if (Batch.AutoStartAnalysis)
                     *  {
                     *      //loop through all the samples, look for their analyses, and start them.
                     *      List<GNNewSampleBatchSamples> ListOfSamples = Batch.GNNewSampleBatchSamples.ToList();
                     *
                     *      foreach (GNNewSampleBatchSamples batchSample in ListOfSamples)
                     *      {
                     *          GNSample sample = batchSample.GNSample;
                     *          var result = this.AutostartAnalysis(sample);
                     *      }
                     *  }
                     *
                     *  try
                     *  {
                     *      String notifyCreateAnalysis = "";
                     *      if (Batch.CreateAnalysisPerSample)
                     *      {
                     *          notifyCreateAnalysis = "Each sample had one analysis created automatically.";
                     *      }
                     *
                     *      String notifyAutostartAnalysis = "";
                     *      if (Batch.AutoStartAnalysis)
                     *      {
                     *          notifyAutostartAnalysis = "Each analysis create was autostarted as soon as the samples were completed. New notifications will be sent to your inbox -with links to each analysis- as these move along.";
                     *      }
                     *
                     *      //NOTIFY USER
                     *      bool notifySuccess =
                     *              new GenomeNext.App.NotificationCloudMessageService().NotifyGNContact(
                     *                  "SAMPLE_STATUS_UPDATE_COMPLETE",
                     *                  "*****@*****.**", //Organization.OrgMainContact.Email,
                     *                  "Sample Status Update",
                     *                  new Dictionary<string, string>
                     *                      {
                     *                          {"ProjectName", Batch.GNSequencerJob.Project},
                     *                          {"TotalSamples", Batch.TotalSamples.ToString()},
                     *                          {"CreateAnalysisPerSample", notifyCreateAnalysis},
                     *                          {"AutoStartAnalysis", notifyAutostartAnalysis},
                     *                          {"ErrorMessage", newSampleMessageStatus.message},
                     *                          {"CreateDateTime",DateTime.Now.ToString()}
                     *                      });
                     *  }
                     *  catch (Exception e2)
                     *  {
                     *      System.Console.WriteLine("***Message " + e2.Message + e2.StackTrace + " **********************************");
                     *
                     *  }
                     *
                     * }
                     */
                }


                success = true;
            }
            catch (Exception e1)
            {
                Exception e2 = new Exception("Unable to Update Status of New Sample.", e1);
                System.Console.WriteLine("***\n  Exception: " + e1.Message + e1.StackTrace + e1.InnerException);
                LogUtil.Warn(logger, e2.Message, e2);
                success = false;
            }
            return(success);
        }