Inheritance: IOrganization
Ejemplo n.º 1
0
        public void AddOrganization(string userId, Organization organization)
        {
            var user = this.users.GetById(userId);
            user.Organization = organization;

            this.users.Save();
        }
Ejemplo n.º 2
0
    public static List<Organization> getOrganizations()
    {
        List<Organization> categoryList = new List<Organization>();
        //SqlConnection connection = new SqlConnection(GetConnectionString());
        SqlConnection connection = new SqlConnection(ConnectStringGenerator.getConnectString());
        string sel = "execute usp_selectOrganization";
        SqlCommand cmd = new SqlCommand(sel, connection);
        connection.Open();
        SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        Organization org;

        while (dr.Read())
        {

            org = new Organization();
            org.OrgID = dr["OrgID"].ToString();
            org.OrgDescription = dr["OrgDescription"].ToString();
            categoryList.Add(org);
            /*
            //course.CategoryID = dr["ICategoryID"].ToString();
            //course.ShortName = dr["IShortName"].ToString();
            //course.LongName = dr["LongName"].ToString();
            categoryList.Add(Faculty);
             */
        }
        dr.Close();
        return categoryList;
    }
		public void EntityStoredProcedure()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();

			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Employment emp = new Employment(gavin, jboss, "AU");
			s.Save(ifa);
			s.Save(jboss);
			s.Save(gavin);
			s.Save(emp);

			IQuery namedQuery = s.GetNamedQuery("selectAllEmployments");
			IList list = namedQuery.List();
			Assert.IsTrue(list[0] is Employment);
			s.Delete(emp);
			s.Delete(ifa);
			s.Delete(jboss);
			s.Delete(gavin);

			t.Commit();
			s.Close();
		}
Ejemplo n.º 4
0
        void accessing_siblings()
        {
            Organization parent = new Organization("parent", Guid.NewGuid());
            Organization childOne  = new Organization("first child", Guid.NewGuid());
            Organization childTwo  = new Organization("second child", Guid.NewGuid());

            context["when a parent node has multiple children"] = () =>
            {
                context["sibling nodes can navigate to one another"] = () =>
                {
                    parent.AddChild(childOne);
                    parent.AddChild(childTwo);

                    it["child one should see a child two node"] = () =>
                    {
                        var siblings = childOne.Siblings();
                        Assert.That(siblings, Is.Not.Null);
                        siblings.should_not_be_empty();
                        siblings.should_contain(childTwo);
                    };

                    it["child two node should see child one node"] = () =>
                    {
                        childTwo.Siblings().should_contain(childOne);
                    };
                };
            };
        }
        public ActionResult Organization(Organization orgSignupData)
        {
            string userid = new Organization().Signup(orgSignupData);
            try
            {

                if (userid != "")
                {
                    //Registering User is successfull .
                    TempData["signupemail"] = orgSignupData.email;
                    TempData["isSignupSuccess"] = 1;
                    return RedirectToAction("Index", "Login");//Redirecting to the Login Page
                }
                else
                {
                    TempData["signupemail"] = orgSignupData.email;
                    TempData["isSignupSuccess"] = 1;
                    return RedirectToAction("Index","Signup"); //Registering User Failed
                }

            }
            catch
            {

                return RedirectToAction("Index", "Signup"); //Registering User Failed
            }
        }
		public void RefCursorOutStoredProcedure()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();

			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Person kevin = new Person("Kevin");
			Employment emp = new Employment(gavin, jboss, "AU");
			Employment emp2 = new Employment(kevin, ifa, "EU");
			s.Save(ifa);
			s.Save(jboss);
			s.Save(gavin);
			s.Save(kevin);
			s.Save(emp);
			s.Save(emp2);

			IQuery namedQuery = s.GetNamedQuery("selectEmploymentsForRegion");
			namedQuery.SetString("regionCode", "EU");
			IList list = namedQuery.List();
			Assert.That(list.Count, Is.EqualTo(1));
			s.Delete(emp2);
			s.Delete(emp);
			s.Delete(ifa);
			s.Delete(jboss);
			s.Delete(kevin);
			s.Delete(gavin);

			t.Commit();
			s.Close();
		}
        public ActionResult Organizations_Update([DataSourceRequest]DataSourceRequest request, Organization organization)
        {
            if (this.ModelState.IsValid)
            {
                var entity = new Organization
                {
                    Id = organization.Id,
                    Name = organization.Name,
                    MateriallyResponsiblePerson = organization.MateriallyResponsiblePerson,
                    LogoUrl = organization.LogoUrl,
                    Vat = organization.Vat,
                    Address = organization.Address,
                    IsSupplier = organization.IsSupplier,
                    CreatedOn = organization.CreatedOn,
                    ModifiedOn = organization.ModifiedOn,
                    IsDeleted = organization.IsDeleted,
                    DeletedOn = organization.DeletedOn
                };

                this.db.Organizations.Attach(entity);
                this.db.Entry(entity).State = EntityState.Modified;
                this.db.SaveChanges();
            }

            return this.Json(new[] { organization }.ToDataSourceResult(request, this.ModelState));
        }
Ejemplo n.º 8
0
        /// <summary> Constructor creating connection using token. </summary>
        /// <param name="serverUrl"> The URL of the server Platform is running on. </param>
        /// <param name="token"> Token that has been created by GetMultiusageToken() method or a single usage one. </param>
        public PlatformClient(string serverUrl, string token)
        {

            this.connector = ServiceConnection.Create(new System.Uri(String.Format(urlFormatString, serverUrl)), token);

            this.org = this.connector.Organizations[0];
        }
Ejemplo n.º 9
0
        public ActionResult CreateOrganization(CreateOrganizationRequestViewModel model)
        {
            if (model == null || !this.ModelState.IsValid)
            {
                this.TempData[GlobalConstants.TempDataErrorKey] = GlobalConstants.InvalidOrganizationRequestErrorMessage;
                return this.RedirectToAction(x => x.Index());
            }

            var organizationToCreate = new Organization()
            {
                Name = model.OrganizationName,
                AboutInfo = model.OrganizationDescription,
                UserId = model.UserId,
                PhoneNumber = model.PhoneNumber
            };

            var isCreated = this.organizations.Create(organizationToCreate);

            if (!isCreated)
            {
                this.TempData[GlobalConstants.TempDataErrorKey] = GlobalConstants.InvalidOrganizationRequestErrorMessage;
                return this.RedirectToAction(x => x.Index());
            }

            this.TempData[GlobalConstants.TempDataSuccessKey] = GlobalConstants.CreatedOrganizationSuccessMessage;

            this.createOrganizationRequests.ProceedRequest(model.Id);
            return this.RedirectToAction(x => x.Index());
        }
 public EditOrganizationViewModel(Organization org)
 {
     Id = org.Id;
     Name = org.Name;
     IsEmailDomainRestricted = org.IsEmailDomainRestricted;
     RestrictedDomain = org.EmailDomains.Count > 0 ? org.EmailDomains.First().Domain : string.Empty;
 }
    protected void SubmitNewProfile_Click(object sender, EventArgs e)
    {
        if (MP == MP2)
        {
            Manager m = new Manager();
            m.Lname = MName.Text;
            m.Fname = MLName.Text;
            m.EmailAdress = MEMail.Text;
            m.PassWord = MP.Text;
            Organization org = new Organization();
            org.Name = OName.Text;
            org.Description = Odescription.InnerText;
            org.WebSiteUrl = Site.Text;
            org.FbWebsite = FaceBook.Text;
            org.Address = Addres.Text;
            org.PhoneNumber = Phone.Text;
            org.LogoSrc = InsertPictureToDirectory();
            int change = m.insertNewOrg(m, org);
            if (change > 0)
            {
                Session["Email"] = m.EmailAdress;
                Response.Redirect("DashBoard.aspx");
            }
        }
        else
        {

        }
    }
Ejemplo n.º 12
0
        public StyleLinkRenderer()
            : base()
        {
            // Set default values (which can be overridden by properties)

            switch (WebConfigurationManager.AppSettings[
                    "nysf_UserControls_DefaultOrganization"].Trim().ToLower())
            {
            case "pt":
                organization = Types.Organization.PublicTheater;
                break;
            case "jp":
                organization = Types.Organization.JoesPub;
                break;
            case "sitp":
                organization = Types.Organization.ShakespeareInThePark;
                break;
            default:
                throw new ApplicationException("An invalid organization was specified in "
                    + "web.config under <appSettings> key, "
                    + "\"nysf_UserControls_DefaultOrganization\". It must be set to \"pt\", "
                    + "\"jp\", or \"sitp\".");
            }
            //forceOrganization = true;
            startOfUrlToStylesheets =
            WebConfigurationManager.AppSettings[
                "nysf_UserControls_DefaultStartOfUrlToStylesheets"].Trim();
        }
