public void TypeCompany_CreatesSuccessfully()
        {
            var organisation = new Organisation(AnyString, BusinessType.LimitedCompany, null);

            Assert.Equal(AnyString, organisation.Name);
            Assert.Equal(BusinessType.LimitedCompany, organisation.Type);
        }
Beispiel #2
0
 public Invoice(int invoice_id, int entity_id, int invoice_type_id, int booking_id, int payer_organisation_id, int payer_patient_id, int non_booking_invoice_organisation_id, string healthcare_claim_number, int reject_letter_id, string message,
                int staff_id, int site_id, DateTime invoice_date_added, decimal total, decimal gst, decimal receipts_total, decimal vouchers_total, decimal credit_notes_total, decimal refunds_total,
                bool is_paid, bool is_refund, bool is_batched, int reversed_by, DateTime reversed_date, DateTime last_date_emailed)
 {
     this.invoice_id              = invoice_id;
     this.entity_id               = entity_id;
     this.invoice_type            = new IDandDescr(invoice_type_id);
     this.booking                 = booking_id            == -1 ? null : new Booking(booking_id);
     this.payer_organisation      = payer_organisation_id ==  0 ? null : new Organisation(payer_organisation_id);
     this.payer_patient           = payer_patient_id      == -1 ? null : new Patient(payer_patient_id);
     this.non_booking_invoice_organisation = non_booking_invoice_organisation_id == -1 ? null : new Organisation(non_booking_invoice_organisation_id);
     this.healthcare_claim_number = healthcare_claim_number;
     this.reject_letter           = reject_letter_id      == -1 ? null : new Letter(reject_letter_id);
     this.message                 = message;
     this.staff                   = new Staff(staff_id);
     this.site                    = site_id               == -1 ? null : new Site(site_id);
     this.invoice_date_added      = invoice_date_added;
     this.total                   = total;
     this.gst                     = gst;
     this.receipts_total          = receipts_total;
     this.vouchers_total          = vouchers_total;
     this.credit_notes_total      = credit_notes_total;
     this.refunds_total           = refunds_total;
     this.is_paid                 = is_paid;
     this.is_refund               = is_refund;
     this.is_batched              = is_batched;
     this.reversed_by             = reversed_by == -1 ? null : new Staff(reversed_by);
     this.reversed_date           = reversed_date;
     this.last_date_emailed       = last_date_emailed;
 }
 public RegisterPatient(int register_patient_id, int organisation_id, int patient_id, DateTime register_patient_date_added)
 {
     this.register_patient_id = register_patient_id;
     this.organisation = new Organisation(organisation_id);
     this.patient = new Patient(patient_id);
     this.register_patient_date_added = register_patient_date_added;
 }
 public Fantassin(string nom, Organisation etatMajor) : base(nom, etatMajor)
 {
     ComportementCombat = new ComportementApiedAvecHache();
     ComportementEmettreUnSon = new ComportementCrier();
     ComportementDeplace = new ComportementDeplaceApied();
     ComportementAffichage = new ComportementAffichageHumble();
 }
 /// <summary>
 /// Add a new client
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="client">client details</param>
 /// <param name="person">Person details</param>
 /// <param name="organisation">Organisation details</param>
 /// <param name="addresses">Addresses</param>
 /// <param name="addressInformation"></param>
 /// <returns></returns>
 public ClientReturnValue AddClient(HostSecurityToken oHostSecurityToken, Client client,
     Person person,
     Organisation organisation,
     List<Address> addresses,
     List<AdditionalAddressElement> addressInformation)
 {
     ClientReturnValue returnValue = null;
     try
     {
         if (Functions.ValidateIWSToken(oHostSecurityToken))
         {
             oClientService = new ClientService();
             returnValue = oClientService.AddClient(Functions.GetLogonIdFromToken(oHostSecurityToken), client, person, organisation, addresses, addressInformation);
         }
         else
         {
             returnValue = new ClientReturnValue();
             returnValue.Success = false;
             returnValue.Message = "Invalid Token";
         }
     }
     catch (Exception ex)
     {
         returnValue = new ClientReturnValue();
         returnValue.Success = false;
         returnValue.Message = ex.Message;
     }
     return returnValue;
 }
 public Chevalier(string nom, Organisation etatMajor) : base(nom, etatMajor)
 {
     ComportementCombat = new ComportementAcheval();
     ComportementEmettreUnSon = new ComportementParler();
     ComportementDeplace = new ComportementDeplaceAcheval();
     ComportementAffichage = new ComportementAffichageNoble();
 }
        public override string ToString()
        {
            if (string.IsNullOrWhiteSpace (FName))
                throw new ApplicationException ("First name is mandatory.");
            Organisation organisation = new Organisation ("");

            return string.Format ("[Employee: FName={0}, LName={1} belonogs to department {3}  with registered id Id={2}]", FName, LName, Id,organisation.Department);
        }
Beispiel #8
0
 public Stock(int stock_id, int organisation_id, int offering_id, int qty, int warning_amt)
 {
     this.stock_id     = stock_id;
     this.organisation = new Organisation(organisation_id);
     this.offering     = new Offering(offering_id);
     this.qty          = qty;
     this.warning_amt  = warning_amt;
 }
 public OrganisationOfferings(int organisation_offering_id, int organisation_id, int offering_id, decimal price, DateTime date_active)
 {
     this.organisation_offering_id = organisation_offering_id;
     this.organisation = new Organisation(organisation_id);
     this.offering = new Offering(offering_id);
     this.price = price;
     this.date_active = date_active;
 }
 public PatientReferrer(int patient_referrer_id, int patient_id, int register_referrer_id, int organisation_id, DateTime patient_referrer_date_added, bool is_debtor)
 {
     this.patient_referrer_id            = patient_referrer_id;
     this.patient                        = new Patient(patient_id);
     this.registerReferrer               = register_referrer_id == -1 ? null : new RegisterReferrer(register_referrer_id);
     this.organisation                   = organisation_id      ==  0 ? null : new Organisation(organisation_id);
     this.patient_referrer_date_added    = patient_referrer_date_added;
     this.is_debtor                      = is_debtor;
 }
Beispiel #11
0
        public void CanLinkToOrganisation()
        {
            var address = new Address("address1", "address2", "town", "region", "postcode", "country");
            var org = new Organisation("name", AnyType, "123");

            anyUser.LinkToOrganisation(org);

            Assert.NotNull(anyUser.Organisation);
        }
Beispiel #12
0
        public Scheme(Organisation organisation)
        {
            Guard.ArgumentNotNull(() => organisation, organisation);

            Organisation = organisation;
            OrganisationId = organisation.Id;
            SchemeStatus = SchemeStatus.Pending;
            ApprovalNumber = string.Empty;
        }
Beispiel #13
0
    public static Booking[] GetBetween(bool debugPageLoadTime, DateTime date_start, DateTime date_end, Staff[] staff, Organisation[] organisations, Patient patient, Staff added_by, bool incDeleted = false, string statusIDsToInclude = null, bool onlyUnavailabilities = false, string booking_id_serach = "")
    {
        DataTable tbl = GetDataTable_Between(debugPageLoadTime, date_start, date_end, staff, organisations, patient, added_by, incDeleted, statusIDsToInclude, onlyUnavailabilities, booking_id_serach);

        Booking[] bookings = new Booking[tbl.Rows.Count];
        for (int i = 0; i < tbl.Rows.Count; i++)
            bookings[i] = LoadFull(tbl.Rows[i]);

        return bookings;
    }
    public static Organisation[] GetAll(bool showDeleted = false, bool exclGroupOrg = true, bool exclClinics = false, bool exclAgedCareFacs = false, bool exclIns = true, bool exclExternal = false, string matchName = "", bool searchNameOnlyStartsWith = false, string org_type_ids = "")
    {
        DataTable tbl = GetDataTable(0, showDeleted, exclGroupOrg, exclClinics, exclAgedCareFacs, exclIns, exclExternal, matchName, searchNameOnlyStartsWith, org_type_ids);

        Organisation[] list = new Organisation[tbl.Rows.Count];
        for (int i = 0; i < tbl.Rows.Count; i++)
            list[i] = Load(tbl.Rows[i]);

        return list;
    }
    public StockUpdateHistory(int stock_update_history_id, int organisation_id, int offering_id, int qty_added, bool is_created, bool is_deleted, int added_by, DateTime date_added)
    {
        this.stock_update_history_id = stock_update_history_id;
        this.organisation = new Organisation(organisation_id);
        this.offering     = new Offering(offering_id);
        this.qty_added    = qty_added;

        this.is_created = is_created;
        this.is_deleted = is_deleted;

        this.added_by     = added_by == -1 ? null : new Staff(added_by);
        this.date_added   = date_added;
    }
 public OfferingOrder(int offering_order_id, int offering_id, int organisation_id, int staff_id, int patient_id, int quantity,
             DateTime date_ordered, DateTime date_filled, DateTime date_cancelled, string descr)
 {
     this.offering_order_id = offering_order_id;
     this.offering          = new Offering(offering_id);
     this.organisation      = new Organisation(organisation_id);
     this.staff             = new Staff(staff_id);
     this.patient           = new Patient(patient_id);
     this.quantity          = quantity;
     this.date_ordered      = date_ordered;
     this.date_filled       = date_filled;
     this.date_cancelled    = date_cancelled;
     this.descr             = descr;
 }
Beispiel #17
0
        public void CannotLinkToSecondOrganisation()
        {
            var address = new Address("address1", "address2", "town", "region", "postcode", "country");
            var org = new Organisation("name", AnyType, "123");

            anyUser.LinkToOrganisation(org);

            var secondAddress = new Address("address12", "address22", "town2", "region2", "postcode2", "country2");
            var secondOrg = new Organisation("name2", AnyType, "1232");

            Action linkToOrganisation = () => anyUser.LinkToOrganisation(secondOrg);

            Assert.Throws<InvalidOperationException>(linkToOrganisation);
        }
        static void CreateRelationship(RestClient client, Root root, int zephyrTestCaseId, int zephyrRequirementId, Options options, Organisation org)
        {
            Script script = client.GetScriptByZephyrId(root, zephyrTestCaseId);

            Requirement requirement = client.GetRequirementByZephyrId(root, zephyrRequirementId);

            try
            {
                client.CreateRelationshipBetweenScriptAndRequirement(options.Server, org.Id, script.Id, requirement.Id);
            }
            catch (RelationshipExistsException)
            {
                Console.WriteLine("  => Relationship already exists!");
            }
        }
Beispiel #19
0
    public Booking(int booking_id, int entity_id, DateTime date_start, DateTime date_end, int organisation_id, int provider, int patient_id,
                int offering_id, int booking_type_id, int booking_status_id, int booking_unavailability_reason_id, 
                int added_by, DateTime date_created, int booking_confirmed_by_type_id,  int confirmed_by, DateTime date_confirmed, 
                int deleted_by, DateTime date_deleted, int cancelled_by, DateTime date_cancelled, 
                bool is_patient_missed_appt, bool is_provider_missed_appt, bool is_emergency, 
                bool need_to_generate_first_letter, bool need_to_generate_last_letter, bool has_generated_system_letters,
                DateTime arrival_time, string sterilisation_code, int informed_consent_added_by, DateTime informed_consent_date,
                bool is_recurring, DayOfWeek recurring_day_of_week, TimeSpan recurring_start_time, TimeSpan recurring_end_time,
                int note_count, int inv_count)
    {
        this.booking_id                    = booking_id;
        this.entity_id                     = entity_id;
        this.date_start                    = date_start;
        this.date_end                      = date_end;
        this.organisation                  = organisation_id   ==  0 ? null : new Organisation(organisation_id);
        this.provider                      = provider          == -1 ? null : new Staff(provider);
        this.patient                       = patient_id        == -1 ? null : new Patient(patient_id);
        this.offering                      = offering_id       == -1 ? null : new Offering(offering_id);
        this.booking_type_id               = booking_type_id;
        this.booking_status                = booking_status_id == -2 ? null : new IDandDescr(booking_status_id);
        this.booking_unavailability_reason = booking_unavailability_reason_id == -1 ? null : new IDandDescr(booking_unavailability_reason_id);
        this.added_by                      = added_by          == -1 ? null :new Staff(added_by);
        this.date_created                  = date_created;
        this.booking_confirmed_by_type     = booking_confirmed_by_type_id == -1 ? null : new IDandDescr(booking_confirmed_by_type_id);
        this.confirmed_by                  = confirmed_by      == -1 ? null : new Staff(confirmed_by);
        this.date_confirmed                = date_confirmed;
        this.deleted_by                    = deleted_by        == -1 ? null : new Staff(deleted_by);
        this.date_deleted                  = date_deleted;
        this.cancelled_by                  = cancelled_by      == -1 ? null : new Staff(cancelled_by);
        this.date_cancelled                = date_cancelled;
        this.is_patient_missed_appt        = is_patient_missed_appt;
        this.is_provider_missed_appt       = is_provider_missed_appt;
        this.is_emergency                  = is_emergency;
        this.need_to_generate_first_letter = need_to_generate_first_letter;
        this.need_to_generate_last_letter  = need_to_generate_last_letter;
        this.has_generated_system_letters  = has_generated_system_letters;
        this.arrival_time                  = arrival_time;
        this.sterilisation_code            = sterilisation_code;
        this.informed_consent_added_by     = informed_consent_added_by == -1 ? null : new Staff(informed_consent_added_by);
        this.informed_consent_date         = informed_consent_date;
        this.is_recurring                  = is_recurring;
        this.recurring_day_of_week         = recurring_day_of_week;
        this.recurring_start_time          = recurring_start_time;
        this.recurring_end_time            = recurring_end_time;

        this.note_count                    = note_count;
        this.inv_count                     = inv_count;
    }
        static void CreateAllRelationships(RestClient client, Root root, Options options, Organisation org)
        {
            var source = new DataSource();

            List<RequirementToScriptRel> data = source.GetRequirementToScriptRelationships().ToList();

            for (int i = 0; i < data.Count; i++)
            {
                int zephyrTestCaseId = data[i].TestCaseId;
                int zephyrRequirementId = data[i].RequirementId;

                Console.WriteLine("{0} of {1}: Creating relationship between test case #{2} and requirement #{3}", i + 1, data.Count, zephyrTestCaseId, zephyrRequirementId);

                CreateRelationship(client, root, zephyrTestCaseId, zephyrRequirementId, options, org);
            }
        }
Beispiel #21
0
 public Letter(int letter_id, int organisation_id, int letter_type_id, int site_id, string code, string reject_message, string docname, bool is_send_to_medico, bool is_allowed_reclaim,
             bool is_manual_override, int num_copies_to_print, bool is_deleted)
 {
     this.letter_id = letter_id;
     this.organisation = organisation_id == 0 ? null : new Organisation(organisation_id);
     this.letter_type = new IDandDescr(letter_type_id);
     this.site = new Site(site_id);
     this.code = code;
     this.reject_message = reject_message;
     this.docname = docname;
     this.is_send_to_medico = is_send_to_medico;
     this.is_allowed_reclaim = is_allowed_reclaim;
     this.is_manual_override = is_manual_override;
     this.num_copies_to_print = num_copies_to_print;
     this.is_deleted = is_deleted;
 }
 public LetterPrintHistory(int letter_print_history_id, int letter_id, int letter_print_history_send_method_id,
                           int booking_id, int patient_id, int organisation_id, int register_referrer_id,
                           int staff_id, int health_card_action_id, DateTime date, string doc_name, bool has_doc)
 {
     this.letter_print_history_id = letter_print_history_id;
     this.letter                  = letter_id       == -1 ? null : new Letter(letter_id);
     this.send_method             = new IDandDescr(letter_print_history_send_method_id);
     this.booking                 = new Booking(booking_id);
     this.patient                 = patient_id           == -1 ? null : new Patient(patient_id);
     this.organisation            = organisation_id      ==  0 ? null : new Organisation(organisation_id);
     this.register_referrer       = register_referrer_id == -1 ? null : new RegisterReferrer(register_referrer_id);
     this.staff                   = staff_id             == -1 ? null : new Staff(staff_id);
     this.health_card_action      = new HealthCardAction(health_card_action_id);
     this.date                    = date;
     this.doc_name                = doc_name;
     this.has_doc                 = has_doc;
 }
 public RegisterStaff(int register_staff_id, DateTime register_staff_date_added, int organisation_id, int staff_id, 
                      string provider_number, bool main_provider_for_clinic,
                      bool excl_sun, bool excl_mon, bool excl_tue, bool excl_wed, bool excl_thu, bool excl_fri, bool excl_sat)
 {
     this.register_staff_id = register_staff_id;
     this.register_staff_date_added = register_staff_date_added;
     this.organisation = new Organisation(organisation_id);
     this.staff = new Staff(staff_id);
     this.provider_number = provider_number;
     this.main_provider_for_clinic = main_provider_for_clinic;
     this.excl_sun = excl_sun;
     this.excl_mon = excl_mon;
     this.excl_tue = excl_tue;
     this.excl_wed = excl_wed;
     this.excl_thu = excl_thu;
     this.excl_fri = excl_fri;
     this.excl_sat = excl_sat;
 }
        public ActionResult Create([Bind(Include = "Id,Name,Description,OwnerId,CreatedOn,ModifiedOn,IsDeleted,DeletedOn")] OrganisationCreateModel organisation)
        {
            if (ModelState.IsValid)
            {
                var entity = new Organisation()
                {
                    Name = organisation.Name,
                    Description = organisation.Description,
                    OwnerId = this.User.Identity.GetUserId()
                };

                this.Organisations.Add(entity);
                this.Organisations.SaveChanges();
                return this.RedirectToAction("Index");
            }

            return View(organisation);
        }
    public string ReplaceMergeFields(string text, Hashtable patientIDHash, int patientID,
                                     Organisation org, string orgAddressText, string orgPhoneText, string orgFaxText, string orgWebText, string orgEmailText)
    {
        if (text.Contains("{pt_name}")        ||
            text.Contains("{pt_title}")       ||
            text.Contains("{pt_firstname}")   ||
            text.Contains("{pt_middlename}")  ||
            text.Contains("{pt_surname}")     ||

            text.Contains("{org_name}")       ||
            text.Contains("{org_addr}")       ||
            text.Contains("{org_phone}")      ||
            text.Contains("{org_office_fax}") ||
            text.Contains("{org_web}")        ||
            text.Contains("{org_email}"))
        {
            Patient patient = (Patient)patientIDHash[patientID];

            string title = string.Empty;
            if (patient.Person.Title.ID != 0)
                title = patient.Person.Title.Descr;
            else if (patient.Person.Title.ID == 0 && patient.Person.Gender == "M")
                title = "Mr.";
            else if (patient.Person.Title.ID == 0 && patient.Person.Gender == "F")
                title = "Ms.";

            text = text
                .Replace("{pt_name}",        patient.Person.FullnameWithoutMiddlename)
                .Replace("{pt_title}",       title)
                .Replace("{pt_firstname}",   patient.Person.Firstname)
                .Replace("{pt_middlename}",  patient.Person.Middlename)
                .Replace("{pt_surname}",     patient.Person.Surname)

                .Replace("{org_name}",       org.Name)
                .Replace("{org_addr}",       orgAddressText)
                .Replace("{org_phone}",      orgPhoneText)
                .Replace("{org_office_fax}", orgFaxText)
                .Replace("{org_web}",        orgWebText)
                .Replace("{org_email}",      orgEmailText)
                ;
        }

        return text;
    }
Beispiel #26
0
 public HealthCard(int health_card_id, int patient_id, int organisation_id, string card_name, string card_nbr, string card_family_member_nbr, DateTime expiry_date,
             DateTime date_referral_signed, DateTime date_referral_received_in_office, bool is_active,
             int added_or_last_modified_by, DateTime added_or_last_modified_date,
             string area_treated)
 {
     this.health_card_id                     = health_card_id;
     this.patient                            = new Patient(patient_id);
     this.organisation                       = new Organisation(organisation_id);
     this.card_name                          = card_name;
     this.card_nbr                           = card_nbr;
     this.card_family_member_nbr             = card_family_member_nbr;
     this.expiry_date                        = expiry_date;
     this.date_referral_signed               = date_referral_signed;
     this.date_referral_received_in_office   = date_referral_received_in_office;
     this.is_active                          = is_active;
     this.added_or_last_modified_by          = added_or_last_modified_by == -1 ? null : new Staff(added_or_last_modified_by);
     this.added_or_last_modified_date        = added_or_last_modified_date;
     this.area_treated                       = area_treated;
 }
        protected WeeeContext GetPreparedContext()
        {
            WeeeContext context = A.Fake<WeeeContext>();

            var organisations = A.Fake<DbSet<Organisation>>();
            A.CallTo(() => organisations.Add(A<Organisation>._)).Invokes((Organisation o) =>
            {
                addedOrganisation = o;
                addedOrganisationId = Guid.NewGuid();
                dbHelper.SetId(o, addedOrganisationId);
            });

            var organisationUsers = A.Fake<DbSet<OrganisationUser>>();
            A.CallTo(() => organisationUsers.Add(A<OrganisationUser>._)).Invokes((OrganisationUser ou) => addedOrganisationUser = ou);

            A.CallTo(() => context.Organisations).Returns(organisations);
            A.CallTo(() => context.OrganisationUsers).Returns(organisationUsers);

            return context;
        }
    protected void Add(ref ArrayList list, Staff staff, Organisation org, DateTime start, DateTime end)
    {
        Tuple<Organisation, DateTime, DateTime> t = new Tuple<Organisation, DateTime, DateTime>(org, start, end);

        bool providerFound = false;
        for (int i = 0; i < list.Count; i++)
        {
            if (((Tuple<Staff, ArrayList>)list[i]).Item1.StaffID == staff.StaffID)
            {
                ((ArrayList)((Tuple<Staff, ArrayList>)list[i]).Item2).Add(t);
                providerFound = true;
            }
        }

        if (!providerFound)
        {
            Tuple<Staff, ArrayList> t2 = new Tuple<Staff, ArrayList>(staff, new ArrayList());
            ((ArrayList)((Tuple<Staff, ArrayList>)t2).Item2).Add(t);
            list.Add(t2);
        }
    }