Ejemplo n.º 13
0
    protected int GetMemberCount(Organization org, bool recursive, Geography geo, DateTime dateTime)
    {
        string cacheDataKey = "ChartData-AllMembershipEvents-5min";

        MembershipEvents events = (MembershipEvents)Cache.Get(cacheDataKey);

        if (events == null)
        {
            events = MembershipEvents.LoadAll();
            Cache.Insert(cacheDataKey, events, null, DateTime.UtcNow.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        DateTime endDateTime = dateTime;

        int eventIndex = 0;
        int currentCount = 0;

        while (eventIndex < events.Count && events[eventIndex].DateTime < endDateTime)
        {
            if (events[eventIndex].OrganizationId == Organization.PPSEid)
            {
                currentCount += events[eventIndex].DeltaCount;
            }

            eventIndex++;
        }

        return currentCount;
    }
Ejemplo n.º 14
0
 protected void Page_Load (object sender, EventArgs e)
 {
     if (_authority.HasPermission(Permission.CanEditMemberships, Organization.PPFIid, Geography.FinlandId, Authorization.Flag.ExactGeographyExactOrganization))
     {
         loadCntry = Country.FromCode("FI");
         geotree = loadCntry.Geography.GetTree();
         nowValue = DateTime.Now;
         if (!IsPostBack)
         {
             foreach (Organization org in Organizations.GetAll())
             {
                 if (org.DefaultCountryId == loadCntry.Identity)
                 {
                     DropDownListOrgs.Items.Add(new ListItem(org.Name, "" + org.Identity));
                 }
             }
         }
         else
         {
             currentOrg = Organization.FromIdentity(Convert.ToInt32(DropDownListOrgs.SelectedValue));
         }
     }
     else
     {
         Response.Write("Access not allowed");
         Response.End();
     }
 }
Ejemplo n.º 15
0
 public async Task<Organization> GetOrganizationAsync(string permalink)
 {
     var organization = new Organization();
     var json = await CallApiAsync(OrganizationsURL + permalink);
     organization.Load(json);
     return organization;
 }
Ejemplo n.º 16
0
        public ActionResult CreateOrUpdate(Organization org)
        {
            org.Initialize();

            var rsp = this.OrganizationService.CreateOrUpdate(org);

            return rsp.IsSuccess ? this.CloseDialogWithAlert("保存成功!") : this.Alert("保存失败,失败原因:" + rsp.ErrorMessage, AlertType.Error);
        }
 public ResultSegment()
 {
     ContactInfo = new ContactInfoSegment();
     Demographics = new DemographicsSegment();
     SocialProfiles = new SocialProfile[0];
     Organizations = new Organization[0];
     Photos = new Photo[0];
 }
        // sets parameters for insert/update
        private Dictionary<string, object> SetParams(Organization data)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();

            result.Add("@name", data.Name);

            return result;
        }
Ejemplo n.º 19
0
 public override Organization AddParent(Organization source)
 {
     throw new InvalidOperationException("Root Organization can not have a parent node.");
     /*
      * Code to prove the rule works
      * return base.AddParent(source);
      */
 }
Ejemplo n.º 20
0
		public override string GetDesignTimeHtml()
		{
			StringWriter writer1 = new StringWriter();
			HtmlTextWriter writer2 = new HtmlTextWriter(writer1);
			this.OrganizationDemo = (Organization) base.Component;
			this.OrganizationDemo.RenderControl(writer2);
			return writer1.ToString();
		}
Ejemplo n.º 21
0
        public static Organization ToDataModel(this C.Vendor domain)
        {
            if (domain == null) return null;

            var data = new Organization { OrganizationId = domain.OrganizationId };

            return data;
        }
Ejemplo n.º 22
0
        public void Save(Organization organization)
        {
            if (organization.IsValid())
            {

                OrganizationRepo.Save(organization);
            }
        }
Ejemplo n.º 23
0
 public OrganizationView(Organization org)
 {
     Id = org.Id;
     Name = org.Name;
     Remark = org.Remark;
     SortCode = org.SortCode;
     CreatedTime = org.CreatedTime;
     children = new List<OrganizationView>();
 }
Ejemplo n.º 24
0
 public OrganizationDto(Organization organization)
 {
     Id = organization.Id;
     OwnerId = organization.OwnerId;
     Name = organization.Name;
     AutoRegisterNewWarden = organization.AutoRegisterNewWarden;
     Users = organization.Users.Select(x => new UserInOrganizationDto(x));
     Wardens = organization.Wardens.Select(x => new WardenDto(x));
 }
Ejemplo n.º 25
0
	//return the aligment between two organizations
	public int Alignment(Organization org) {
		//just the average of all alignments
		int sum = 0;
		Array topics = Enum.GetValues(typeof(Topic));
		foreach(Topic t in topics){
			sum += Alignment(t, org.GetStance(t));
		}
		return sum / topics.Length;
	}
Ejemplo n.º 26
0
        public void Delete(Organization organization)
        {
            //if (organization.Id == Organization.SystemOrganizationId)
            //{
            //    throw new ArgumentException("Can not delete system organization.");
            //}

            OrganizationRepo.Remove(organization);
        }
		public void SQLQueryInterface()
		{
			ISession s = OpenSession();
			ITransaction t = s.BeginTransaction();
			Organization ifa = new Organization("IFA");
			Organization jboss = new Organization("JBoss");
			Person gavin = new Person("Gavin");
			Employment emp = new Employment(gavin, jboss, "AU");

			s.Save(ifa);
			s.Save(jboss);
			s.Save(gavin);
			s.Save(emp);

			IList l = s.CreateSQLQuery(OrgEmpRegionSQL)
				.AddEntity("org", typeof(Organization))
				.AddJoin("emp", "org.employments")
				.AddScalar("regionCode", NHibernateUtil.String)
				.List();
			Assert.AreEqual(2, l.Count);

			l = s.CreateSQLQuery(OrgEmpPersonSQL)
				.AddEntity("org", typeof(Organization))
				.AddJoin("emp", "org.employments")
				.AddJoin("pers", "emp.employee")
				.List();
			Assert.AreEqual(l.Count, 1);

			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();

			l = s.CreateSQLQuery("select {org.*}, {emp.*} " +
			                     "from ORGANIZATION org " +
			                     "     left outer join EMPLOYMENT emp on org.ORGID = emp.EMPLOYER, ORGANIZATION org2")
				.AddEntity("org", typeof(Organization))
				.AddJoin("emp", "org.employments")
				.SetResultTransformer(new DistinctRootEntityResultTransformer())
				.List();
			Assert.AreEqual(l.Count, 2);

			t.Commit();
			s.Close();

			s = OpenSession();
			t = s.BeginTransaction();

			s.Delete(emp);
			s.Delete(gavin);
			s.Delete(ifa);
			s.Delete(jboss);

			t.Commit();
			s.Close();
		}
Ejemplo n.º 28
0
 public HomeController(ITwitterService twitterService, IBlogService blogService)
 {
     this.twitterService = twitterService;
     this.blogService = blogService;
     organization = OrganizationRepository.GetDefaultOrganization(readOnly: true);
     Mapper.CreateMap<Organization, OrganizationDetailsModel>();
     Mapper.CreateMap<OrganizationSetting, OrganizationSettingModel>();
     Mapper.CreateMap<CauseTemplate, CauseTemplateDetailsModel>();
 }
Ejemplo n.º 29
0
        //MyDataTemplate _myDTemplate = null;
        public MainWindow()
        {
            InitializeComponent();

            AddStudentButton.Click += AddStudentButton_Click;

            ReplaceStudentsButton.Click += ReplaceStudentsButton_Click;

            _theOrganization = (Organization) this.Resources["TheOrganization"];
        }
Ejemplo n.º 30
0
        public void Index()
        {
            var organization = new Organization();
            organization.EmpList.Add(1,"EmployeeOne");
            organization.EmpList.Add(2, "EmployeeTwo");

            var empName = organization[2];
            var empName2 = organization.EmpList[2];
            Assert.AreEqual(empName, empName2);
        }
Ejemplo n.º 31
0
        public static LyncUserResult AddFederationDomain(int itemId, string domainName, string proxyFqdn)
        {
            List <BackgroundTaskParameter> parameters = new List <BackgroundTaskParameter>();

            parameters.Add(new BackgroundTaskParameter("domainName", domainName));
            parameters.Add(new BackgroundTaskParameter("proxyFqdn", proxyFqdn));

            LyncUserResult res = TaskManager.StartResultTask <LyncUserResult>("LYNC", "ADD_LYNC_FEDERATIONDOMAIN", itemId, parameters);

            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

            if (accountCheck < 0)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.NOT_AUTHORIZED);
                return(res);
            }


            try
            {
                Organization org = (Organization)PackageController.GetPackageItem(itemId);
                if (org == null)
                {
                    throw new ApplicationException(
                              string.Format("Organization is null. ItemId={0}", itemId));
                }

                int        lyncServiceId = GetLyncServiceID(org.PackageId);
                LyncServer lync          = GetLyncServer(lyncServiceId, org.ServiceId);

                if (string.IsNullOrEmpty(org.LyncTenantId))
                {
                    PackageContext cntx = PackageController.GetPackageContext(org.PackageId);

                    org.LyncTenantId = lync.CreateOrganization(org.OrganizationId,
                                                               org.DefaultDomain,
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_CONFERENCING].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ALLOWVIDEO].QuotaAllocatedValue),
                                                               Convert.ToInt32(cntx.Quotas[Quotas.LYNC_MAXPARTICIPANTS].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_FEDERATION].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ENTERPRISEVOICE].QuotaAllocatedValue));

                    if (string.IsNullOrEmpty(org.LyncTenantId))
                    {
                        TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ENABLE_ORG);
                        return(res);
                    }
                    else
                    {
                        PackageController.UpdatePackageItem(org);
                    }
                }

                lync = GetLyncServer(lyncServiceId, org.ServiceId);

                bool bDomainExists             = false;
                LyncFederationDomain[] domains = GetFederationDomains(itemId);
                foreach (LyncFederationDomain d in domains)
                {
                    if (d.DomainName.ToLower() == domainName.ToLower())
                    {
                        bDomainExists = true;
                        break;
                    }
                }

                if (!bDomainExists)
                {
                    lync.AddFederationDomain(org.OrganizationId, domainName.ToLower(), proxyFqdn);
                }
            }
            catch (Exception ex)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_FEDERATIONDOMAIN, ex);
                return(res);
            }

            TaskManager.CompleteResultTask();
            return(res);
        }
Ejemplo n.º 32
0
        public ActionResult Delete(int id)
        {
            Organization organization = context.Organizations.Single(x => x.OrganizationID == id);

            return(PartialView(organization));
        }
Ejemplo n.º 33
0
    protected override Task <NetworkCredential> GetServiceCredentialAsync(Component component, Organization organization, DeploymentScope deploymentScope, Project project)
    => WithKubernetesContext(component, deploymentScope, async(client, data, roleDefinition, serviceAccount) =>
    {
        var configuration = await client
                            .CreateClusterConfigAsync(serviceAccount)
                            .ConfigureAwait(false);

        return(new NetworkCredential()
        {
            Domain = client.BaseUri.ToString(),
            Password = new SerializerBuilder().Build().Serialize(configuration),
            UserName = serviceAccount.Name()
        });
    });
Ejemplo n.º 34
0
        public ActionResult _Activate(int?id)
        {
            string UserName1 = @User.Identity.Name.ToString();

            var U = (from P in context.Organizations
                     where P.OrganizationID == id
                     select P.OrganizationID).SingleOrDefault();

            var Un = (from P in context.Organizations
                      where P.OrganizationID == id
                      select P.OrganizationName).SingleOrDefault();

            ViewBag.AOrgID   = id;
            ViewBag.AOrgName = Un;

            var Ua = (from P in context.Organizations
                      where P.OrganizationID == id
                      select P.Active).SingleOrDefault();

            ViewBag.Activate = Ua;

            //var Uu = (from P in context.AspNetUsers
            //          where P.Id == U
            //          select P.RoleBinID).SingleOrDefault();

            //ViewBag.Role = Uu;

            //var active = (from ast in context.AspNetUsers
            //              where ast.Id == U
            //              select ast.Active).SingleOrDefault();

            //ViewBag.Active = active;

            //var O = (from P in context.AspNetUsers
            //         where P.UserName == UserName1
            //         select P.OrganizationID).SingleOrDefault();

            //var Oname = (from P in context.Organizations
            //             where P.OrganizationID == O
            //             select P.OrganizationName).SingleOrDefault();


            //ViewBag.UID = id;
            //ViewBag.OID = O;
            //ViewBag.OName = Oname;


            Organization organization = context.Organizations.Single(x => x.OrganizationID == id);


            ViewBag.DateUpdated = DateTime.Now;

            string UserName = @User.Identity.Name.ToString();

            ViewBag.UpdatedBy = UserName;

            ViewBag.DateCreated = organization.DateCreated;
            ViewBag.CreatedBy   = organization.CreatedBy;
            ViewBag.Status      = organization.Active;



            return(PartialView(organization));
        }