Beispiel #29
0
        public static FaceToFaceCommunicationBuilder WithDefaults(this FaceToFaceCommunicationBuilder @this, Organisation internalOrganisation)
        {
            var faker = @this.Session.Faker();

            var administrator = (Person) new UserGroups(@this.Session).Administrators.Members.First;

            @this.WithDescription(faker.Lorem.Sentence(20));
            @this.WithSubject(faker.Lorem.Sentence(5));
            @this.WithEventPurpose(new CommunicationEventPurposes(@this.Session).Meeting);
            @this.WithFromParty(internalOrganisation.ActiveEmployees.First);
            @this.WithToParty(internalOrganisation.ActiveCustomers.First);
            @this.WithOwner(administrator);
            @this.WithActualStart(DateTime.UtcNow);

            return(@this);
        }
 protected Employer GetEmployer(Employer employer, Organisation organisation)
 {
     employer.Organisation = organisation;
     return(employer);
 }
 public async Task <IEnumerable <Organisation> > GetUnrelatedOrganisations(Organisation organisation)
 {
     return(await context.Organisations.Where(o => o != organisation && !o.ParentRelatedOrganisations.Contains(organisation)).ToListAsync());
 }
 public void Remove(Organisation organisation)
 {
     OrganisationRepository.Remove(organisation);
 }
        public string UpdateOrganization(Organisation orginfo)
        {
            try
            {
                UserLoginInformation loggedinUser = (UserLoginInformation)LoginController.ActiveUser;
                if (orginfo.OrganisationId == 0)
                {
                    orginfo.ModifiedById = loggedinUser.USERID.ToString();
                    orginfo.CreatedById  = loggedinUser.USERID.ToString();
                    orginfo.CreatedDate  = DateTime.Now;
                    orginfo.ModifiedDate = DateTime.Now;
                    orginfo.Status       = 1;
                    _context.Organisations.Add(orginfo);
                    _context.SaveChanges();
                }
                else
                {
                    try
                    {
                        using (TransactionScope transactionScope = new TransactionScope())
                        {
                            try
                            {
                                using (kryptoEntities1 db = new kryptoEntities1())
                                {
                                    orginfo = Updateobject(orginfo.OrganisationId, orginfo);
                                    orginfo.ModifiedById    = loggedinUser.USERID.ToString();
                                    orginfo.ModifiedDate    = DateTime.Now;
                                    db.Entry(orginfo).State = EntityState.Modified;
                                    db.SaveChanges();

                                    List <MyNode> responseNodes =
                                        JsonConvert.DeserializeObject <List <MyNode> >(orginfo.UserSelections);
                                    List <UserLoginInformation> usersInDb = new List <UserLoginInformation>();

                                    foreach (FacilityMaster @facility in orginfo.GetAssocaitedFacilities())
                                    {
                                        usersInDb.AddRange(@facility.GetAssocaitedOrganisationAdmins());
                                    }

                                    List <int> indb         = usersInDb.Select(x => x.USERID).ToList();
                                    List <int> inselections = responseNodes.Select(x => x.value).ToList();

                                    var toInclude = UserDatatablesController.ExcludedRight(indb, inselections);
                                    var toExclude = UserDatatablesController.ExcludedLeft(indb, inselections);

                                    foreach (int @in in toInclude)
                                    {
                                        UserLoginInformation current = db.UserLoginInformations.Find(@in);
                                        current.IsOrganisationAdmin = true;
                                        current.IsFacilityAdmin     = true;
                                        db.Entry(current).State     = EntityState.Modified;
                                    }
                                    foreach (int @out in toExclude)
                                    {
                                        UserLoginInformation current = db.UserLoginInformations.Find(@out);
                                        current.IsOrganisationAdmin = false;
                                        db.Entry(current).State     = EntityState.Modified;
                                    }
                                    db.SaveChanges();
                                }
                                transactionScope.Complete();
                            }
                            catch (Exception ee)
                            {
                                return("FAIL");
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        return("FAIL");
                    }
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                return("FAIL");
            }
            return("SUCESS");
        }
        public JsonResult getMatchingOrganization(int selectedOrg)
        {
            Organisation orginfo = _context.Organisations.SingleOrDefault(x => x.OrganisationId.Equals(selectedOrg) && x.Status == 1);

            return(Json(orginfo, JsonRequestBehavior.AllowGet));
        }
Beispiel #35
0
 public Organisation PostSave(Organisation org)
 {
     org          = OrganisationDbService.Instance.SaveOrganisation(org);
     org.Contacts = new ContactApiController().GetByOrganisationId(org.Id);
     return(org);
 }
Beispiel #36
0
        private void AddSampleData(SurveyContext context)
        {
            var userManager = new ApplicationUserManager(new ApplicationUserStore(context));
            var roleManager = new ApplicationRoleManager(new ApplicationRoleStore(context));

            try
            {
                Project CurrentProject = null;

                var org = new Organisation()
                {
                    Id                      = Guid.Parse("cfa81eb0-9fc7-4932-a3e8-1c822370d034"), // this is the ID on our production database
                    Name                    = "OnRecord",
                    TelNumber               = "0209390499",
                    AddressLine1            = "110 Kings road",
                    AddressLine2            = "Regent street",
                    Town                    = "London",
                    County                  = "London",
                    Postcode                = "EC23 4AD",
                    DefaultLanguageId       = LanguagesRepository.English.Id,
                    DefaultCalendarId       = CalendarsRepository.Gregorian.Id,
                    IsActive                = true,
                    SubscriptionEnabled     = true,
                    SubscriptionMonthlyRate = 6M
                };

                context.Organisations.AddOrUpdate(org);
                var user = new OrgUser()
                {
                    Id = Guid.Parse("b3c19356-d11d-48f2-a3a8-69392a7b4e7b"), OrganisationId = org.Id, IsRootUser = true, Email = "*****@*****.**", UserName = "******", TypeId = OrgUserTypesRepository.Administrator.Id, LastLogin = new DateTime(2015, 1, 1), IsWebUser = true, IsMobileUser = true
                };
                userManager.AddOrUpdateUser(user, "Test1234");

                OrgUserTypesRepository.Administrator.GetRoles().ToList().ForEach(role => userManager.AddToRole(user.Id, role));

                context.SaveChanges();
                org.RootUser = user;
                context.SaveChanges();

                CurrentProject = new Project()
                {
                    Id = Guid.Parse("cb7f09a2-1823-4f60-820e-3fedc462fe76"), Number = "123", Name = "Test Project 1", StartDate = new DateTime(2015, 1, 1), Flagged = true, OrganisationId = org.Id
                };
                context.Projects.AddOrUpdate(CurrentProject);
                context.SaveChanges();

                var dataList = new DataList()
                {
                    Id = Guid.Parse("884505e1-97c8-4602-8c00-f75ae08d99ab"), OrganisationId = org.Id, Name = "Colors"
                };
                context.DataLists.AddOrUpdate(dataList);

                context.DataListItems.AddOrUpdate(new DataListItem {
                    Id = Guid.Parse("0a138f19-2e98-4030-b9e9-78527043c1c2"), DataListId = dataList.Id, Text = "Black", Value = 0, Order = 1
                });
                context.DataListItems.AddOrUpdate(new DataListItem {
                    Id = Guid.Parse("32d75f9b-7da6-43b5-8f3f-b7830dc6e5f7"), DataListId = dataList.Id, Text = "White", Value = 1, Order = 2
                });
                context.DataListItems.AddOrUpdate(new DataListItem {
                    Id = Guid.Parse("298cdd84-4cd1-481f-875e-c2c9adce43bc"), DataListId = dataList.Id, Text = "Blue", Value = 2, Order = 3
                });
                context.DataListItems.AddOrUpdate(new DataListItem {
                    Id = Guid.Parse("8e63ad2d-6872-4e6d-86e6-55782450f991"), DataListId = dataList.Id, Text = "Red", Value = 3, Order = 4
                });

                context.SaveChanges();

                var cat = new FormTemplateCategory()
                {
                    Id = Guid.Parse("8DBFEC4D-96E0-4135-A726-D144D5707858"), Title = "Recordings", OrganisationId = org.Id
                };
                context.FormTemplateCategories.AddOrUpdate(cat);
                context.SaveChanges();

                var adviceThreadsCat = new FormTemplateCategory()
                {
                    Id = Guid.Parse("F4284C22-1FB4-4187-AD0F-B8FEB059C842"), Title = "Advice Recordings", OrganisationId = org.Id
                };
                context.FormTemplateCategories.AddOrUpdate(adviceThreadsCat);
                context.SaveChanges();

                var template = new FormTemplate()
                {
                    Id = Guid.Parse("52692cf5-fd17-4fc6-b72b-b65b7e8d4e98"), ProjectId = CurrentProject.Id, Code = "101", Title = "First Form", Description = "This is the first from.", Colour = "#ddff00", Version = 1.0, FormTemplateCategoryId = cat.Id, IsPublished = true, Discriminator = FormTemplateDiscriminators.RegularThread, OrganisationId = org.Id, CreatedById = user.Id
                };
                context.FormTemplates.AddOrUpdate(template);
                context.SaveChanges();

                var category1 = new MetricGroup()
                {
                    Id = Guid.Parse("bedb627d-155d-4807-93dd-40cbb1fa335d"), Title = "First questions", FormTemplateId = template.Id, Order = template.GetMaxGroupOrder()
                };
                template.AddGroup(category1);
                context.MetricGroups.AddOrUpdate(category1);

                var category2 = new MetricGroup()
                {
                    Id = Guid.Parse("45ca1db0-820b-4271-8f26-7a75e7e73c80"), Title = "Second questions", FormTemplateId = template.Id, Order = template.GetMaxGroupOrder()
                };
                template.AddGroup(category2);
                context.MetricGroups.AddOrUpdate(category2);

                var category3 = new MetricGroup()
                {
                    Id = Guid.Parse("0b76ee76-405a-434a-9bca-4e5b3f1eb5e7"), Title = "Third questions", FormTemplateId = template.Id, Order = template.GetMaxGroupOrder()
                };
                template.AddGroup(category3);
                context.MetricGroups.AddOrUpdate(category3);
                context.SaveChanges();

                var metric1 = new FreeTextMetric()
                {
                    Id = Guid.Parse("f6e5b494-d845-48dc-a783-e3e93b340b3a"), ShortTitle = "q1", Description = "What is the answer1", NumberOfLine = 1, MaxLength = 10, Order = category1.GetMaxMetricOrder(), Mandatory = true
                };
                category1.AddMetric(metric1);
                context.FreeTextMetrics.AddOrUpdate(metric1);

                var metric2 = new FreeTextMetric()
                {
                    Id = Guid.Parse("8a85e16c-9abb-4f99-83fc-564605bbd52f"), ShortTitle = "q2", Description = "What is the answer2", NumberOfLine = 3, Order = category1.GetMaxMetricOrder(), Mandatory = true
                };
                category1.AddMetric(metric2);
                context.FreeTextMetrics.AddOrUpdate(metric2);

                var metric3 = new FreeTextMetric()
                {
                    Id = Guid.Parse("b2f747bc-b403-47de-95c2-2efd8e1ebeb6"), ShortTitle = "q3", Description = "What is the answer3", NumberOfLine = 3, Order = category2.GetMaxMetricOrder()
                };
                category2.AddMetric(metric3);
                context.FreeTextMetrics.AddOrUpdate(metric3);

                var metric4 = new FreeTextMetric()
                {
                    Id = Guid.Parse("a8373528-0d92-4d91-bff0-5397700644c8"), ShortTitle = "q4", Description = "What is the answer4", NumberOfLine = 2, Order = category2.GetMaxMetricOrder()
                };
                category2.AddMetric(metric4);
                context.FreeTextMetrics.AddOrUpdate(metric4);

                var metric5 = new FreeTextMetric()
                {
                    Id = Guid.Parse("14531856-8b05-4711-850e-d0ac00173732"), ShortTitle = "q5", Description = "What is the answer5", NumberOfLine = 2, Order = category3.GetMaxMetricOrder()
                };
                category3.AddMetric(metric5);
                context.FreeTextMetrics.AddOrUpdate(metric5);

                var metric6 = new RateMetric()
                {
                    Id = Guid.Parse("ae9399eb-80b2-4944-be22-55b561f10bc5"), ShortTitle = "r1", Description = "What is the rate1", MinValue = 1, MaxValue = 5, DefaultValue = 1, Order = category1.GetMaxMetricOrder()
                };
                category1.AddMetric(metric6);
                context.RateMetrics.AddOrUpdate(metric6);

                var metric7 = new DateMetric()
                {
                    Id = Guid.Parse("68ce9679-14b5-4e00-97d6-38ad6db54f54"), ShortTitle = "d1", Description = "Date of Event", Order = category1.GetMaxMetricOrder(), HasTimeValue = false
                };
                category1.AddMetric(metric7);
                context.DateMetrics.AddOrUpdate(metric7);

                var metric8 = new DichotomousMetric()
                {
                    Id = Guid.Parse("e254bf53-2ddb-4817-a9d7-6d8513696a2f"), ShortTitle = "yn1", Description = "Are you ok?", Order = category1.GetMaxMetricOrder()
                };
                category1.AddMetric(metric8);
                context.DichotomousMetrics.AddOrUpdate(metric8);

                context.SaveChanges();

                // default advice thread template.
                var adviceTemplate = new FormTemplate()
                {
                    Id = Guid.Parse("780f4d2d-524f-4714-a5b2-a43c8eaff3c3"), ProjectId = CurrentProject.Id, Code = "202", Title = "Advice Form", Description = "This is the default advice form.", Colour = "#08874b", DescriptionFormat = "{{comment}}", Version = 1.0, FormTemplateCategoryId = adviceThreadsCat.Id, IsPublished = true, Discriminator = FormTemplateDiscriminators.AdviceThread, OrganisationId = org.Id, CreatedById = user.Id
                };
                context.FormTemplates.AddOrUpdate(adviceTemplate);
                context.SaveChanges();

                var adviceFormCategory1 = new MetricGroup()
                {
                    Id = Guid.Parse("3b940609-0e1c-4542-87be-f69f2b3faa79"), Title = "Advice Form", FormTemplateId = adviceTemplate.Id, Order = adviceTemplate.GetMaxGroupOrder()
                };
                adviceTemplate.AddGroup(adviceFormCategory1);
                context.MetricGroups.AddOrUpdate(adviceFormCategory1);

                var adviceFormMetric1 = new FreeTextMetric()
                {
                    Id = Guid.Parse("bbb60c5f-cc29-473f-994e-3a04d25c9b60"), ShortTitle = "Comment", Description = "Write your advice or comment here", NumberOfLine = 2, MaxLength = 500, Order = adviceFormCategory1.GetMaxMetricOrder(), Mandatory = true
                };
                adviceFormCategory1.AddMetric(adviceFormMetric1);
                context.FreeTextMetrics.AddOrUpdate(adviceFormMetric1);

                var adviceFormMetric2 = new AttachmentMetric()
                {
                    Id = Guid.Parse("a48e8139-4608-4b72-a85b-b9908714f242"), ShortTitle = "Attachments", Description = "Upload any supporting evidence or media", AllowMultipleFiles = true, Order = adviceFormCategory1.GetMaxMetricOrder()
                };
                adviceFormCategory1.AddMetric(adviceFormMetric2);
                context.AttachmentMetrics.AddOrUpdate(adviceFormMetric2);

                context.SaveChanges();

                //var data = new FilledForm() { Id = Guid.Parse("390f8abc-dc99-411a-a22f-8cf43313337a"), FormTemplateId = template.Id, ProjectId = CurrentProject.Id, FilledById = user.Id };
                //context.FilledForms.AddOrUpdate(data);

                //context.FormValues.AddOrUpdate(new FormValue() { Id = Guid.Parse("24bacf38-52ee-40e5-916c-a3f81a84eea5"), FilledFormId = data.Id, MetricId = metric1.Id, TextValue = "answer 1" });
                //context.FormValues.AddOrUpdate(new FormValue() { Id = Guid.Parse("cdb38534-f412-4397-aa1e-51a587db402f"), FilledFormId = data.Id, MetricId = metric2.Id, TextValue = "answer 2" });
                //context.FormValues.AddOrUpdate(new FormValue() { Id = Guid.Parse("b3d3dc58-5467-42ac-8d2a-3e327635a72d"), FilledFormId = data.Id, MetricId = metric3.Id, TextValue = "answer 3" });
                //context.FormValues.AddOrUpdate(new FormValue() { Id = Guid.Parse("d3efb64f-8bf1-4916-9dd0-07fc11ec171e"), FilledFormId = data.Id, MetricId = metric4.Id, TextValue = "answer 4" });
                //context.FormValues.AddOrUpdate(new FormValue() { Id = Guid.Parse("9a0e941e-f28a-4bf3-9a23-edeecf4368df"), FilledFormId = data.Id, MetricId = metric5.Id, TextValue = "answer 5" });
                //context.FormValues.AddOrUpdate(new FormValue() { Id = Guid.Parse("a00e12d0-92a5-4737-9dd3-b83f8a71e320"), FilledFormId = data.Id, MetricId = metric6.Id, NumericValue = 3 });
                //context.FormValues.AddOrUpdate(new FormValue() { Id = Guid.Parse("b2f46bdc-f987-4a2d-bcc7-bb7c4f592f21"), FilledFormId = data.Id, MetricId = metric7.Id, DateValue = DateTime.Now });
                //context.FormValues.AddOrUpdate(new FormValue() { Id = Guid.Parse("747a6bbf-c439-40e4-a76e-d03b68ed1614"), FilledFormId = data.Id, MetricId = metric8.Id, BoolValue = true });

                //context.SaveChanges();

                var reportCat = new ReportTemplateCategory()
                {
                    Id = Guid.Parse("00b2ea95-dcaf-480a-b470-6d012a5f1d6e"), OrganisationId = org.Id, Title = "First report category"
                };
                context.ReportTemplateCategories.AddOrUpdate(reportCat);

                var reportTemplate = new ReportTemplate()
                {
                    Id = Guid.Parse("04d3727c-738a-44b7-952d-7c74e2383c4b"), OrganisationId = org.Id, Name = "First sample report", CategoryId = reportCat.Id, Description = "", IsPublished = true
                };
                context.ReportTemplates.AddOrUpdate(reportTemplate);

                context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
        }
        public Organisation FindOrganisationById(int organisationId)
        {
            Organisation organisation = DbContext.Organisations.Find(organisationId);

            return(organisation);
        }
 public void SaveNewOrganisation(Organisation organisation)
 {
     DbContext.Organisations.Add(organisation);
     DbContext.SaveChanges();
 }
        public static int Save(Organisation org)
        {
            int           rowsaffected = 0;
            DbTransaction trans        = null;

            try
            {
                trans = Database.BeginTransaction(cs);

                if (org.ID == 0)
                {
                    string sql =
                        @"INSERT INTO Organisation 
(OrganisationName, Address, Email, Phone, Login, Password, DbName, DbLogin, DbPassword)
VALUES (@Org, @Address, @Email, @Phone, @Login, @Password, @DbName, @DbLogin, @DbPassword)";

                    DbParameter par1 = Database.AddParameter(cs, "@Org", org.OrganisationName);
                    DbParameter par2 = Database.AddParameter(cs, "@Address", org.Address);
                    DbParameter par3 = Database.AddParameter(cs, "@Email", org.Email);
                    DbParameter par4 = Database.AddParameter(cs, "@Phone", org.Phone);
                    DbParameter par5 = Database.AddParameter(cs, "@Login", Cryptography.Encrypt(org.Login));
                    DbParameter par6 = Database.AddParameter(cs, "@Password", Cryptography.Encrypt(org.Password));
                    DbParameter par7 = Database.AddParameter(cs, "@DbName", Cryptography.Encrypt(org.DbName));
                    DbParameter par8 = Database.AddParameter(cs, "@DbLogin", Cryptography.Encrypt(org.DbLogin));
                    DbParameter par9 = Database.AddParameter(cs, "@DbPassword", Cryptography.Encrypt(org.DbPassword));
                    rowsaffected += Database.InsertData(trans, sql, par1, par2, par3, par4, par5, par6, par7, par8, par9);

                    org.ID = rowsaffected;
                    CreateDatabase(org);
                }
                else
                {
                    DbParameter parPass = null;
                    string      sql     = "UPDATE Organisation SET Login = @Login, OrganisationName = @Org, Address = @Address, Email = @Email, Phone = @Phone";

                    if (org.Password != null)
                    {
                        sql    += ", Password = @Password";
                        parPass = Database.AddParameter(cs, "@Password", Cryptography.Encrypt(org.Password));
                    }

                    sql += " WHERE ID = @ID";

                    DbParameter par1 = Database.AddParameter(cs, "@ID", org.ID);
                    DbParameter par2 = Database.AddParameter(cs, "@Login", Cryptography.Encrypt(org.Login));
                    DbParameter par3 = Database.AddParameter(cs, "@Org", org.OrganisationName);
                    DbParameter par4 = Database.AddParameter(cs, "@Address", org.Address);
                    DbParameter par5 = Database.AddParameter(cs, "@Email", org.Email);
                    DbParameter par6 = Database.AddParameter(cs, "@Phone", org.Phone);
                    rowsaffected += Database.ModifyData(trans, sql, par1, par2, par3, par4, par5, par6, parPass);
                }

                trans.Commit();
            }
            catch (Exception)
            {
                if (trans != null)
                {
                    trans.Rollback();
                }
            }
            finally
            {
                if (trans != null)
                {
                    Database.ReleaseConnection(trans.Connection);
                }
            }

            return(rowsaffected);
        }
        /// <summary>
        /// Update a Organisation
        /// </summary>
        /// <param name="currentUser"></param>
        /// <param name="user"></param>
        /// <param name="appID"></param>
        /// <param name="overrideID"></param>
        /// <param name="code"></param>
        /// <param name="lockID"></param>
        /// <param name="dataRepository"></param>
        /// <param name="uow"></param>
        public void DeleteOrganisation(string currentUser, string user, string appID, string overrideID, string code, string lockID, IRepository <Organisation> dataRepository, IUnitOfWork uow, IExceptionManager exceptionManager, IMappingService mappingService)
        {
            try
            {
                #region Parameter validation

                // Validate parameters
                if (string.IsNullOrEmpty(currentUser))
                {
                    throw new ArgumentOutOfRangeException("currentUser");
                }
                if (string.IsNullOrEmpty(user))
                {
                    throw new ArgumentOutOfRangeException("user");
                }
                if (string.IsNullOrEmpty(appID))
                {
                    throw new ArgumentOutOfRangeException("appID");
                }
                if (string.IsNullOrEmpty(code))
                {
                    throw new ArgumentOutOfRangeException("code");
                }
                if (string.IsNullOrEmpty(lockID))
                {
                    throw new ArgumentOutOfRangeException("lockID");
                }
                if (null == dataRepository)
                {
                    throw new ArgumentOutOfRangeException("dataRepository");
                }
                if (null == uow)
                {
                    throw new ArgumentOutOfRangeException("uow");
                }
                if (null == exceptionManager)
                {
                    throw new ArgumentOutOfRangeException("exceptionManager");
                }
                if (null == mappingService)
                {
                    throw new ArgumentOutOfRangeException("mappingService");
                }

                #endregion

                using (uow)
                {
                    // Convert string to guid
                    Guid codeGuid = Guid.Parse(code);

                    // Find item based on ID
                    Organisation dataEntity = dataRepository.Single(x => x.Code == codeGuid);

                    // Delete the item
                    dataRepository.Delete(dataEntity);

                    // Commit unit of work
                    uow.Commit();
                }
            }
            catch (Exception e)
            {
                //Prevent exception from propogating across the service interface
                exceptionManager.ShieldException(e);
            }
        }
        /// <summary>
        /// Retrieve a Organisation with associated lookups
        /// </summary>
        /// <param name="currentUser"></param>
        /// <param name="user"></param>
        /// <param name="appID"></param>
        /// <param name="overrideID"></param>
        /// <param name="code"></param>
        /// <param name="dataRepository"></param>
        /// <param name="uow"></param>
        /// <returns></returns>
        public OrganisationVMDC GetOrganisation(string currentUser, string user, string appID, string overrideID, string code, IUnitOfWork uow, IRepository <Organisation> dataRepository
                                                , IRepository <OrganisationType> organisationTypeRepository
                                                , IExceptionManager exceptionManager, IMappingService mappingService)

        {
            try
            {
                #region Parameter validation

                // Validate parameters
                if (string.IsNullOrEmpty(currentUser))
                {
                    throw new ArgumentOutOfRangeException("currentUser");
                }
                if (string.IsNullOrEmpty(user))
                {
                    throw new ArgumentOutOfRangeException("user");
                }
                if (string.IsNullOrEmpty(appID))
                {
                    throw new ArgumentOutOfRangeException("appID");
                }
                if (null == dataRepository)
                {
                    throw new ArgumentOutOfRangeException("dataRepository");
                }
                if (null == uow)
                {
                    throw new ArgumentOutOfRangeException("uow");
                }
                if (null == exceptionManager)
                {
                    throw new ArgumentOutOfRangeException("exceptionManager");
                }
                if (null == mappingService)
                {
                    throw new ArgumentOutOfRangeException("mappingService");
                }

                #endregion

                using (uow)
                {
                    OrganisationDC destination = null;

                    // If code is null then just return supporting lists
                    if (!string.IsNullOrEmpty(code))
                    {
                        // Convert code to Guid
                        Guid codeGuid = Guid.Parse(code);

                        // Retrieve specific Organisation
                        Organisation dataEntity = dataRepository.Single(x => x.Code == codeGuid);

                        // Convert to data contract for passing through service interface
                        destination = mappingService.Map <Organisation, OrganisationDC>(dataEntity);
                    }

                    IEnumerable <OrganisationType> organisationTypeList = organisationTypeRepository.GetAll(x => x.Name);

                    List <OrganisationTypeDC> organisationTypeDestinationList = mappingService.Map <List <OrganisationTypeDC> >(organisationTypeList);

                    // Create aggregate contract
                    OrganisationVMDC returnObject = new OrganisationVMDC();

                    returnObject.OrganisationItem     = destination;
                    returnObject.OrganisationTypeList = organisationTypeDestinationList;

                    return(returnObject);
                }
            }
            catch (Exception e)
            {
                //Prevent exception from propogating across the service interface
                exceptionManager.ShieldException(e);

                return(null);
            }
        }
Beispiel #42
0
 public void Restore(Organisation org)
 {
     org.Archived = false;
     DbService.db().Save(org);
 }
Beispiel #43
0
 public void Archive(Organisation org)
 {
     org.Archived = true;
     DbService.db().Save(org);
 }
Beispiel #44
0
        void CreateTestData(int recordCount = 500, int yearCount = 3)
        {
            var organisations = DataRepository.GetAll <Organisation>();
            var sicCodes      = DataRepository.GetAll <SicCode>();

            while (organisations.Count() < recordCount)
            {
                var    sector       = Numeric.Rand(0, 1) == 0 ? SectorTypes.Private : SectorTypes.Public;
                string searchText   = Text.AlphabetChars[Numeric.Rand(0, 1)].ToString();
                var    organisation = new Organisation();
                PagedResult <EmployerRecord> result;
                if (sector == SectorTypes.Public)
                {
                    try
                    {
                        result = PublicSectorRepository.Search(searchText, Numeric.Rand(1, recordCount), 10);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                    if (result == null || result.RowCount == 0 || result.Results == null || result.Results.Count == 0)
                    {
                        continue;
                    }
                    foreach (var employer in result.Results)
                    {
                        if (organisations.Any(o => o.OrganisationName == employer.Name))
                        {
                            continue;
                        }
                        organisation = new Organisation();
                        organisation.OrganisationName = employer.Name;
                        organisation.SectorType       = sector;
                        organisation.Status           = OrganisationStatuses.Active;
                        organisation.StatusDetails    = "TEST DATA";
                        DataRepository.Insert(organisation);
                        DataRepository.SaveChanges();

                        DataRepository.Insert(new OrganisationAddress()
                        {
                            OrganisationId = organisation.OrganisationId,
                            Address1       = "Address line " + organisation.OrganisationId,
                            Address3       = "City" + organisation.OrganisationId,
                            Country        = "Country" + organisation.OrganisationId,
                            PostCode       = "Post Code" + organisation.OrganisationId,
                            Status         = AddressStatuses.Active
                        });

                        employer.SicCodes = PublicSectorRepository.GetSicCodes(employer.CompanyNumber);

                        foreach (var sicCode in employer.SicCodes.SplitI())
                        {
                            var code = sicCode.ToInt32();
                            if (!sicCodes.Any(s => s.SicCodeId == code))
                            {
                                MvcApplication.WarningLog.WriteLine($"Invalid SIC code '{code}' received from companies house");
                                continue;
                            }
                            if (organisation.OrganisationSicCodes.Any(a => a.SicCodeId == code))
                            {
                                continue;
                            }
                            DataRepository.Insert(new OrganisationSicCode()
                            {
                                OrganisationId = organisation.OrganisationId,
                                SicCodeId      = code
                            });
                        }
                        DataRepository.SaveChanges();
                    }
                }
                else if (sector == SectorTypes.Private)
                {
                    try
                    {
                        result = PrivateSectorRepository.Search(searchText, Numeric.Rand(1, recordCount), 10);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                    if (result == null || result.RowCount == 0 || result.Results == null || result.Results.Count == 0)
                    {
                        continue;
                    }
                    foreach (var employer in result.Results)
                    {
                        if (organisations.Any(o => o.OrganisationName == employer.Name))
                        {
                            continue;
                        }
                        organisation = new Organisation();
                        organisation.OrganisationName       = employer.Name;
                        organisation.SectorType             = sector;
                        organisation.Status                 = OrganisationStatuses.Active;
                        organisation.StatusDetails          = "TEST DATA";
                        organisation.PrivateSectorReference = employer.CompanyNumber;
                        DataRepository.Insert(organisation);
                        DataRepository.SaveChanges();

                        DataRepository.Insert(new OrganisationAddress()
                        {
                            OrganisationId = organisation.OrganisationId,
                            Address1       = employer.Address1,
                            Address2       = employer.Address2,
                            Address3       = employer.Address3,
                            Country        = employer.Country,
                            PostCode       = employer.PostCode,
                            PoBox          = employer.PoBox,
                            Status         = AddressStatuses.Active
                        });

                        employer.SicCodes = PrivateSectorRepository.GetSicCodes(employer.CompanyNumber);

                        foreach (var sicCode in employer.SicCodes.SplitI())
                        {
                            var code = sicCode.ToInt32();
                            if (!sicCodes.Any(s => s.SicCodeId == code))
                            {
                                MvcApplication.WarningLog.WriteLine($"Invalid SIC code '{code}' received from companies house");
                                continue;
                            }
                            if (organisation.OrganisationSicCodes.Any(a => a.SicCodeId == code))
                            {
                                continue;
                            }
                            DataRepository.Insert(new OrganisationSicCode()
                            {
                                OrganisationId = organisation.OrganisationId,
                                SicCodeId      = code
                            });
                        }
                        DataRepository.SaveChanges();
                    }
                }
            }

            foreach (var organisation in organisations.ToList())
            {
                for (var year = DateTime.Now.Year; year >= (DateTime.Now.Year - yearCount); year--)
                {
                    var returns        = organisation.Returns.ToList();
                    var accountingDate = GetAccountYearStartDate(organisation.SectorType, year);
                    var @return        = returns.FirstOrDefault(r => r.AccountingDate == accountingDate);
                    if (@return != null)
                    {
                        continue;
                    }
                    DataRepository.Insert(new Return()
                    {
                        OrganisationId              = organisation.OrganisationId,
                        AccountingDate              = accountingDate,
                        Status                      = ReturnStatuses.Submitted,
                        StatusDate                  = accountingDate.AddDays(Numeric.Rand(0, 365)),
                        CompanyLinkToGPGInfo        = "https://" + organisation.OrganisationName.ReplaceI(" ", "") + ".co.uk/GPGData",
                        DiffMeanBonusPercent        = Numeric.Rand(0, 100),
                        DiffMeanHourlyPayPercent    = Numeric.Rand(0, 100),
                        DiffMedianBonusPercent      = Numeric.Rand(0, 100),
                        DiffMedianHourlyPercent     = Numeric.Rand(0, 100),
                        FemaleLowerPayBand          = Numeric.Rand(0, 100),
                        FemaleMedianBonusPayPercent = Numeric.Rand(0, 100),
                        FemaleMiddlePayBand         = Numeric.Rand(0, 100),
                        FemaleUpperPayBand          = Numeric.Rand(0, 100),
                        FemaleUpperQuartilePayBand  = Numeric.Rand(0, 100),
                        FirstName                   = "Firstname" + organisation.OrganisationId,
                        LastName                    = "Lastname" + organisation.OrganisationId,
                        JobTitle                    = "Jobtitle " + organisation.OrganisationId,
                        MaleLowerPayBand            = Numeric.Rand(0, 100),
                        MaleMedianBonusPayPercent   = Numeric.Rand(0, 100),
                        MaleUpperQuartilePayBand    = Numeric.Rand(0, 100),
                        MaleMiddlePayBand           = Numeric.Rand(0, 100),
                        MaleUpperPayBand            = Numeric.Rand(0, 100)
                    });
                }
            }
            DataRepository.SaveChanges();
        }
        public ActionResult Result(int currentrecord)
        {
            Organisation currentOrganisation = _context.Organisations.Find(currentrecord);
            List <int>   participantsIds     = null;

            if (currentrecord != 0)
            {
                List <UserLoginInformation> usersInDb = new List <UserLoginInformation>();

                foreach (FacilityMaster @facility in currentOrganisation.GetAssocaitedFacilities())
                {
                    usersInDb.AddRange(@facility.GetAssocaitedOrganisationAdmins());
                }

                participantsIds = usersInDb.Select(x => x.USERID).ToList();
            }
            List <MyNode> nodes = new List <MyNode>();

            MyOrganisation @org = new MyOrganisation();

            @org.Name  = currentOrganisation.Name;
            @org.Value = currentOrganisation.OrganisationId;

            MyNode orgNode = new MyNode
            {
                text      = org.Name,
                value     = org.Value,
                icon      = "glyphicon glyphicon-home",
                backColor = "#ffffff",
                color     = "#428bca",
                //state = new state() { @checked = true, disabled = false, expanded = true, selected = false },
                nodetype = MyNodeType.Organisation
            };
            List <MyFacility> facilities = @org.GetAllMatchingFacilities();

            if (facilities != null && facilities.Count > 0)
            {
                orgNode.nodes = new List <MyNode>();
                foreach (MyFacility @fac in facilities)
                {
                    MyNode facNode = new MyNode
                    {
                        parent    = orgNode.value,
                        text      = fac.Name,
                        value     = fac.Value,
                        icon      = "glyphicon glyphicon-th-list",
                        backColor = "#ffffff",
                        color     = "#66512c",
                        //state = new state() { @checked = true, disabled = false, expanded = true, selected = false },
                        nodetype = MyNodeType.Facility
                    };
                    List <MyUser> users = @fac.GetAllMatchingUsers();
                    if (users != null && users.Count > 0)
                    {
                        facNode.nodes = new List <MyNode>();
                        foreach (MyUser @user in users)
                        {
                            MyNode userNode = new MyNode
                            {
                                parent    = facNode.value,
                                text      = user.Name,
                                value     = user.Value,
                                icon      = "glyphicon glyphicon-user",
                                backColor = "#ffffff",
                                color     = "#31708f",
                                nodetype  = MyNodeType.User
                            };
                            if (ChatGroupController.CheckIfMatchingMyUserExists(participantsIds, userNode) != null)
                            {
                                userNode.state = new state
                                {
                                    @checked = true,
                                    disabled = false,
                                    expanded = true,
                                    selected = false
                                };
                            }

                            facNode.nodes.Add(userNode);
                        }
                    }
                    if (users.Count > 0)
                    {
                        orgNode.nodes.Add(facNode);
                    }
                }
            }
            if (facilities.Count > 0 && orgNode.nodes.Count > 0)
            {
                nodes.Add(orgNode);
            }
            return(Json(nodes, JsonRequestBehavior.AllowGet));
        }
 public void Add(Organisation organisation)
 {
     OrganisationRepository.Add(organisation);
 }
        public Organisation Updateobject(int id, Organisation filled)
        {
            Organisation obj = _context.Organisations.Find(id);

            PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in props)
            {
                object currentprop = prop.GetValue(filled);
                if (currentprop is Int32)
                {
                    int currentint = (int)currentprop;
                    if (currentint == 0)
                    {
                        prop.SetValue(filled, prop.GetValue(obj), null);
                    }
                }
                else if (currentprop is Int16)
                {
                    Int16 currentInt16 = (Int16)currentprop;
                    if (currentInt16 == 0)
                    {
                        prop.SetValue(filled, prop.GetValue(obj), null);
                    }
                }
                else if (currentprop is Byte)
                {
                    Byte currentByte = (Byte)currentprop;
                    if (currentByte == 0)
                    {
                        prop.SetValue(filled, prop.GetValue(obj), null);
                    }
                }
                else if (currentprop is Boolean)
                {
                    Boolean currentBoolean = (Boolean)currentprop;
                    if (currentBoolean == (Boolean)prop.GetValue(obj))
                    {
                        prop.SetValue(filled, prop.GetValue(obj), null);
                    }
                }
                else if (currentprop is String)
                {
                    prop.SetValue(filled, (String)currentprop, null);
                }
                else if (currentprop is DateTime)
                {
                    DateTime currentDateTime = (DateTime)currentprop;
                    if (currentDateTime == new DateTime())
                    {
                        prop.SetValue(filled, prop.GetValue(obj), null);
                    }
                }
                else
                {
                    if (currentprop == null)
                    {
                        prop.SetValue(filled, prop.GetValue(obj), null);
                    }
                }
            }
            return(filled);
        }
Beispiel #48
0
        public void OrganisationMarkedAsDemoTest()
        {
            Organisation organisation = Api.Organisation;

            Assert.IsTrue((bool)organisation.IsDemoCompany, "Demo Organisation was not marked as Demo");
        }
        public async Task <IActionResult> ReviewRequest(OrganisationViewModel model, string command)
        {
            //Ensure user has completed the registration process
            var checkResult = await CheckUserRegisteredOkAsync();

            if (checkResult != null)
            {
                return(checkResult);
            }

            //Make sure we can load employers from session
            var m = UnstashModel <OrganisationViewModel>();

            if (m == null)
            {
                return(View("CustomError", WebService.ErrorViewModelFactory.Create(1112)));
            }

            model.ManualEmployers = m.ManualEmployers;

            //Unwrap code
            UserOrganisation userOrg;
            var result = UnwrapRegistrationRequest(model, out userOrg, true);

            if (result != null)
            {
                return(result);
            }

            //Check model is valid

            //Exclude the address details
            var excludes = new HashSet <string>();

            excludes.AddRange(
                nameof(model.Address1),
                nameof(model.Address2),
                nameof(model.Address3),
                nameof(model.City),
                nameof(model.County),
                nameof(model.Country),
                nameof(model.Postcode),
                nameof(model.PoBox));

            //Exclude the contact details
            excludes.AddRange(
                nameof(model.ContactFirstName),
                nameof(model.ContactLastName),
                nameof(model.ContactJobTitle),
                nameof(model.ContactEmailAddress),
                nameof(model.ContactPhoneNumber));

            //Exclude the SIC Codes
            excludes.Add(nameof(model.SicCodeIds));

            excludes.Add(nameof(model.SearchText));
            excludes.Add(nameof(model.OrganisationName));
            excludes.AddRange(
                nameof(model.CompanyNumber),
                nameof(model.CharityNumber),
                nameof(model.MutualNumber),
                nameof(model.OtherName),
                nameof(model.OtherValue));

            //Exclude the DUNS number when declining
            if (command.EqualsI("decline"))
            {
                excludes.Add(nameof(model.DUNSNumber));
            }

            ModelState.Exclude(excludes.ToArray());

            if (!ModelState.IsValid)
            {
                this.CleanModelErrors <OrganisationViewModel>();
                return(View(nameof(ReviewRequest), model));
            }

            if (command.EqualsI("decline"))
            {
                result = RedirectToAction("ConfirmCancellation");
            }
            else if (command.EqualsI("approve"))
            {
                //Check for DUNS number conflicts
                Organisation conflictOrg = null;
                if (!string.IsNullOrWhiteSpace(model.DUNSNumber))
                {
                    conflictOrg = await SharedBusinessLogic.DataRepository.GetAll <Organisation>()
                                  .FirstOrDefaultAsync(
                        o => userOrg.OrganisationId != o.OrganisationId &&
                        o.DUNSNumber.ToLower() == model.DUNSNumber.ToLower());

                    if (conflictOrg != null)
                    {
                        ModelState.AddModelError(3030, nameof(model.DUNSNumber));
                    }
                }

                //Check for company number conflicts
                if (!string.IsNullOrWhiteSpace(model.CompanyNumber))
                {
                    conflictOrg = await SharedBusinessLogic.DataRepository.GetAll <Organisation>()
                                  .FirstOrDefaultAsync(
                        o => userOrg.OrganisationId != o.OrganisationId &&
                        o.CompanyNumber.ToLower() == model.CompanyNumber.ToLower());

                    if (conflictOrg != null)
                    {
                        ModelState.AddModelError(
                            3031,
                            nameof(model.CompanyNumber),
                            new { organisationName = conflictOrg.OrganisationName, referenceName = "Company number" });
                    }
                }

                //Check for charity number conflicts
                if (!string.IsNullOrWhiteSpace(model.CharityNumber))
                {
                    var orgRef = await SharedBusinessLogic.DataRepository.GetAll <OrganisationReference>()
                                 .FirstOrDefaultAsync(
                        o => userOrg.OrganisationId != o.OrganisationId &&
                        o.ReferenceName.ToLower() == nameof(model.CharityNumber).ToLower() &&
                        o.ReferenceValue.ToLower() == model.CharityNumber.ToLower());

                    conflictOrg = orgRef?.Organisation;
                    if (conflictOrg != null)
                    {
                        ModelState.AddModelError(
                            3031,
                            nameof(model.CharityNumber),
                            new { organisationName = conflictOrg.OrganisationName, referenceName = "Charity number" });
                    }
                }

                //Check for mutual number conflicts
                if (!string.IsNullOrWhiteSpace(model.MutualNumber))
                {
                    var orgRef = await SharedBusinessLogic.DataRepository.GetAll <OrganisationReference>()
                                 .FirstOrDefaultAsync(
                        o => userOrg.OrganisationId != o.OrganisationId &&
                        o.ReferenceName.ToLower() == nameof(model.MutualNumber).ToLower() &&
                        o.ReferenceValue.ToLower() == model.MutualNumber.ToLower());

                    conflictOrg = orgRef?.Organisation;
                    if (conflictOrg != null)
                    {
                        ModelState.AddModelError(
                            3031,
                            nameof(model.MutualNumber),
                            new
                        {
                            organisationName = conflictOrg.OrganisationName,
                            referenceName    = "Mutual partnership number"
                        });
                    }
                }

                //Check for other reference conflicts
                if (!string.IsNullOrWhiteSpace(model.OtherValue))
                {
                    var orgRef = await SharedBusinessLogic.DataRepository.GetAll <OrganisationReference>()
                                 .FirstOrDefaultAsync(
                        o => userOrg.OrganisationId != o.OrganisationId &&
                        o.ReferenceName.ToLower() == model.OtherName.ToLower() &&
                        o.ReferenceValue.ToLower() == model.OtherValue.ToLower());

                    conflictOrg = orgRef?.Organisation;
                    if (conflictOrg != null)
                    {
                        ModelState.AddModelError(
                            3031,
                            nameof(model.OtherValue),
                            new { organisationName = conflictOrg.OrganisationName, referenceName = model.OtherValue });
                    }
                }

                if (!ModelState.IsValid)
                {
                    this.CleanModelErrors <OrganisationViewModel>();
                    return(View("ReviewRequest", model));
                }

                //Activate the org user
                userOrg.PINConfirmedDate = VirtualDateTime.Now;

                //Activate the organisation
                userOrg.Organisation.SetStatus(
                    OrganisationStatuses.Active,
                    OriginalUser == null ? VirtualUser.UserId : OriginalUser.UserId,
                    "Manually registered");

                // Save the DUNS Number
                if (string.IsNullOrWhiteSpace(userOrg.Organisation.DUNSNumber) &&
                    !string.IsNullOrWhiteSpace(model.DUNSNumber))
                {
                    userOrg.Organisation.DUNSNumber = model.DUNSNumber;
                }

                //Delete the DUNS reference
                if (model.IsDUNS && userOrg.Organisation.DUNSNumber == model.OtherValue)
                {
                    var dunsRef =
                        userOrg.Organisation.OrganisationReferences.FirstOrDefault(r =>
                                                                                   r.ReferenceName == nameof(model.OtherName));
                    if (dunsRef != null)
                    {
                        userOrg.Organisation.OrganisationReferences.Remove(dunsRef);
                    }
                }

                //Set the latest registration
                userOrg.Organisation.LatestRegistration = userOrg;

                // save any sic codes
                if (!string.IsNullOrEmpty(model.SicCodeIds))
                {
                    var newSicCodes = model.SicCodeIds.Split(',').Cast <int>().OrderBy(sc => sc);
                    foreach (var sc in newSicCodes)
                    {
                        userOrg.Organisation.OrganisationSicCodes.Add(
                            new OrganisationSicCode
                        {
                            SicCodeId = sc, OrganisationId = userOrg.OrganisationId, Created = VirtualDateTime.Now
                        });
                    }
                }

                //Retire the old address
                if (userOrg.Organisation.LatestAddress != null &&
                    userOrg.Organisation.LatestAddress.AddressId != userOrg.Address.AddressId)
                {
                    userOrg.Organisation.LatestAddress.SetStatus(
                        AddressStatuses.Retired,
                        OriginalUser == null ? VirtualUser.UserId : OriginalUser.UserId,
                        "Replaced by Manual registration");
                }

                //Activate the address
                userOrg.Address.SetStatus(
                    AddressStatuses.Active,
                    OriginalUser == null ? VirtualUser.UserId : OriginalUser.UserId,
                    "Manually registered");
                userOrg.Organisation.LatestAddress = userOrg.Address;

                //Send the approved email to the applicant
                if (!await SendRegistrationAcceptedAsync(
                        userOrg.User.ContactEmailAddress.Coalesce(userOrg.User.EmailAddress),
                        userOrg.User.EmailAddress.StartsWithI(SharedBusinessLogic.SharedOptions.TestPrefix)))
                {
                    ModelState.AddModelError(1132);
                    this.CleanModelErrors <OrganisationViewModel>();
                    return(View("ReviewRequest", model));
                }

                //Log the approval
                if (!userOrg.User.EmailAddress.StartsWithI(SharedBusinessLogic.SharedOptions.TestPrefix))
                {
                    await _adminService.RegistrationLog.WriteAsync(
                        new RegisterLogModel
                    {
                        StatusDate          = VirtualDateTime.Now,
                        Status              = "Manually registered",
                        ActionBy            = VirtualUser.EmailAddress,
                        Details             = "",
                        Sector              = userOrg.Organisation.SectorType,
                        Organisation        = userOrg.Organisation.OrganisationName,
                        CompanyNo           = userOrg.Organisation.CompanyNumber,
                        Address             = userOrg?.Address.GetAddressString(),
                        SicCodes            = userOrg.Organisation.GetLatestSicCodeIdsString(),
                        UserFirstname       = userOrg.User.Firstname,
                        UserLastname        = userOrg.User.Lastname,
                        UserJobtitle        = userOrg.User.JobTitle,
                        UserEmail           = userOrg.User.EmailAddress,
                        ContactFirstName    = userOrg.User.ContactFirstName,
                        ContactLastName     = userOrg.User.ContactLastName,
                        ContactJobTitle     = userOrg.User.ContactJobTitle,
                        ContactOrganisation = userOrg.User.ContactOrganisation,
                        ContactPhoneNumber  = userOrg.User.ContactPhoneNumber
                    });
                }

                //Show confirmation
                if (VirtualUser.EmailAddress.StartsWithI(SharedBusinessLogic.SharedOptions.TestPrefix))
                {
                    TempData["TestUrl"] = Url.Action("Impersonate", "Admin",
                                                     new { emailAddress = userOrg.User.EmailAddress });
                }

                result = RedirectToAction("RequestAccepted");
            }
            else
            {
                return(new HttpBadRequestResult($"Invalid command on '{command}'"));
            }

            //Save the changes and redirect
            await SharedBusinessLogic.DataRepository.SaveChangesAsync();

            //Send notification email to existing users
            _adminService.SharedBusinessLogic.NotificationService.SendUserAddedEmailToExistingUsers(userOrg.Organisation,
                                                                                                    userOrg.User);

            //Ensure the organisation has an employer reference
            if (userOrg.PINConfirmedDate.HasValue && string.IsNullOrWhiteSpace(userOrg.Organisation.EmployerReference))
            {
                await _adminService.OrganisationBusinessLogic.SetUniqueEmployerReferenceAsync(userOrg.Organisation);
            }

            //Add or remove this organisation to/from the search index
            await _adminService.SearchBusinessLogic.UpdateSearchIndexAsync(userOrg.Organisation);

            //Save the model for the redirect
            StashModel(model);

            return(result);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Utilities.SetNoCache(Response);
        }

        try
        {
            if (Session == null || Session["DB"] == null)
            {
                throw new SessionTimedOutException();
            }

            string type       = Request.QueryString["type"];
            string id         = Request.QueryString["staff"];
            string weekday    = Request.QueryString["weekday"];
            string start_time = Request.QueryString["start_time"];
            string end_time   = Request.QueryString["end_time"];
            string outside    = Request.QueryString["outside"];

            if (type == null || (type != "provider" && type != "org") ||
                id == null || (id != "-1" && !Regex.IsMatch(id, @"^\d+$")) ||
                weekday == null || (weekday != "monday" && weekday != "tuesday" && weekday != "wednesday" && weekday != "thursday" && weekday != "friday" && weekday != "saturday" && weekday != "sunday") ||
                start_time == null || !Regex.IsMatch(start_time, @"^\d{4}$") ||
                end_time == null || !Regex.IsMatch(end_time, @"^\d{4}$") ||
                outside == null || (outside != "0" && outside != "1"))
            {
                throw new CustomMessageException();
            }


            Organisation org   = type == "org" ? OrganisationDB.GetByID(Convert.ToInt32(id)) : null;
            Staff        staff = type == "provider" ? StaffDB.GetByID(Convert.ToInt32(id)) : null;

            if ((type == "provider" && staff == null) ||
                (type == "org" && org == null))
            {
                throw new CustomMessageException();
            }

            Booking[] bookings     = BookingDB.GetFutureBookings(staff, org, weekday, ConvertToTimeSpan(start_time), ConvertToTimeSpan(end_time), Request.QueryString["outside"] == "1");
            string    bookingDates = string.Empty;
            for (int i = 0; i < bookings.Length; i++)
            {
                bookingDates += bookings[i].DateStart.ToString(@"ddd MMM d yyy HH:mm") + ",";
            }

            if (bookingDates.Length > 0)
            {
                Response.Write(bookingDates.Substring(0, bookingDates.Length - 1));
            }
            else
            {
                Response.Write("NONE");
            }
        }
        catch (SessionTimedOutException)
        {
            Utilities.UnsetSessionVariables();
            Response.Write("SessionTimedOutException");
        }
        catch (Exception ex)
        {
            Response.Write("Exception: " + (Utilities.IsDev() ? ex.ToString() : "Error - please contact system administrator."));
        }
    }
Beispiel #51
0
        public void OneTimeSetUp()
        {
            this.accounts      = FakeServiceFactory.Create <Account>();
            this.organisations = FakeServiceFactory.Create <Organisation>();
            this.sessions      = FakeServiceFactory.Create <Session>();
            this.subthemes     = FakeServiceFactory.Create <Subtheme>();
            this.themes        = FakeServiceFactory.Create <Theme>();

            this.unauthorized = "unauthorizedusersecret";
            this.authorized   = "authorizedusersecret";

            Account account1 = new Account("*****@*****.**", "name1", "surname1", "picture1", this.authorized)
            {
                Organisations         = new List <Organisation>(),
                OrganisedSessions     = new List <Session>(),
                ParticipatingSessions = new List <Session>(),
                Subthemes             = new List <Subtheme>(),
                Themes = new List <Theme>()
            };

            account1 = this.accounts.Add(account1);
            Account account2 = new Account("*****@*****.**", "name2", "surname2", "picture2", this.unauthorized);

            account2 = this.accounts.Add(account2);

            Organisation organisation = new Organisation("name", account1.Id)
            {
                Sessions = new List <Session>(),
                Themes   = new List <Theme>()
            };

            organisation = this.organisations.Add(organisation);
            account1.Organisations.Add(organisation);
            this.accounts.Change(account1);

            Theme theme = new Theme("name", "descr", organisation.Id, organisation.OrganiserId, "tag")
            {
                Subthemes = new List <Subtheme>()
            };

            theme = this.themes.Add(theme);
            organisation.Themes.Add(theme);
            this.organisations.Change(organisation);
            account1.Themes.Add(theme);
            this.accounts.Change(account1);

            Subtheme subtheme = new Subtheme("name", theme.OrganiserId, theme.Id)
            {
                Sessions = new List <Session>()
            };

            subtheme = this.subthemes.Add(subtheme);
            theme.Subthemes.Add(subtheme);
            this.themes.Change(theme);
            account1.Subthemes.Add(subtheme);
            this.accounts.Change(account1);

            Session session = new Session(true, 0, "descr", false, 10, 10, organisation.Id, 0, subtheme.Id, DateTime.Now, DateTime.Now.AddDays(5))
            {
                Organisers   = new List <Account>(),
                Participants = new List <Account>()
            };

            session = this.sessions.Add(session);
            subtheme.Sessions.Add(session);
            this.subthemes.Change(subtheme);
            account1.OrganisedSessions.Add(session);
            session.Organisers.Add(account1);
            account1.ParticipatingSessions.Add(session);
            session.Participants.Add(account1);
            this.accounts.Change(account1);
            this.sessions.Change(session);
        }
Beispiel #52
0
 public static ErrorType WithOrganisation(this ErrorType errorType, Organisation organisation)
 {
     errorType.Organisation = organisation;
     return(errorType);
 }
Beispiel #53
0
        private static bool OrganisationIsNewThisYearAndHasNotProvidedScopeForLastYear(Organisation organisation)
        {
            DateTime currentYearSnapshotDate = organisation.SectorType.GetAccountingStartDate();
            bool     organisationCreatedInCurrentReportingYear = organisation.Created >= currentYearSnapshotDate;

            if (organisationCreatedInCurrentReportingYear)
            {
                int previousReportingYear = currentYearSnapshotDate.AddYears(-1).Year;
                OrganisationScope scope   = organisation.GetScopeForYear(previousReportingYear);

                if (scope.IsScopePresumed())
                {
                    return(true);
                }
            }

            return(false);
        }
        public void MyAccount_NavigationTest(IWebDriver driver)
        {
            try
            {
                Thread.Sleep(900);

                CommonUtils CookiesAction = new CommonUtils(driver);
                CookiesAction.RejectAll_Cookies();
                Thread.Sleep(900);

                SignIn_Page.Click();


                Excel_Suite userEmail = new Excel_Suite(Env.EXCEL_TEST_URL);
                userEmail.getCellData("SPP_TestData", true);
                UserEmail.SendKeys(Env.Email_Id);
                Password.SendKeys("Test@123");

                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(800));
                Thread.Sleep(800);


                SubmitButton.Click();

                MyAccount_Toggle.Click();

                Organisation.Click();
                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "dropdown is working fine");

                wait = new WebDriverWait(driver, TimeSpan.FromSeconds(800));
                AJAXCall.WaitForAjax();

                MyAccount_Toggle.Click();
                ServiceProvider_Page.Click();
                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "dropdown is working fine");

                Thread.Sleep(1000);
                MyAccount_Toggle.Click();

                userRoles_Page.Click();
                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "pageload is working fine");

                MyAccount_Toggle.Click();
                BankAccount_Page.Click();
                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "pageload is working fine");


                MyAccount_Toggle.Click();
                TuslaCertificate_Page.Click();
                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "pageload is working fine");



                Thread.Sleep(500);
                MyAccount_Toggle.Click();
                FeesList_Page.Click();
                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "pageload is working fine");


                MyAccount_Toggle.Click();
                ServiceCalendar_Page.Click();
                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "pageload is working fine");


                MyAccount_Toggle.Click();

                ECCEPreContracting_Page.Click();
                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "pageload is working fine");

                MyAccount_Toggle.Click();

                CapitalWorksEquipment_Page.Click();

                ReportsGeneration._test.Log(Status.Pass, " " + "   " + driver.Url + "   " + "dropdown is working fine");
            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #55