Ejemplo n.º 35
0
        /// <summary>
        /// 更新角色信息信息
        /// </summary>
        /// <param name="inputDtos">包含更新信息的角色信息DTO信息</param>
        /// <returns>业务操作结果</returns>
        public async Task <OperationResult> EditRoles(params RoleInputDto[] inputDtos)
        {
            RoleRepository.UnitOfWork.BeginTransaction();
            var result = RoleRepository.Update(inputDtos,
                                               (dto, entity) =>
            {
                //if (entity.IsSystem)
                //{
                //    throw new Exception("角色“{0}”为系统角色,不能编辑".FormatWith(dto.Name));
                //}
                if (dto.OrganizationId.HasValue)
                {
                    if (RoleRepository.CheckExists(m => m.Name == dto.Name && m.Organization != null && m.Organization.Id == dto.OrganizationId.Value, dto.Id))
                    {
                        throw new Exception("同组织机构中名称为“{0}”的角色已存在,不能重复添加。".FormatWith(dto.Name));
                    }
                }
                else if (RoleRepository.CheckExists(m => m.Name == dto.Name && m.Organization == null, dto.Id))
                {
                    throw new Exception("无组织机构的名称为的角色已存在,不能重复添加".FormatWith(dto.Name));
                }
            },
                                               (dto, entity) =>
            {
                if (dto.OrganizationId.HasValue && dto.OrganizationId.Value > 0)
                {
                    Organization organization = OrganizationRepository.GetByKey(dto.OrganizationId.Value);
                    if (organization == null)
                    {
                        throw new Exception("要加入的组织机构不存在。");
                    }
                    entity.Organization = organization;
                }
                else
                {
                    entity.Organization = null;
                }
                return(entity);
            });

            if (result.Successed || result.ResultType == OperationResultType.NoChanged)
            {
                foreach (var data in inputDtos)
                {
                    Role       role      = RoleRepository.TrackEntities.Where(x => x.Name.Equals(data.Name)).FirstOrDefault();
                    List <int> moduleIds = new List <int>();
                    for (int i = 0; i < data.ModuleManagerModels.Count; i++)
                    {
                        moduleIds.Add(data.ModuleManagerModels[i].Id);
                    }
                    if (role != null)
                    {
                        result = await SecurityService.SecurityManager.SetRoleModules(role, moduleIds.ToArray());
                    }
                }
            }

            RoleRepository.UnitOfWork.Commit();
            if (result.ResultType == OperationResultType.Error)
            {
                return(result);
            }
            else
            {
                return(new OperationResult(OperationResultType.Success, "修改角色信息成功!"));
            }
        }
Ejemplo n.º 36
0
 static public CashAdvances ForOrganization(Organization organization, bool includeClosed)
 {
     return(FromArray(SwarmDb.GetDatabaseForReading().GetCashAdvances(organization,
                                                                      includeClosed ? DatabaseCondition.None : DatabaseCondition.OpenTrue)));
 }