0
        private ParseOrderLineResult ParseOrderLine(Organisation org, List <string> catalogIds, string orderLinesAsString)
        {
            var olElements = orderLinesAsString.Split(new string[] { " x " }, StringSplitOptions.None).ToList();

            if (olElements.Count != 2)
            {
                return(new ParseOrderLineResult(ParseOrderLineResultState.ParseError));
            }

            string quantityString = olElements[0].Trim();

            decimal quantity = 1;

            if (!decimal.TryParse(quantityString, out quantity))
            {
                return(new ParseOrderLineResult(ParseOrderLineResultState.ParseError));
            }



            string productName       = olElements[1].Trim();
            bool   productHasOptions = false;

            string[] productOptionElements = null;

            if (productName.Contains('?'))
            {
                var productNameElements = productName.Split('?').ToList();

                productName = productNameElements[0].Trim();

                productHasOptions     = true;
                productOptionElements = productNameElements[1].Split('&');
            }

            Product product = _Ctx.Product.FirstOrDefault(p => p.Name == productName && catalogIds.Contains(p.CatalogId));

            if (product == null)
            {
                string msg = string.Format("Product '{0}' not found for line: {1}", productName, orderLinesAsString);
                return(new ParseOrderLineResult(ParseOrderLineResultState.ProductNotFound, msg));
            }

            _Ctx.Entry(product).State = System.Data.Entity.EntityState.Detached;

            OrderLine orderLine = new OrderLine()
            {
                Quantity      = quantity,
                ProductId     = product.Id,
                Product       = product,
                PlanningOrder = product.PlanningOrder
            };

            if (productHasOptions)
            {
                orderLine.OrderLineOptions = new List <OrderLineOption>();

                for (int i = 0; i < productOptionElements.Length; i++)
                {
                    string optionString   = productOptionElements[i].Trim();
                    var    optionElements = optionString.Split('=');

                    string optionCode  = optionElements[0].Trim();
                    string optionValue = optionElements[1].Trim();

                    if (optionCode.ToLower() == "persons")
                    {
                        orderLine.Persons = optionValue;
                        continue;
                    }

                    ProductOption option = _Ctx.ProductOption.FirstOrDefault(po => po.Code == optionCode && po.OrganisationId == org.Id);

                    if (option == null)
                    {
                        string msg = string.Format("Product option '{0}' not found for line: {1}", optionCode, orderLinesAsString);
                        return(new ParseOrderLineResult(ParseOrderLineResultState.ProductOptionNotFound, msg));
                    }

                    /*
                     * OrderLineOption olOption = new OrderLineOption()
                     * {
                     *  ProductOptionId = option.Id
                     * };*/

                    OrderLineOption olOption = OrderLineOption.CreateNew();
                    olOption.ProductOptionId = option.Id;

                    if (option.HasValueObjects)
                    {
                        ProductOptionValue value = _Ctx.ProductOptionValue.FirstOrDefault(v => v.ProductOptionId == option.Id && v.Code == optionValue);

                        if (value != null)
                        {
                            olOption.ProductOptionValueId = value.Id;
                        }
                        else
                        {
                            throw new ApplicationException(string.Format("Product option value not found: {0}!", optionValue));
                        }
                    }
                    else
                    {
                        decimal optionNumValue = 0;

                        if (!decimal.TryParse(optionValue, out optionNumValue))
                        {
                            string msg = string.Format("Could not parse value '{0}' for option '{1}' for line: {2}", optionValue, optionCode, orderLinesAsString);
                            return(new ParseOrderLineResult(ParseOrderLineResultState.InvalidProductOptionValue));
                        }

                        olOption.ProductOptionValue = optionNumValue;
                    }

                    orderLine.OrderLineOptions.Add(olOption);
                }
            }

            return(new ParseOrderLineResult(orderLine));
        }
        /// <summary>
        ///  Create a Organisation
        /// </summary>
        /// <param name="currentUser"></param>
        /// <param name="user"></param>
        /// <param name="appID"></param>
        /// <param name="overrideID"></param>
        /// <param name="dc"></param>
        /// <param name="dataRepository"></param>
        /// <param name="uow"></param>
        public OrganisationVMDC CreateOrganisation(string currentUser, string user, string appID, string overrideID, OrganisationDC dc, IRepository <Organisation> dataRepository, IUnitOfWork uow, IExceptionManager exceptionManager, IMappingService mappingService)
        {
            try
            {
                #region Parameter validation

                // Validate parameters
                if (string.IsNullOrEmpty(currentUser))
                {
                    throw new ArgumentOutOfRangeException("currentUser");
                }
                if (string.IsNullOrEmpty(user))
                {
                    throw new ArgumentOutOfRangeException("user");
                }
                if (string.IsNullOrEmpty(appID))
                {
                    throw new ArgumentOutOfRangeException("appID");
                }
                if (null == dc)
                {
                    throw new ArgumentOutOfRangeException("dc");
                }
                if (null == dataRepository)
                {
                    throw new ArgumentOutOfRangeException("dataRepository");
                }
                if (null == uow)
                {
                    throw new ArgumentOutOfRangeException("uow");
                }
                if (null == exceptionManager)
                {
                    throw new ArgumentOutOfRangeException("exceptionManager");
                }
                if (null == mappingService)
                {
                    throw new ArgumentOutOfRangeException("mappingService");
                }

                #endregion

                using (uow)
                {
                    // Create a new ID for the Organisation item
                    dc.Code = Guid.NewGuid();

                    // Map data contract to model
                    Organisation destination = mappingService.Map <OrganisationDC, Organisation>(dc);

                    // Add the new item
                    dataRepository.Add(destination);

                    // Commit unit of work
                    uow.Commit();

                    // Map model back to data contract to return new row id.
                    dc = mappingService.Map <Organisation, OrganisationDC>(destination);
                }

                // Create aggregate data contract
                OrganisationVMDC returnObject = new OrganisationVMDC();

                // Add new item to aggregate
                returnObject.OrganisationItem = dc;

                return(returnObject);
            }
            catch (Exception e)
            {
                //Prevent exception from propogating across the service interface
                exceptionManager.ShieldException(e);

                return(null);
            }
        }
        private void DisplayOrganisationDetails(Organisation organisation)
        {
            _pnlContactDetails.Style.Add("width", "800px");
            _pnlContactDetails.Style.Add("height", "500px");
            _pnlOrganisation.Visible = true;
            _pnlIndividual.Visible = false;

            //Get the data for the dropdown lists only if we havent fetched it earlier
            if (!(bool)ViewState["OrganisationsDropdownsPopulated"])
            {
                BindOrganisationsDropdownLists();
                ViewState["OrganisationsDropdownsPopulated"] = true;
            }

            _txtOrganisationName.Text = organisation.Name;
            _txtRegisteredName.Text = organisation.RegisteredName;
            _txtRegisteredNo.Text = organisation.RegisteredNo;
            _txtVATNo.Text = organisation.VATNo;
            _ddlIndustry.SelectedValue = organisation.IndustryId.ToString();
            _ddlSubType.SelectedValue = organisation.SubTypeId.ToString();
        }
        public static QuoteItemBuilder WithSerializedDefaults(this QuoteItemBuilder @this, Organisation internalOrganisation)
        {
            var faker = @this.Session.Faker();

            var serializedProduct = new UnifiedGoodBuilder(@this.Session).WithSerialisedDefaults(internalOrganisation).Build();

            @this.WithDetails(faker.Lorem.Sentence());
            @this.WithComment(faker.Lorem.Sentence());
            @this.WithInternalComment(faker.Lorem.Sentence());
            @this.WithEstimatedDeliveryDate(@this.Session.Now().AddDays(5));
            @this.WithInvoiceItemType(new InvoiceItemTypes(@this.Session).ProductItem);
            @this.WithProduct(serializedProduct);
            @this.WithSerialisedItem(serializedProduct.SerialisedItems.First);
            @this.WithUnitOfMeasure(new UnitsOfMeasure(@this.Session).Piece);
            @this.WithAssignedUnitPrice(faker.Random.UInt());
            @this.WithQuantity(1);
            return(@this);
        }