Ejemplo n.º 37
0
        public void InsertTestData()
        {
            // Avoid polluting the database if there's already something in there.
            if (_context.Locations.Any() ||
                _context.Organizations.Any() ||
                _context.Tasks.Any() ||
                _context.Campaigns.Any() ||
                _context.Events.Any() ||
                _context.EventSkills.Any() ||
                _context.Skills.Any() ||
                _context.Resources.Any())
            {
                return;
            }

            #region postalCodes
            var existingPostalCode = _context.PostalCodes.ToList();
            _context.PostalCodes.AddRange(GetPostalCodes(existingPostalCode));
            #endregion

            var organizations      = new List <Organization>();
            var organizationSkills = new List <Skill>();
            var locations          = GetLocations();
            var users       = new List <ApplicationUser>();
            var taskSignups = new List <TaskSignup>();
            var events      = new List <Event>();
            var eventSkills = new List <EventSkill>();
            var campaigns   = new List <Campaign>();
            var tasks       = new List <AllReadyTask>();
            var resources   = new List <Resource>();
            var contacts    = GetContacts();
            var skills      = new List <Skill>();

            #region Skills
            var medical = new Skill {
                Name = "Medical", Description = "specific enough, right?"
            };
            var cprCertified = new Skill {
                Name = "CPR Certified", ParentSkill = medical, Description = "ha ha ha ha, stayin alive"
            };
            var md = new Skill {
                Name = "MD", ParentSkill = medical, Description = "Trust me, I'm a doctor"
            };
            var surgeon = new Skill {
                Name = "Surgeon", ParentSkill = md, Description = "cut open; sew shut; play 18 holes"
            };
            skills.AddRange(new[] { medical, cprCertified, md, surgeon });
            #endregion

            #region Organization

            var organization = new Organization
            {
                Name                 = "Humanitarian Toolbox",
                LogoUrl              = "http://www.htbox.org/upload/home/ht-hero.png",
                WebUrl               = "http://www.htbox.org",
                Location             = locations.FirstOrDefault(),
                Campaigns            = new List <Campaign>(),
                OrganizationContacts = new List <OrganizationContact>(),
            };

            #endregion

            #region Organization Skills

            organizationSkills.Add(new Skill
            {
                Name               = "Code Ninja",
                Description        = "Ability to commit flawless code without review or testing",
                OwningOrganization = organization
            });

            #endregion

            #region Campaign
            //TODO: Campaign/Event/Task dates need to be set as a DateTimeOffset, offset to the correct timezone instead of UtcNow or DateTime.Today.
            var firePreventionCampaign = new Campaign
            {
                Name = "Neighborhood Fire Prevention Days",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTimeOffset.Now.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTimeOffset.Now.AddMonths(3), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(firePreventionCampaign);

            var smokeDetectorCampaignImpact = new CampaignImpact
            {
                ImpactType         = ImpactType.Numeric,
                NumericImpactGoal  = 10000,
                CurrentImpactLevel = 6722,
                Display            = true,
                TextualImpactGoal  = "Total number of smoke detectors installed."
            };
            _context.CampaignImpacts.Add(smokeDetectorCampaignImpact);

            var smokeDetectorCampaign = new Campaign
            {
                Name = "Working Smoke Detectors Save Lives",
                ManagingOrganization = organization,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(1), _timeZone),
                CampaignImpact       = smokeDetectorCampaignImpact,
                TimeZoneId           = _timeZone.Id,
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(smokeDetectorCampaign);

            var financialCampaign = new Campaign
            {
                Name = "Everyday Financial Safety",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(1), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(financialCampaign);

            var safetyKitCampaign = new Campaign
            {
                Name = "Simple Safety Kit Building",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(2), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(safetyKitCampaign);

            var carSafeCampaign = new Campaign
            {
                Name = "Family Safety In the Car",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-1), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(2), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(carSafeCampaign);

            var escapePlanCampaign = new Campaign
            {
                Name = "Be Ready to Get Out: Have a Home Escape Plan",
                ManagingOrganization = organization,
                TimeZoneId           = _timeZone.Id,
                StartDateTime        = AdjustToTimezone(DateTime.Today.AddMonths(-6), _timeZone),
                EndDateTime          = AdjustToTimezone(DateTime.Today.AddMonths(6), _timeZone),
                Location             = GetRandom(locations),
                Published            = true
            };
            organization.Campaigns.Add(escapePlanCampaign);

            #endregion

            #region Event
            var queenAnne = new Event
            {
                Name           = "Queen Anne Fire Prevention Day",
                Campaign       = firePreventionCampaign,
                StartDateTime  = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime    = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
                TimeZoneId     = firePreventionCampaign.TimeZoneId,
                Location       = GetRandom(locations),
                RequiredSkills = new List <EventSkill>(),
                EventType      = EventType.Itinerary,
            };
            queenAnne.Tasks = GetSomeTasks(queenAnne, organization);
            var ask = new EventSkill {
                Skill = surgeon, Event = queenAnne
            };
            queenAnne.RequiredSkills.Add(ask);
            eventSkills.Add(ask);
            ask = new EventSkill {
                Skill = cprCertified, Event = queenAnne
            };
            queenAnne.RequiredSkills.Add(ask);
            eventSkills.Add(ask);
            tasks.AddRange(queenAnne.Tasks);

            var ballard = new Event
            {
                Name          = "Ballard Fire Prevention Day",
                Campaign      = firePreventionCampaign,
                StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
                TimeZoneId    = firePreventionCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            ballard.Tasks = GetSomeTasks(ballard, organization);
            tasks.AddRange(ballard.Tasks);
            var madrona = new Event
            {
                Name          = "Madrona Fire Prevention Day",
                Campaign      = firePreventionCampaign,
                StartDateTime = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(firePreventionCampaign.StartDateTime.AddMonths(2), _timeZone),
                TimeZoneId    = firePreventionCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            madrona.Tasks = GetSomeTasks(madrona, organization);
            tasks.AddRange(madrona.Tasks);
            var southLoopSmoke = new Event
            {
                Name          = "Smoke Detector Installation and Testing-South Loop",
                Campaign      = smokeDetectorCampaign,
                StartDateTime = AdjustToTimezone(smokeDetectorCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(smokeDetectorCampaign.EndDateTime, _timeZone),
                TimeZoneId    = smokeDetectorCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            southLoopSmoke.Tasks = GetSomeTasks(southLoopSmoke, organization);
            tasks.AddRange(southLoopSmoke.Tasks);
            var northLoopSmoke = new Event
            {
                Name          = "Smoke Detector Installation and Testing-Near North Side",
                Campaign      = smokeDetectorCampaign,
                StartDateTime = AdjustToTimezone(smokeDetectorCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(smokeDetectorCampaign.EndDateTime, _timeZone),
                TimeZoneId    = smokeDetectorCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            northLoopSmoke.Tasks = GetSomeTasks(northLoopSmoke, organization);
            tasks.AddRange(northLoopSmoke.Tasks);
            var dateTimeToday    = DateTime.Today;
            var rentersInsurance = new Event
            {
                Name          = "Renters Insurance Education Door to Door and a bag of chips",
                Description   = "description for the win",
                Campaign      = financialCampaign,
                StartDateTime = AdjustToTimezone(new DateTime(dateTimeToday.Year, dateTimeToday.Month, dateTimeToday.Day, 8, 0, 0), _timeZone),
                EndDateTime   = AdjustToTimezone(new DateTime(dateTimeToday.Year, dateTimeToday.Month, dateTimeToday.Day, 16, 0, 0), _timeZone),
                TimeZoneId    = financialCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Rally,
            };
            rentersInsurance.Tasks = GetSomeTasks(rentersInsurance, organization);
            tasks.AddRange(rentersInsurance.Tasks);
            var rentersInsuranceEd = new Event
            {
                Name          = "Renters Insurance Education Door to Door (woop woop)",
                Description   = "another great description",
                Campaign      = financialCampaign,
                StartDateTime = AdjustToTimezone(financialCampaign.StartDateTime.AddMonths(1).AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(financialCampaign.EndDateTime, _timeZone),
                TimeZoneId    = financialCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            rentersInsuranceEd.Tasks = GetSomeTasks(rentersInsuranceEd, organization);
            tasks.AddRange(rentersInsuranceEd.Tasks);
            var safetyKitBuild = new Event
            {
                Name          = "Safety Kit Assembly Volunteer Day",
                Description   = "Full day of volunteers building kits",
                Campaign      = safetyKitCampaign,
                StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
                TimeZoneId    = safetyKitCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            safetyKitBuild.Tasks = GetSomeTasks(safetyKitBuild, organization);
            tasks.AddRange(safetyKitBuild.Tasks);

            var safetyKitHandout = new Event
            {
                Name          = "Safety Kit Distribution Weekend",
                Description   = "Handing out kits at local fire stations",
                Campaign      = safetyKitCampaign,
                StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
                TimeZoneId    = safetyKitCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            safetyKitHandout.Tasks = GetSomeTasks(safetyKitHandout, organization);
            tasks.AddRange(safetyKitHandout.Tasks);
            var carSeatTest1 = new Event
            {
                Name          = "Car Seat Testing-Naperville",
                Description   = "Checking car seats at local fire stations after last day of school year",
                Campaign      = carSafeCampaign,
                StartDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(carSafeCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
                TimeZoneId    = carSafeCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            carSeatTest1.Tasks = GetSomeTasks(carSeatTest1, organization);
            tasks.AddRange(carSeatTest1.Tasks);
            var carSeatTest2 = new Event
            {
                Name          = "Car Seat and Tire Pressure Checking Volunteer Day",
                Description   = "Checking those things all day at downtown train station parking",
                Campaign      = carSafeCampaign,
                StartDateTime = AdjustToTimezone(carSafeCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(carSafeCampaign.StartDateTime.AddMonths(1).AddDays(5), _timeZone),
                TimeZoneId    = carSafeCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            carSeatTest2.Tasks = GetSomeTasks(carSeatTest2, organization);
            tasks.AddRange(carSeatTest2.Tasks);
            var homeFestival = new Event
            {
                Name          = "Park District Home Safety Festival",
                Description   = "At downtown park district(adjacent to pool)",
                Campaign      = safetyKitCampaign,
                StartDateTime = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(safetyKitCampaign.StartDateTime.AddMonths(1), _timeZone),
                TimeZoneId    = safetyKitCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            homeFestival.Tasks = GetSomeTasks(homeFestival, organization);
            tasks.AddRange(homeFestival.Tasks);
            var homeEscape = new Event
            {
                Name          = "Home Escape Plan Flyer Distribution",
                Description   = "Handing out flyers door to door in several areas of town after school/ work hours.Streets / blocks will vary but number of volunteers.",
                Campaign      = escapePlanCampaign,
                StartDateTime = AdjustToTimezone(escapePlanCampaign.StartDateTime.AddDays(1), _timeZone),
                EndDateTime   = AdjustToTimezone(escapePlanCampaign.StartDateTime.AddMonths(7), _timeZone),
                TimeZoneId    = escapePlanCampaign.TimeZoneId,
                Location      = GetRandom(locations),
                EventType     = EventType.Itinerary,
            };
            homeEscape.Tasks = GetSomeTasks(homeEscape, organization);
            tasks.AddRange(homeEscape.Tasks);
            #endregion

            #region Link campaign and event

            firePreventionCampaign.Events = new List <Event> {
                queenAnne, ballard, madrona
            };
            smokeDetectorCampaign.Events = new List <Event> {
                southLoopSmoke, northLoopSmoke
            };
            financialCampaign.Events = new List <Event> {
                rentersInsurance, rentersInsuranceEd
            };
            safetyKitCampaign.Events = new List <Event> {
                safetyKitBuild, safetyKitHandout
            };
            carSafeCampaign.Events = new List <Event> {
                carSeatTest1, carSeatTest2
            };
            escapePlanCampaign.Events = new List <Event> {
                homeFestival, homeEscape
            };

            #endregion

            #region Add Campaigns and Events
            organizations.Add(organization);
            campaigns.Add(firePreventionCampaign);
            campaigns.Add(smokeDetectorCampaign);
            campaigns.Add(financialCampaign);
            campaigns.Add(escapePlanCampaign);
            campaigns.Add(safetyKitCampaign);
            campaigns.Add(carSafeCampaign);

            events.AddRange(firePreventionCampaign.Events);
            events.AddRange(smokeDetectorCampaign.Events);
            events.AddRange(financialCampaign.Events);
            events.AddRange(escapePlanCampaign.Events);
            events.AddRange(safetyKitCampaign.Events);
            events.AddRange(carSafeCampaign.Events);
            #endregion

            #region Insert Resource items into Resources
            resources.Add(new Resource
            {
                Name             = "allReady Partner Name",
                Description      = "allready Partner Description",
                PublishDateBegin = DateTime.Today,
                PublishDateEnd   = DateTime.Today.AddDays(14),
                MediaUrl         = "",
                ResourceUrl      = "",
                CategoryTag      = "Partners"
            });
            resources.Add(new Resource
            {
                Name             = "allReady Partner Name 2",
                Description      = "allready Partner Description 2",
                PublishDateBegin = DateTime.Today.AddDays(-3),
                PublishDateEnd   = DateTime.Today.AddDays(-1),
                MediaUrl         = "",
                ResourceUrl      = "",
                CategoryTag      = "Partners"
            });
            #endregion

            #region Insert into DB
            _context.Skills.AddRange(skills);
            _context.Contacts.AddRange(contacts);
            _context.EventSkills.AddRange(eventSkills);
            _context.Locations.AddRange(locations);
            _context.Organizations.AddRange(organizations);
            _context.Tasks.AddRange(tasks);
            _context.Campaigns.AddRange(campaigns);
            _context.Events.AddRange(events);
            _context.Resources.AddRange(resources);
            //_context.SaveChanges();
            #endregion

            #region Users for Events
            var username1 = $"{_settings.DefaultUsername}1.com";
            var username2 = $"{_settings.DefaultUsername}2.com";
            var username3 = $"{_settings.DefaultUsername}3.com";

            var user1 = new ApplicationUser {
                FirstName  = "FirstName1", LastName = "LastName1", UserName = username1, Email = username1, EmailConfirmed = true,
                TimeZoneId = _timeZone.Id, PhoneNumber = "111-111-1111"
            };
            _userManager.CreateAsync(user1, _settings.DefaultAdminPassword).GetAwaiter().GetResult();
            users.Add(user1);

            var user2 = new ApplicationUser {
                FirstName  = "FirstName2", LastName = "LastName2", UserName = username2, Email = username2, EmailConfirmed = true,
                TimeZoneId = _timeZone.Id, PhoneNumber = "222-222-2222"
            };
            _userManager.CreateAsync(user2, _settings.DefaultAdminPassword).GetAwaiter().GetResult();
            users.Add(user2);

            var user3 = new ApplicationUser {
                FirstName  = "FirstName3", LastName = "LastName3", UserName = username3, Email = username3, EmailConfirmed = true,
                TimeZoneId = _timeZone.Id, PhoneNumber = "333-333-3333"
            };
            _userManager.CreateAsync(user3, _settings.DefaultAdminPassword).GetAwaiter().GetResult();
            users.Add(user3);
            #endregion

            #region TaskSignups
            var i = 0;
            foreach (var task in tasks.Where(t => t.Event == madrona))
            {
                for (var j = 0; j < i; j++)
                {
                    taskSignups.Add(new TaskSignup {
                        Task = task, User = users[j], Status = TaskStatus.Assigned
                    });
                }

                i = (i + 1) % users.Count;
            }
            _context.TaskSignups.AddRange(taskSignups);
            #endregion

            #region OrganizationContacts
            organization.OrganizationContacts.Add(new OrganizationContact {
                Contact = contacts.First(), Organization = organization, ContactType = 1                                                             /*Primary*/
            });
            #endregion

            #region Wrap Up DB
            _context.SaveChanges();
            #endregion
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Lists tasks, limit 100.
        /// </summary>
        /// <param name="organization">filter tasks to a specific organization</param>
        /// <returns>A list of tasks</returns>
        public async Task <List <TaskType> > FindTasksByOrganizationAsync(Organization organization)
        {
            Arguments.CheckNotNull(organization, nameof(organization));

            return(await FindTasksByOrganizationIdAsync(organization.Id));
        }
Ejemplo n.º 39
0
 static public CashAdvances ForOrganization(Organization organization)
 {
     return(ForOrganization(organization, false));
 }
Ejemplo n.º 40
0
 public Task SendOrganizationPaymentFailedAsync(User owner, Organization organization)
 {
     return(Task.CompletedTask);
 }
Ejemplo n.º 41
0
 public Task SendOrganizationNoticeAsync(User user, Organization organization, bool isOverMonthlyLimit, bool isOverHourlyLimit)
 {
     return(Task.CompletedTask);
 }
Ejemplo n.º 42
0
 public Task SendOrganizationInviteAsync(User sender, Organization organization, Invite invite)
 {
     return(Task.CompletedTask);
 }
        public async Task ExistingEvent()
        {
            var context = ServiceProvider.GetService <AllReadyContext>();

            var htb = new Organization
            {
                Id        = 123,
                Name      = "Humanitarian Toolbox",
                LogoUrl   = "http://www.htbox.org/upload/home/ht-hero.png",
                WebUrl    = "http://www.htbox.org",
                Campaigns = new List <Campaign>()
            };

            var firePrev = new Campaign
            {
                Id   = 1,
                Name = "Neighborhood Fire Prevention Days",
                ManagingOrganization = htb,
                TimeZoneId           = "Central Standard Time"
            };

            htb.Campaigns.Add(firePrev);

            var queenAnne = new Event
            {
                Id            = 100,
                Name          = "Queen Anne Fire Prevention Day",
                Campaign      = firePrev,
                CampaignId    = firePrev.Id,
                StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
                EndDateTime   = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
                Location      = new Location {
                    Id = 1
                },
                RequiredSkills = new List <EventSkill>()
            };

            context.Organizations.Add(htb);
            context.Events.Add(queenAnne);
            context.SaveChanges();

            const string newName = "Some new name value";

            var startDateTime = new DateTime(2015, 7, 12, 4, 15, 0);
            var endDateTime   = new DateTime(2015, 12, 7, 15, 10, 0);
            var vm            = new EventEditViewModel
            {
                CampaignId       = queenAnne.CampaignId,
                CampaignName     = queenAnne.Campaign.Name,
                Description      = queenAnne.Description,
                EndDateTime      = endDateTime,
                Id               = queenAnne.Id,
                ImageUrl         = queenAnne.ImageUrl,
                Location         = null,
                Name             = newName,
                RequiredSkills   = queenAnne.RequiredSkills,
                TimeZoneId       = "Central Standard Time",
                StartDateTime    = startDateTime,
                OrganizationId   = queenAnne.Campaign.ManagingOrganizationId,
                OrganizationName = queenAnne.Campaign.ManagingOrganization.Name,
            };
            var query = new EditEventCommand {
                Event = vm
            };
            var handler = new EditEventCommandHandler(context, Mock.Of <IConvertDateTimeOffset>());
            var result  = await handler.Handle(query);

            Assert.Equal(100, result); // should get back the event id

            var data = context.Events.Single(_ => _.Id == result);

            Assert.Equal(newName, data.Name);

            Assert.Equal(2015, data.StartDateTime.Year);
            Assert.Equal(7, data.StartDateTime.Month);
            Assert.Equal(12, data.StartDateTime.Day);
            Assert.Equal(4, data.StartDateTime.Hour);
            Assert.Equal(15, data.StartDateTime.Minute);
            Assert.Equal(-5, data.StartDateTime.Offset.TotalHours);

            Assert.Equal(2015, data.EndDateTime.Year);
            Assert.Equal(12, data.EndDateTime.Month);
            Assert.Equal(7, data.EndDateTime.Day);
            Assert.Equal(15, data.EndDateTime.Hour);
            Assert.Equal(10, data.EndDateTime.Minute);
            Assert.Equal(-6, data.EndDateTime.Offset.TotalHours);
        }
		protected virtual IEnumerable consolRecords(
			[PXDBString]
			string ledgerCD,
			[PXDBString]
			string branchCD
			)
		{
			Ledger ledger = PXSelect<Ledger,
				Where<Ledger.consolAllowed, Equal<True>,
				And<Ledger.ledgerCD, Equal<Required<Ledger.ledgerCD>>>>>.Select(this, ledgerCD);

			if (ledger == null)
			{
				throw new PXException(Messages.CantFindConsolidationLedger, ledgerCD);
			}

			Branch branch = PXSelect<Branch,
				Where<Branch.branchCD, Equal<Required<Branch.branchCD>>>>.Select(this, branchCD);

			if (!string.IsNullOrEmpty(branchCD) && branch == null)
			{
				throw new PXException(Messages.CantFindConsolidationBranch, branchCD);
			}

			if (branch != null && ledger.BalanceType != LedgerBalanceType.Report)
			{
				Organization organization = OrganizationMaint.FindOrganizationByID(this, branch.OrganizationID);

				if (organization.OrganizationType == OrganizationTypes.WithBranchesNotBalancing)
				{
					throw new PXException(Messages.BranchCannotBeConsolidated, branchCD);
				}
			}

			var exportSubaccountMapper = CreateExportSubaccountMapper();

			var noSegmentsToExport = false;
			if (PXAccess.FeatureInstalled<FeaturesSet.subAccount>())
			{
				noSegmentsToExport = SubaccountSegmentsView.Select()
					.RowCast<Segment>()
					.All(segment => segment.ConsolNumChar <= 0);
			}

			PXSelectBase<GLHistory> cmd = new PXSelectJoin<GLHistory,
				InnerJoin<Account, On<Account.accountID, Equal<GLHistory.accountID>>,
				InnerJoin<Sub, On<Sub.subID, Equal<GLHistory.subID>>,
				InnerJoin<Ledger, On<Ledger.ledgerID, Equal<GLHistory.ledgerID>>,
				InnerJoin<Branch, On<Branch.branchID, Equal<GLHistory.branchID>>>>>>,
				Where<Ledger.ledgerCD, Equal<Required<Ledger.ledgerCD>>,
				And<GLHistory.accountID, NotEqual<Current<GLSetup.ytdNetIncAccountID>>>>,
				OrderBy<Asc<GLHistory.finPeriodID, Asc<Account.accountCD, Asc<Sub.subCD>>>>>(this);

			if (!string.IsNullOrEmpty(branchCD))
			{
				cmd.WhereAnd<Where<Branch.branchCD, Equal<Required<Branch.branchCD>>>>();
			}

			foreach (PXResult<GLHistory, Account, Sub> result in cmd.Select(ledgerCD, branchCD))
			{
				GLHistory history = result;
				Account account = result;
				Sub sub = result;

				string accountCD = account.GLConsolAccountCD;
				string subCD = exportSubaccountMapper.GetMappedSubaccountCD(sub);

				if (accountCD != null && accountCD.TrimEnd() != ""
					&& (subCD != null && subCD.TrimEnd() != "" || noSegmentsToExport))
				{
					GLConsolData consolData = new GLConsolData();
					consolData.MappedValue = subCD;
					consolData.AccountCD = accountCD;
					consolData.FinPeriodID = history.FinPeriodID;
					consolData = ConsolRecords.Locate(consolData);
					if (consolData != null)
					{
						consolData.ConsolAmtDebit += history.FinPtdDebit;
						consolData.ConsolAmtCredit += history.FinPtdCredit;
					}
					else
					{
						consolData = new GLConsolData();
						consolData.MappedValue = subCD;
						consolData.MappedValueLength = subCD.Length;
						consolData.AccountCD = accountCD;
						consolData.FinPeriodID = history.FinPeriodID;
						consolData.ConsolAmtDebit = history.FinPtdDebit;
						consolData.ConsolAmtCredit = history.FinPtdCredit;
						ConsolRecords.Insert(consolData);
					}
				}
			}

			return ConsolRecords.Cache.Inserted;
		}
        public async Task ExistingEventUpdateLocation()
        {
            const string seattlePostalCode = "98117";

            var seattle = new Location
            {
                Id          = 1,
                Address1    = "123 Main Street",
                Address2    = "Unit 2",
                City        = "Seattle",
                PostalCode  = seattlePostalCode,
                Country     = "USA",
                State       = "WA",
                Name        = "Organizer name",
                PhoneNumber = "555-555-5555"
            };

            var htb = new Organization
            {
                Id        = 123,
                Name      = "Humanitarian Toolbox",
                LogoUrl   = "http://www.htbox.org/upload/home/ht-hero.png",
                WebUrl    = "http://www.htbox.org",
                Campaigns = new List <Campaign>()
            };

            var firePrev = new Campaign
            {
                Id   = 1,
                Name = "Neighborhood Fire Prevention Days",
                ManagingOrganization = htb,
                TimeZoneId           = "Central Standard Time"
            };

            htb.Campaigns.Add(firePrev);

            var queenAnne = new Event
            {
                Id             = 100,
                Name           = "Queen Anne Fire Prevention Day",
                Campaign       = firePrev,
                CampaignId     = firePrev.Id,
                StartDateTime  = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
                EndDateTime    = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
                Location       = seattle,
                RequiredSkills = new List <EventSkill>()
            };

            var context = ServiceProvider.GetService <AllReadyContext>();

            context.Locations.Add(seattle);
            context.Organizations.Add(htb);
            context.Events.Add(queenAnne);
            context.SaveChanges();

            var newLocation = new Location
            {
                Address1    = "123 new address",
                Address2    = "new suite",
                PostalCode  = "98004",
                City        = "Bellevue",
                State       = "WA",
                Country     = "USA",
                Name        = "New name",
                PhoneNumber = "New number"
            }.ToEditModel();

            var locationEdit = new EventEditViewModel
            {
                CampaignId       = queenAnne.CampaignId,
                CampaignName     = queenAnne.Campaign.Name,
                Description      = queenAnne.Description,
                EndDateTime      = queenAnne.EndDateTime,
                Id               = queenAnne.Id,
                ImageUrl         = queenAnne.ImageUrl,
                Location         = newLocation,
                Name             = queenAnne.Name,
                RequiredSkills   = queenAnne.RequiredSkills,
                TimeZoneId       = "Central Standard Time",
                StartDateTime    = queenAnne.StartDateTime,
                OrganizationId   = queenAnne.Campaign.ManagingOrganizationId,
                OrganizationName = queenAnne.Campaign.ManagingOrganization.Name,
            };

            var query = new EditEventCommand {
                Event = locationEdit
            };
            var handler = new EditEventCommandHandler(context, Mock.Of <IConvertDateTimeOffset>());
            var result  = await handler.Handle(query);

            Assert.Equal(100, result); // should get back the event id

            var data = context.Events.Single(a => a.Id == result);

            Assert.Equal(data.Location.Address1, newLocation.Address1);
            Assert.Equal(data.Location.Address2, newLocation.Address2);
            Assert.Equal(data.Location.City, newLocation.City);
            Assert.Equal(data.Location.PostalCode, newLocation.PostalCode);
            Assert.Equal(data.Location.State, newLocation.State);
            Assert.Equal(data.Location.Country, newLocation.Country);
            Assert.Equal(data.Location.PhoneNumber, newLocation.PhoneNumber);
            Assert.Equal(data.Location.Name, newLocation.Name);
        }
Ejemplo n.º 46
0
        public ETL_FinancialPrepaidExpenseTransaction ExtractTransaction(Session session, Guid TransactionId, string AccountCode)
        {
            ETL_FinancialPrepaidExpenseTransaction resultTransaction = null;

            try
            {
                bool             Acceptable = false;
                CriteriaOperator criteria_RowStatus
                    = new BinaryOperator("RowStatus", Constant.ROWSTATUS_ACTIVE, BinaryOperatorType.GreaterOrEqual);
                CriteriaOperator criteria_Code = new BinaryOperator("Code", AccountCode, BinaryOperatorType.Equal);
                CriteriaOperator criteria      = CriteriaOperator.And(criteria_Code, criteria_RowStatus);
                Account          account       = session.FindObject <Account>(criteria);

                Organization defaultOrg       = Organization.GetDefault(session, OrganizationEnum.NAAN_DEFAULT);
                Organization currentDeployOrg = Organization.GetDefault(session, OrganizationEnum.QUASAPHARCO);
                Account      defaultAccount   = Account.GetDefault(session, DefaultAccountEnum.NAAN_DEFAULT);
                Transaction  transaction      = session.GetObjectByKey <Transaction>(TransactionId);
                if (transaction == null)
                {
                    return(resultTransaction);
                }

                resultTransaction = new ETL_FinancialPrepaidExpenseTransaction();
                if (currentDeployOrg != null)
                {
                    resultTransaction.OwnerOrgId = currentDeployOrg.OrganizationId;
                }
                else
                {
                    resultTransaction.OwnerOrgId = defaultOrg.OrganizationId;
                }

                resultTransaction.TransactionId      = transaction.TransactionId;
                resultTransaction.Amount             = transaction.Amount;
                resultTransaction.Code               = transaction.Code;
                resultTransaction.CreateDate         = transaction.CreateDate;
                resultTransaction.Description        = transaction.Description;
                resultTransaction.IsBalanceForward   = (transaction is BalanceForwardTransaction);
                resultTransaction.IssuedDate         = transaction.IssueDate;
                resultTransaction.UpdateDate         = transaction.UpdateDate;
                resultTransaction.GeneralJournalList = new List <ETL_GeneralJournal>();

                foreach (GeneralJournal journal
                         in
                         transaction.GeneralJournals.Where(i => i.RowStatus == Constant.ROWSTATUS_BOOKED_ENTRY || i.RowStatus == Constant.ROWSTATUS_ACTIVE))
                {
                    ETL_GeneralJournal tempJournal = new ETL_GeneralJournal();
                    if (journal.AccountId != null)
                    {
                        tempJournal.AccountId = journal.AccountId.AccountId;
                    }
                    else
                    {
                        tempJournal.AccountId = defaultAccount.AccountId;
                    }

                    tempJournal.CreateDate = journal.CreateDate;
                    tempJournal.Credit     = journal.Credit;
                    if (journal.CurrencyId == null)
                    {
                        tempJournal.CurrencyId = CurrencyBO.DefaultCurrency(session).CurrencyId;
                    }
                    else
                    {
                        tempJournal.CurrencyId = journal.CurrencyId.CurrencyId;
                    }
                    tempJournal.Debit            = journal.Debit;
                    tempJournal.Description      = journal.Description;
                    tempJournal.GeneralJournalId = journal.GeneralJournalId;
                    tempJournal.JournalType      = journal.JournalType;
                    resultTransaction.GeneralJournalList.Add(tempJournal);

                    Account tmpAccount       = session.GetObjectByKey <Account>(tempJournal.AccountId);
                    bool    flgIsLeafAccount = tmpAccount.Accounts == null || tmpAccount.Accounts.Count == 0 ? true : false;

                    if (flgIsLeafAccount &&
                        accountingBO.IsRelateAccount(session, account.AccountId, tempJournal.AccountId))
                    {
                        Acceptable = true;
                    }
                }
                if (!Acceptable)
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            resultTransaction.AccountCode = AccountCode;
            return(resultTransaction);
        }
Ejemplo n.º 47
0
 public EmployeePayments(Organization organization) : base(organization)
 {
     transactionType = TransactionTypes.EmployeePayment;
 }
        protected override void LoadTestData()
        {
            var htb = new Organization
            {
                Name      = "Humanitarian Toolbox",
                LogoUrl   = "http://www.htbox.org/upload/home/ht-hero.png",
                WebUrl    = "http://www.htbox.org",
                Campaigns = new List <Campaign>()
            };

            var firePrev = new Campaign
            {
                Name = "Neighborhood Fire Prevention Days",
                ManagingOrganization = htb
            };

            var queenAnne = new Event
            {
                Id            = 1,
                Name          = "Queen Anne Fire Prevention Day",
                Campaign      = firePrev,
                CampaignId    = firePrev.Id,
                StartDateTime = new DateTime(2015, 7, 4, 10, 0, 0).ToUniversalTime(),
                EndDateTime   = new DateTime(2015, 12, 31, 15, 0, 0).ToUniversalTime(),
                Location      = new Location {
                    Id = 1
                },
                RequiredSkills = new List <EventSkill>(),
            };

            var username1 = $"*****@*****.**";
            var username2 = $"*****@*****.**";

            var user1 = new ApplicationUser {
                UserName = username1, Email = username1, EmailConfirmed = true
            };

            Context.Users.Add(user1);
            var user2 = new ApplicationUser {
                UserName = username2, Email = username2, EmailConfirmed = true
            };

            Context.Users.Add(user2);

            htb.Campaigns.Add(firePrev);
            Context.Organizations.Add(htb);

            var volunteerTask = new VolunteerTask
            {
                Event         = queenAnne,
                Description   = "Description of a very important task",
                Name          = "Task # ",
                EndDateTime   = DateTime.Now.AddDays(1),
                StartDateTime = DateTime.Now.AddDays(-3)
            };

            queenAnne.VolunteerTasks.Add(volunteerTask);
            Context.Events.Add(queenAnne);

            var volunteerTaskSignups = new List <VolunteerTaskSignup>
            {
                new VolunteerTaskSignup {
                    VolunteerTask = volunteerTask, User = user1
                },
                new VolunteerTaskSignup {
                    VolunteerTask = volunteerTask, User = user2
                }
            };

            Context.VolunteerTaskSignups.AddRange(volunteerTaskSignups);

            Context.SaveChanges();
        }
Ejemplo n.º 49
0
        public ActionResult UpdateOrg(string text)
        {
            if (Request.HttpMethod.ToUpper() == "GET")
            {
                ViewData["text"] = "";
                return(View());
            }
            var lines = text.Split('\n');
            var names = lines[0].Split('\t');

            for (var i = 1; i < lines.Length; i++)
            {
                var a   = lines[i].Split('\t');
                var oid = a[0].ToInt();
                var o   = DbUtil.Db.LoadOrganizationById(oid);
                for (var c = 1; c < a.Length; c++)
                {
                    switch (names[c].Trim())
                    {
                    case "Campus":
                        if (a[c].AllDigits())
                        {
                            o.CampusId = a[c].ToInt();
                            if (o.CampusId == 0)
                            {
                                o.CampusId = null;
                            }
                        }
                        break;

                    case "CanSelfCheckin":
                        o.CanSelfCheckin = a[c].ToBool2();
                        break;

                    case "RegStart":
                        o.RegStart = a[c].ToDate();
                        break;

                    case "RegEnd":
                        o.RegEnd = a[c].ToDate();
                        break;

                    case "Schedule":
                        if (a[c].HasValue() && a[c] != "None")
                        {
                            var scin = Organization.ParseSchedule(a[c].TrimEnd());
                            var sc   = o.OrgSchedules.FirstOrDefault();
                            if (sc != null)
                            {
                                sc.SchedDay  = scin.SchedDay;
                                sc.SchedTime = scin.SchedTime;
                            }
                            else
                            {
                                o.OrgSchedules.Add(scin);
                            }
                        }
                        break;

                    case "BirthDayStart":
                        o.BirthDayStart = a[c].ToDate();
                        break;

                    case "BirthDayEnd":
                        o.BirthDayEnd = a[c].ToDate();
                        break;

                    case "EntryPoint":
                        if (a[c].AllDigits())
                        {
                            var id = a[c].ToInt();
                            if (id > 0)
                            {
                                o.EntryPointId = id;
                            }
                        }
                        break;

                    case "LeaderType":
                        if (a[c].AllDigits())
                        {
                            var id = a[c].ToInt();
                            if (id > 0)
                            {
                                o.LeaderMemberTypeId = id;
                            }
                        }
                        break;

                    case "SecurityType":
                        o.SecurityTypeId = string.Compare(a[c], "LeadersOnly", true) == 0 ? 2 : string.Compare(a[c], "UnShared", true) == 0 ? 3 : 0;
                        break;

                    case "FirstMeeting":
                        o.FirstMeetingDate = a[c].ToDate();
                        break;

                    case "Gender":
                        o.GenderId = a[c] == "Male" ? (int?)1 : a[c] == "Female" ? (int?)2 : null;
                        break;

                    case "GradeAgeStart":
                        o.GradeAgeStart = a[c].ToInt2();
                        break;

                    case "MainFellowshipOrg":
                        o.IsBibleFellowshipOrg = a[c].ToBool2();
                        break;

                    case "LastDayBeforeExtra":
                        o.LastDayBeforeExtra = a[c].ToDate();
                        break;

                    case "LastMeeting":
                        o.LastMeetingDate = a[c].ToDate();
                        break;

                    case "Limit":
                        o.Limit = a[c].ToInt2();
                        break;

                    case "Location":
                        o.Location = a[c];
                        break;

                    case "Name":
                        o.OrganizationName = a[c];
                        break;

                    case "NoSecurityLabel":
                        o.NoSecurityLabel = a[c].ToBool2();
                        break;

                    case "NumCheckInLabels":
                        o.NumCheckInLabels = a[c].ToInt2();
                        break;

                    case "NumWorkerCheckInLabels":
                        o.NumWorkerCheckInLabels = a[c].ToInt2();
                        break;

                    case "OnLineCatalogSort":
                        o.OnLineCatalogSort = a[c] == "0" ? (int?)null : a[c].ToInt2();
                        break;

                    case "OrganizationStatusId":
                        o.OrganizationStatusId = a[c].ToInt();
                        break;

                    case "PhoneNumber":
                        o.PhoneNumber = a[c];
                        break;

                    case "RollSheetVisitorWks":
                        o.RollSheetVisitorWks = a[c] == "0" ? (int?)null : a[c].ToInt2();
                        break;
                    }
                }
                DbUtil.Db.SubmitChanges();
            }
            return(Redirect("/"));
        }
Ejemplo n.º 50
0
        /// <inheritdoc/>
        public async Task <SearchResults> SearchRepository(bool onlyAdmin, string keyWord, int page)
        {
            User user = GetCurrentUser().Result;

            SearchResults repository           = new SearchResults();
            string        giteaSearchUriString = $"repos/search?limit={_settings.RepoSearchPageCount}";

            if (onlyAdmin)
            {
                giteaSearchUriString += $"&uid={user.Id}";
            }

            if (!string.IsNullOrEmpty(keyWord))
            {
                giteaSearchUriString += $"&q={keyWord}";
            }

            bool allElementsRetrieved = false;

            int resultPage = 1;

            if (page != 0)
            {
                resultPage = page;
            }

            int totalCount = 0;

            while (!allElementsRetrieved)
            {
                HttpResponseMessage response = await _httpClient.GetAsync(giteaSearchUriString + "&page=" + resultPage);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    if (resultPage == 1 || page == resultPage)
                    {
                        // This is the first or a specific page requested
                        repository = await response.Content.ReadAsAsync <SearchResults>();
                    }
                    else
                    {
                        SearchResults pageResultRepository = await response.Content.ReadAsAsync <SearchResults>();

                        repository.Data.AddRange(pageResultRepository.Data);
                    }

                    if (response.Headers.TryGetValues("X-Total-Count", out IEnumerable <string> values))
                    {
                        totalCount = Convert.ToInt32(values.First());
                    }

                    if (page == resultPage ||
                        (repository?.Data != null && repository.Data.Count >= totalCount) ||
                        (repository?.Data != null && repository.Data.Count >= _settings.RepoSearchPageCount))
                    {
                        allElementsRetrieved = true;
                    }
                    else
                    {
                        resultPage++;
                    }
                }
                else
                {
                    _logger.LogError("User " + AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext) + " SearchRepository failed with statuscode " + response.StatusCode);
                    allElementsRetrieved = true;
                }
            }

            if (repository?.Data == null || !repository.Data.Any())
            {
                return(repository);
            }

            foreach (Repository repo in repository.Data)
            {
                if (string.IsNullOrEmpty(repo.Owner?.Login))
                {
                    continue;
                }

                repo.IsClonedToLocal = IsLocalRepo(repo.Owner.Login, repo.Name);
                Organization org = await GetCachedOrg(repo.Owner.Login);

                if (org.Id != -1)
                {
                    repo.Owner.UserType = UserType.Org;
                }
            }

            return(repository);
        }
Ejemplo n.º 51
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;
            bool             organizationAuditingFlag;
            bool             accountAuditingFlag;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    Console.WriteLine("Enabling auditing on the organization and account entities.");

                    // Enable auditing on the organization.
                    // First, get the organization's ID from the system user record.
                    Guid orgId = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).OrganizationId;

                    // Next, retrieve the organization's record.
                    var retrivedOrg = service.Retrieve(Organization.EntityLogicalName, orgId,
                                                       new ColumnSet(new string[] { "isauditenabled" })) as Organization;

                    // Cache the value to set it back later
                    organizationAuditingFlag = retrivedOrg.IsAuditEnabled.Value;

                    // Enable auditing on the organization.
                    Organization orgToUpdate = new Organization {
                        Id             = orgId,
                        IsAuditEnabled = true
                    };
                    service.Update(orgToUpdate);

                    // Enable auditing on account entities.
                    accountAuditingFlag = EnableEntityAuditing(service, Account.EntityLogicalName, true);

                    #endregion Enable Auditing for an Account
                    #region Retrieve the Record Change History
                    Console.WriteLine("Retrieving the account change history.\n");

                    // Retrieve the audit history for the account and display it.
                    var changeRequest = new RetrieveRecordChangeHistoryRequest {
                        Target = new EntityReference(Account.EntityLogicalName, _newAccountId)
                    };

                    var changeResponse =
                        (RetrieveRecordChangeHistoryResponse)service.Execute(changeRequest);

                    AuditDetailCollection details = changeResponse.AuditDetailCollection;

                    foreach (AttributeAuditDetail detail in details.AuditDetails)
                    {
                        // Display some of the detail information in each audit record.
                        DisplayAuditDetails(service, detail);
                    }
                    #endregion Retrieve the Record Change History

                    #region Retrieve the Attribute Change History

                    // Update the Telephone1 attribute in the Account entity record.
                    var accountToUpdate = new Account {
                        AccountId  = _newAccountId,
                        Telephone1 = "123-555-5555"
                    };

                    service.Update(accountToUpdate);
                    Console.WriteLine("Updated the Telephone1 field in the Account entity.");

                    // Retrieve the attribute change history.
                    Console.WriteLine("Retrieving the attribute change history for Telephone1.");
                    var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                    {
                        Target = new EntityReference(
                            Account.EntityLogicalName, _newAccountId),
                        AttributeLogicalName = "telephone1"
                    };

                    var attributeChangeHistoryResponse =
                        (RetrieveAttributeChangeHistoryResponse)service.Execute(attributeChangeHistoryRequest);

                    // Display the attribute change history.
                    details = attributeChangeHistoryResponse.AuditDetailCollection;

                    foreach (var detail in details.AuditDetails)
                    {
                        DisplayAuditDetails(service, detail);
                    }

                    // Save an Audit record ID for later use.
                    Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                    #endregion Retrieve the Attribute Change History

                    #region Retrieve the Audit Details
                    Console.WriteLine("Retrieving audit details for an audit record.");

                    // Retrieve the audit details and display them.
                    var auditDetailsRequest = new RetrieveAuditDetailsRequest
                    {
                        AuditId = auditSampleId
                    };

                    var auditDetailsResponse =
                        (RetrieveAuditDetailsResponse)service.Execute(auditDetailsRequest);

                    DisplayAuditDetails(service, auditDetailsResponse.AuditDetail);

                    #endregion Retrieve the Audit Details

                    #region Revert Auditing
                    // Set the organization and account auditing flags back to the old values

                    orgToUpdate.IsAuditEnabled = organizationAuditingFlag;
                    service.Update(orgToUpdate);

                    EnableEntityAuditing(service, Account.EntityLogicalName, accountAuditingFlag);

                    #endregion Revert Auditing

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate

                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Ejemplo n.º 52
0
        public static LyncUserResult CreateLyncUser(int itemId, int accountId, int lyncUserPlanId)
        {
            LyncUserResult res = TaskManager.StartResultTask <LyncUserResult>("LYNC", "CREATE_LYNC_USER");

            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);

            if (accountCheck < 0)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.NOT_AUTHORIZED);
                return(res);
            }


            LyncUser retLyncUser = new LyncUser();
            bool     isLyncUser;

            isLyncUser = DataProvider.CheckLyncUserExists(accountId);
            if (isLyncUser)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_IS_ALREADY_LYNC_USER);
                return(res);
            }

            OrganizationUser user;

            user = OrganizationController.GetAccount(itemId, accountId);
            if (user == null)
            {
                TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT);
                return(res);
            }

            user = OrganizationController.GetUserGeneralSettings(itemId, accountId);
            if (string.IsNullOrEmpty(user.FirstName))
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_FIRST_NAME_IS_NOT_SPECIFIED);
                return(res);
            }

            if (string.IsNullOrEmpty(user.LastName))
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_LAST_NAME_IS_NOT_SPECIFIED);
                return(res);
            }

            bool quota = CheckQuota(itemId);

            if (!quota)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_QUOTA_HAS_BEEN_REACHED);
                return(res);
            }


            LyncServer lync;

            try
            {
                bool bReloadConfiguration = false;

                Organization org = (Organization)PackageController.GetPackageItem(itemId);
                if (org == null)
                {
                    throw new ApplicationException(
                              string.Format("Organization is null. ItemId={0}", itemId));
                }

                int lyncServiceId = GetLyncServiceID(org.PackageId);
                lync = GetLyncServer(lyncServiceId, org.ServiceId);

                if (string.IsNullOrEmpty(org.LyncTenantId))
                {
                    PackageContext cntx = PackageController.GetPackageContext(org.PackageId);

                    org.LyncTenantId = lync.CreateOrganization(org.OrganizationId,
                                                               org.DefaultDomain,
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_CONFERENCING].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ALLOWVIDEO].QuotaAllocatedValue),
                                                               Convert.ToInt32(cntx.Quotas[Quotas.LYNC_MAXPARTICIPANTS].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_FEDERATION].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ENTERPRISEVOICE].QuotaAllocatedValue));

                    if (string.IsNullOrEmpty(org.LyncTenantId))
                    {
                        TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ENABLE_ORG);
                        return(res);
                    }
                    else
                    {
                        DomainInfo domain = ServerController.GetDomain(org.DefaultDomain);

                        //Add the service records
                        if (domain != null)
                        {
                            if (domain.ZoneItemId != 0)
                            {
                                ServerController.AddServiceDNSRecords(org.PackageId, ResourceGroups.Lync, domain, "");
                            }
                        }

                        PackageController.UpdatePackageItem(org);

                        bReloadConfiguration = true;
                    }
                }

                if (lync.GetOrganizationTenantId(org.OrganizationId) == string.Empty)
                {
                    PackageContext cntx = PackageController.GetPackageContext(org.PackageId);

                    org.LyncTenantId = lync.CreateOrganization(org.OrganizationId,
                                                               org.DefaultDomain,
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_CONFERENCING].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ALLOWVIDEO].QuotaAllocatedValue),
                                                               Convert.ToInt32(cntx.Quotas[Quotas.LYNC_MAXPARTICIPANTS].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_FEDERATION].QuotaAllocatedValue),
                                                               Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ENTERPRISEVOICE].QuotaAllocatedValue));

                    if (string.IsNullOrEmpty(org.LyncTenantId))
                    {
                        TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ENABLE_ORG);
                        return(res);
                    }
                    else
                    {
                        PackageController.UpdatePackageItem(org);

                        bReloadConfiguration = true;
                    }
                }


                LyncUserPlan plan = GetLyncUserPlan(itemId, lyncUserPlanId);

                if (!lync.CreateUser(org.OrganizationId, user.UserPrincipalName, plan))
                {
                    TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER);
                    return(res);
                }

                if (bReloadConfiguration)
                {
                    LyncControllerAsync userWorker = new LyncControllerAsync();
                    userWorker.LyncServiceId         = lyncServiceId;
                    userWorker.OrganizationServiceId = org.ServiceId;
                    userWorker.Enable_CsComputerAsync();
                }
            }
            catch (Exception ex)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER, ex);
                return(res);
            }

            try
            {
                DataProvider.AddLyncUser(accountId, lyncUserPlanId, user.UserPrincipalName);
            }
            catch (Exception ex)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER_TO_DATABASE, ex);
                return(res);
            }

            res.IsSuccess = true;
            TaskManager.CompleteResultTask();
            return(res);
        }
Ejemplo n.º 53
0
        public CsvExportMineTests(CustomWebApplicationFactory <JinCreek.Server.Admin.Startup> factory)
        {
            _client  = factory.CreateClient();
            _context = factory.Services.GetService <IServiceScopeFactory>().CreateScope().ServiceProvider.GetService <MainDbContext>();

            Utils.RemoveAllEntities(_context);

            _context.Add(_org1    = Utils.CreateOrganization(code: 1, name: "org1"));
            _context.Add(_org2    = Utils.CreateOrganization(code: 2, name: "org2"));
            _context.Add(_domain1 = new Domain {
                Id = Guid.NewGuid(), Name = "domain01", Organization = _org1
            });
            _context.Add(_domain2 = new Domain {
                Id = Guid.NewGuid(), Name = "domain03", Organization = _org2
            });
            _context.Add(_userGroup1 = new UserGroup {
                Id = Guid.NewGuid(), Name = "userGroup1", Domain = _domain1
            });
            _context.Add(_userGroup2 = new UserGroup {
                Id = Guid.NewGuid(), Name = "userGroup2", Domain = _domain2
            });
            _context.Add(_user0 = new SuperAdmin {
                AccountName = "user0", Password = Utils.HashPassword("user0")
            });                                                                                                      // スーパー管理者
            _context.Add(_user1 = new UserAdmin {
                AccountName = "user1", Password = Utils.HashPassword("user1"), DomainId = _domain1.Id
            });                                                                                                                             // ユーザー管理者
            _context.Add(_user2 = new UserAdmin {
                AccountName = "user2", Password = Utils.HashPassword("user2"), DomainId = _domain1.Id
            });                                                                                                                             // ユーザー管理者
            _context.Add(_user2a = new UserAdmin {
                AccountName = "user2a", Password = Utils.HashPassword("user2a"), DomainId = _domain1.Id
            });                                                                                                                                // ユーザー管理者
            _context.Add(_user3 = new GeneralUser()
            {
                AccountName = "user2", DomainId = _domain2.Id
            });
            _context.Add(_simGroup1 = new SimGroup()
            {
                Id                      = Guid.NewGuid(),
                Name                    = "simGroup1",
                Organization            = _org1,
                Apn                     = "apn",
                AuthenticationServerIp  = "AuthenticationServerIp",
                IsolatedNw1IpPool       = "IsolatedNw1IpPool",
                IsolatedNw1SecondaryDns = "IsolatedNw1SecondaryDns",
                IsolatedNw1IpRange      = "IsolatedNw1IpRange",
                IsolatedNw1PrimaryDns   = "IsolatedNw1PrimaryDns",
                NasIp                   = "NasIp",
                PrimaryDns              = "PrimaryDns",
                SecondaryDns            = "SecondaryDns",
                UserNameSuffix          = ""
            });
            _context.Add(_sim1 = new Sim() // 組織 : '自組織
            {
                Msisdn   = "msisdn01",
                Imsi     = "imsi01",
                IccId    = "iccid01",
                UserName = "******",
                Password = "******",
                SimGroup = _simGroup1
            });
            _context.Add(_sim2 = new Sim() // 組織 : '自組織
            {
                Msisdn   = "msisdn02",
                Imsi     = "imsi02",
                IccId    = "iccid02",
                UserName = "******",
                Password = "******",
                SimGroup = _simGroup1
            });
            _context.Add(_device1 = new Device()
            {
                LteModule     = null,
                Domain        = _domain1,
                Name          = "device01",
                UseTpm        = true,
                ManagedNumber = "001",
                WindowsSignInListCacheDays = 1,
            });
            _context.Add(_device2 = new Device()
            {
                LteModule     = null,
                Domain        = _domain1,
                Name          = "device02",
                UseTpm        = true,
                ManagedNumber = "001",
                WindowsSignInListCacheDays = 1,
            });
            _context.Add(_simDevice1 = new SimAndDevice() // 組織 : '自組織
            {
                Sim                    = _sim1,
                Device                 = _device1,
                IsolatedNw2Ip          = "127.0.0.1",
                AuthenticationDuration = 1,
                StartDate              = DateTime.Parse("2020-02-07"),
                EndDate                = DateTime.Now.AddHours(6.00)
            });
            _context.Add(_simDevice2 = new SimAndDevice() // 組織 : '自組織
            {
                Sim                    = _sim2,
                Device                 = _device1,
                IsolatedNw2Ip          = "127.0.0.1",
                AuthenticationDuration = 1,
                StartDate              = DateTime.Parse("2020-02-07"),
                EndDate                = DateTime.Now.AddHours(6.00)
            });
            _context.Add(_simDevice3 = new SimAndDevice() // 組織 : '自組織
            {
                Sim                    = _sim2,
                Device                 = _device2,
                IsolatedNw2Ip          = "127.0.0.1",
                AuthenticationDuration = 1,
                StartDate              = DateTime.Parse("2020-02-07"),
                EndDate                = DateTime.Now.AddHours(6.00)
            });
            _context.SaveChanges();
        }