Beispiel #59
0
        private static void TestFindingItemsUsingLinqSyntax(Repository repository, Organisation organisation)
        {
            // Try the linq syntax to select items with sales details..
            var itemQuery = from item in repository.Items
                            where item.SalesDetails != null
                            select item;

            var itemList = itemQuery.ToList();

            Console.WriteLine("There are {0} inventory items", itemList.Count);

            foreach (var item in itemList)
            {
                Console.WriteLine(string.Format("   Item {0} is sold at price: {1} {2}", item.Description, item.SalesDetails.UnitPrice, organisation.BaseCurrency));
            }
        }
    public static Organisation[] GetFlattenedTree(DataTable dt = null, bool showDeleted = false, int organisationID = 0, bool onlyLowerBranches = false, string org_type_ids = "")
    {
        if (dt == null)
        {
            dt = OrganisationDB.GetDataTable(0, showDeleted, true, false, false, true, true, "", false, org_type_ids);
        }
        dt.Columns.Add("tree_level", typeof(Int32));

        Organisation[] tree = GetChildren(ref dt, "parent_organisation_id is NULL", 0);

        if (organisationID != 0)
        {
            for (int i = 0; i < tree.Length; i++)
            {
                if (tree[i].OrganisationID == organisationID || Contains(tree[i].TreeChildren, organisationID))
                {
                    if (!onlyLowerBranches)
                    {
                        tree = new Organisation[] { tree[i] }
                    }
                    ;
                    else
                    {
                        tree = new Organisation[] { GetNode(new Organisation[] { tree[i] }, organisationID) }
                    };
                }
            }
        }

        DataTable newTable = dt.Clone();

        Flatten(tree, ref newTable);

        if (onlyLowerBranches && newTable.Rows.Count > 0)  // if taking only sub-tree, then reset the level to zero for the base node(s)
        {
            int levelAdjustment = Convert.ToInt32(newTable.Rows[0]["tree_level"]);
            for (int i = 0; i < newTable.Rows.Count; i++)
            {
                newTable.Rows[i]["tree_level"] = Convert.ToInt32(newTable.Rows[i]["tree_level"]) - levelAdjustment;
            }
        }

        ArrayList newList = new ArrayList();
        Hashtable orgHash = new Hashtable();

        for (int i = 0; i < newTable.Rows.Count; i++)
        {
            Organisation org = OrganisationDB.LoadAll(newTable.Rows[i]);
            org.TreeLevel = Convert.ToInt32(newTable.Rows[i]["tree_level"]);
            orgHash[org.OrganisationID] = org;
            newList.Add(org);
        }

        Organisation[] list = (Organisation[])newList.ToArray(typeof(Organisation));

        for (int i = 0; i < list.Length; i++)
        {
            if (list[i].ParentOrganisation != null)
            {
                list[i].ParentOrganisation = (Organisation)orgHash[list[i].ParentOrganisation.OrganisationID];
            }
        }

        return(list);
    }