Ejemplo n.º 54
0
        public static LyncUserResult SetLyncUserGeneralSettings(int itemId, int accountId, string sipAddress, string lineUri)
        {
            LyncUserResult res = TaskManager.StartResultTask <LyncUserResult>("LYNC", "SET_LYNC_USER_GENERAL_SETTINGS");

            string PIN = "";

            string[] uriAndPin = ("" + lineUri).Split(':');

            if (uriAndPin.Length > 0)
            {
                lineUri = uriAndPin[0];
            }
            if (uriAndPin.Length > 1)
            {
                PIN = uriAndPin[1];
            }

            LyncUser user = null;

            try
            {
                Organization org = (Organization)PackageController.GetPackageItem(itemId);
                if (org == null)
                {
                    throw new ApplicationException(
                              string.Format("Organization is null. ItemId={0}", itemId));
                }

                int        lyncServiceId = GetLyncServiceID(org.PackageId);
                LyncServer lync          = GetLyncServer(lyncServiceId, org.ServiceId);

                OrganizationUser usr;
                usr = OrganizationController.GetAccount(itemId, accountId);

                if (usr != null)
                {
                    user = lync.GetLyncUserGeneralSettings(org.OrganizationId, usr.UserPrincipalName);
                }

                if (user != null)
                {
                    LyncUserPlan plan = ObjectUtils.FillObjectFromDataReader <LyncUserPlan>(DataProvider.GetLyncUserPlanByAccountId(accountId));

                    if (plan != null)
                    {
                        user.LyncUserPlanId   = plan.LyncUserPlanId;
                        user.LyncUserPlanName = plan.LyncUserPlanName;
                    }


                    if (!string.IsNullOrEmpty(sipAddress))
                    {
                        if (user.SipAddress != sipAddress)
                        {
                            if (sipAddress != usr.UserPrincipalName)
                            {
                                if (DataProvider.LyncUserExists(accountId, sipAddress))
                                {
                                    TaskManager.CompleteResultTask(res, LyncErrorCodes.ADDRESS_ALREADY_USED);
                                    return(res);
                                }
                            }
                            user.SipAddress = sipAddress;
                        }
                    }

                    user.LineUri = lineUri;
                    user.PIN     = PIN;

                    lync.SetLyncUserGeneralSettings(org.OrganizationId, usr.UserPrincipalName, user);

                    DataProvider.UpdateLyncUser(accountId, sipAddress);
                }
            }
            catch (Exception ex)
            {
                TaskManager.CompleteResultTask(res, LyncErrorCodes.FAILED_SET_SETTINGS, ex);
                return(res);
            }

            res.IsSuccess = true;
            TaskManager.CompleteResultTask();
            return(res);
        }
Ejemplo n.º 55
0
        public void FixtureSetUp()
        {
            _runDbConsole = false;  // set to true to open H2 console

            if (_runDbConsole)
            {
                Environment.SetEnvironmentVariable("IGNITE_H2_DEBUG_CONSOLE", "true");
            }

            Ignition.Start(GetConfig());
            Ignition.Start(GetConfig("grid2"));

            // Populate caches
            var cache       = GetPersonCache();
            var personCache = GetSecondPersonCache();

            for (var i = 0; i < PersonCount; i++)
            {
                cache.Put(i, new Person(i, string.Format(" Person_{0}  ", i))
                {
                    Address = new Address {
                        Zip = i, Street = "Street " + i, AliasTest = i
                    },
                    OrganizationId = i % 2 + 1000,
                    Birthday       = StartDateTime.AddYears(i),
                    AliasTest      = -i
                });

                var i2 = i + PersonCount;
                personCache.Put(i2, new Person(i2, "Person_" + i2)
                {
                    Address = new Address {
                        Zip = i2, Street = "Street " + i2
                    },
                    OrganizationId = i % 2 + 1000,
                    Birthday       = StartDateTime.AddYears(i)
                });
            }

            var orgCache = GetOrgCache();

            orgCache[1000] = new Organization {
                Id = 1000, Name = "Org_0"
            };
            orgCache[1001] = new Organization {
                Id = 1001, Name = "Org_1"
            };
            orgCache[1002] = new Organization {
                Id = 1002, Name = null
            };

            var roleCache = GetRoleCache();

            roleCache[new RoleKey(1, 101)] = new Role {
                Name = "Role_1", Date = StartDateTime
            };
            roleCache[new RoleKey(2, 102)] = new Role {
                Name = "Role_2", Date = StartDateTime.AddYears(1)
            };
            roleCache[new RoleKey(3, 103)] = new Role {
                Name = null, Date = StartDateTime.AddHours(5432)
            };
        }
Ejemplo n.º 56
0
    private string GenerateAdministrators(Organization org, Geography geo)
    {
        RoleLookup officers = RoleLookup.FromGeographyAndOrganization(geo.Identity, org.Identity);

        return(GenerateAdministrators(org, geo, officers));
    }
Ejemplo n.º 57
0
 public static void AssertAreEqual(Organization expected, Organization actual)
 {
     Assert.AreEqual(expected.Description, actual.Description);
     Assert.AreEqual(expected.Name, actual.Name);
 }
Ejemplo n.º 58
0
 public void Init()
 {
     instance = new Organization();
 }
Ejemplo n.º 59
0
 public Task SendOrganizationAddedAsync(User sender, Organization organization, User user)
 {
     return(Task.CompletedTask);
 }
Ejemplo n.º 60
0
 public ItemGroups(Organization organization) : base(organization)
 {
 }