示例#1
0
        public IM_View(CoreUI ui, IMService im, ulong key)
        {
            InitializeComponent();

            UI = ui;
            Core = ui.Core;
            IM    = im;
            Locations = IM.Core.Locations;
            UserID = key;

            IM.ActiveUsers.Add(UserID);

            UpdateName();

            // do here so window can be found and multiples not created for the same user
            IM.MessageUpdate += new IM_MessageHandler(IM_MessageUpdate);
            IM.StatusUpdate += new IM_StatusHandler(IM_StatusUpdate);
            Core.KeepDataGui += new KeepDataHandler(Core_KeepData);

            MessageTextBox.Core = Core;
            MessageTextBox.ContextMenuStrip.Items.Insert(0, new ToolStripSeparator());

            TimestampMenu = new ToolStripMenuItem("Timestamps", ViewRes.timestamp, new EventHandler(Menu_Timestamps));
            MessageTextBox.ContextMenuStrip.Items.Insert(0, TimestampMenu);
        }
示例#2
0
        public void GetByCityState_ValidCityNullState_ThrowsArgumentException()
        {
            var locationService = new LocationService(new FakeLocationRepository());

            var argEx = Assert.Throws<ArgumentException>(() => locationService.GetByCityState("San Luis Obispo", null));
            Assert.True(argEx.Message.StartsWith("State must be non-null"));
        }
        public void SuccessMatch()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Domain details
            var start = new DateTime(1999, 12, 31);
            var finish = new DateTime(2020, 1, 1);
            var system = new SourceSystem { Name = "Endur" };
            var mapping = new LocationMapping
            {
                System = system,
                MappingValue = "A"
            };
            var location = new Location
            {
                Id = 1,
                Validity = new DateRange(start, finish)
            };
            //Location.AddDetails(details);
            location.ProcessMapping(mapping);

            // Contract details
            var identifier = new EnergyTrading.Mdm.Contracts.MdmId
            {
                SystemName = "Endur",
                Identifier = "A"
            };
            var cDetails = new EnergyTrading.MDM.Contracts.Sample.LocationDetails();

            mappingEngine.Setup(x => x.Map<LocationMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)).Returns(identifier);
            mappingEngine.Setup(x => x.Map<Location, EnergyTrading.MDM.Contracts.Sample.LocationDetails>(location)).Returns(cDetails);
            validatorFactory.Setup(x => x.IsValid(It.IsAny<MappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);

            var list = new List<LocationMapping> { mapping };
            repository.Setup(x => x.Queryable<LocationMapping>()).Returns(list.AsQueryable());

            var request = new MappingRequest { SystemName = "Endur", Identifier = "A", ValidAt = SystemTime.UtcNow(), Version = 1 };

            // Act
            var response = service.Map(request);
            var candidate = response.Contract;

            // Assert
            mappingEngine.Verify(x => x.Map<LocationMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping));
            mappingEngine.Verify(x => x.Map<Location, EnergyTrading.MDM.Contracts.Sample.LocationDetails>(location));
            repository.Verify(x => x.Queryable<LocationMapping>());
            Assert.IsNotNull(candidate, "Contract null");
            Assert.AreEqual(2, candidate.Identifiers.Count, "Identifier count incorrect");
            // NB This is order dependent
            Assert.AreSame(identifier, candidate.Identifiers[1], "Different identifier assigned");
            Assert.AreSame(cDetails, candidate.Details, "Different details assigned");
            Assert.AreEqual(start, candidate.MdmSystemData.StartDate, "Start date differs");
            Assert.AreEqual(finish, candidate.MdmSystemData.EndDate, "End date differs");
        }
示例#4
0
        public void GetByCityState_NullCityValidState_ThrowsArgumentException()
        {
            var locationService = new LocationService(new FakeLocationRepository());

            var argEx = Assert.Throws<ArgumentException>(() => locationService.GetByCityState(null, "ZZ"));
            Assert.True(argEx.Message.StartsWith("City must be non-null"));
        }
        public void EarlierVersionRaisesVersionConflict()
        {
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            validatorFactory.Setup(x => x.IsValid(It.IsAny<EnergyTrading.MDM.Contracts.Sample.Location>(), It.IsAny<IList<IRule>>())).Returns(true);

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            var cd = new EnergyTrading.MDM.Contracts.Sample.LocationDetails();
            var nexus = new EnergyTrading.Mdm.Contracts.SystemData { StartDate = new DateTime(2012, 1, 1) };
            var contract = new EnergyTrading.MDM.Contracts.Sample.Location { Details = cd, MdmSystemData = nexus };

            var details = ObjectMother.Create<Location>();
            details.Id = 1;
            var entity = ObjectMother.Create<Location>();
            entity.Id = 2;
            entity.AddDetails(details);

            repository.Setup(x => x.FindOne<Location>(1)).Returns(entity);

            // Act
            service.Update(1, 1, contract);
        }
        public void ValidContractAdded()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);
            var identifier = new MdmId { SystemName = "Test", Identifier = "A" };
            var message = new CreateMappingRequest
            {
                EntityId = 12,
                Mapping = identifier
            };

            var system = new MDM.SourceSystem { Name = "Test" };
            var mapping = new LocationMapping { System = system, MappingValue = "A" };
            validatorFactory.Setup(x => x.IsValid(It.IsAny<CreateMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);
            mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.MdmId, LocationMapping>(identifier)).Returns(mapping);

            var location = new MDM.Location();
            repository.Setup(x => x.FindOne<MDM.Location>(12)).Returns(location);

            // Act
            var candidate = (LocationMapping)service.CreateMapping(message);

            // Assert
            Assert.AreSame(mapping, candidate);
            repository.Verify(x => x.Save(location));
            repository.Verify(x => x.Flush());
        }
示例#7
0
        public LinkNode(OpLink link, LinkTree parent)
        {
            Link = link;
            ParentView = parent;
            Trust = parent.Trust;
            Locations = parent.Core.Locations;

            UpdateStatus();
        }
示例#8
0
 public IList<AdvanticSignal> GetAdvanticSignal(String userId)
 {
     List<AdvanticSignal> advanticSignalList = new List<AdvanticSignal>();
     LocationService locationService = new LocationService();
     User user= new User(userId);
     List<Location> locationList = locationService.GetLocationsByUser(user);
     foreach (Location location in locationList)
         advanticSignalList.AddRange(GetAdvanticSignal(user, location));
     return advanticSignalList;
 }
示例#9
0
        public void GetByCityState_ValidCityInvalidState_ReturnsEmptyList()
        {
            // Arrange
            var locationService = new LocationService(new FakeLocationRepository());

            // Act
            IEnumerable<Location> nonsenseLocations = locationService.GetByCityState("Sacramento", "BB");

            // Assert
            Assert.True(nonsenseLocations.Count() == 0);
        }
        public void NullRequestErrors()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Act
            service.CrossMap(null);
        }
示例#11
0
        public Controller(CountryService countryService, CompanyService companyService, DeliveryService deliveryService, PriceService priceService, RouteService routeService, LocationService locationService, StatisticsService statisticsService, EventService eventService)
        {
            this.countryService = countryService;
            this.companyService = companyService;
            this.deliveryService = deliveryService;
            this.priceService = priceService;
            this.routeService = routeService;
            this.locationService = locationService;
            this.statisticsService = statisticsService;
            this.eventService = eventService;

            Network.Instance.MessageReceived += new Network.MessageReceivedDelegate(OnReceived);
        }
示例#12
0
文件: GPSManager.cs 项目: kyw/GPSTest
    void Start()
    {
        AndroidJNI.AttachCurrentThread();
        gpsActivityJavaClass = new AndroidJavaClass("com.fobikr.gpstest.GPSTest");
        locationService = Input.location;

        // First, check if user has location service enabled
        if (!locationService.isEnabledByUser)
            GameObject.Find("gps_output2").guiText.text = "Unable to determine device location";
        // Start service before querying location
        locationService.Start(0.5f, 0.5f);

        CheckService();
    }
        public void NullContractInvalid()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            validatorFactory.Setup(x => x.IsValid(It.IsAny<object>(), It.IsAny<IList<IRule>>())).Returns(false);

            // Act
            service.Create(null);
        }
示例#14
0
        public EditUserModel CreateEditUserModel(string userId)
        {
            var permissionFactory = new PermissionFactory();

            var userDetails = CreateUserDetailsModel(new UserService().GetUserById(userId));
            var locations = new LocationService().GetAllLocations().ToList();
            var permissions = new PermissionService().GetAllPermissions().Select(permissionFactory.CreatePermissionModel).ToList();

            return new EditUserModel()
            {
                Locations = locations,
                Permissions = permissions,
                UserDetails = userDetails
            };
        }
示例#15
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var locationService = new LocationService();
            var address = new Domain.Address();
            var person = new Domain.PersonEntry(locationService, address);
            var vm = new UI.PersonEntry.PersonEntryViewModel(person, new SchedulerProvider());
            vm.Load();

            var window = new UI.PersonEntry.PersonEntryView(vm);
            vm.CloseCommand = new DelegateCommand(window.Close);

            this.MainWindow = window;
            window.Show();
        }
        public void InvalidContractNotSaved()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            var contract = new EnergyTrading.MDM.Contracts.Sample.Location();

            validatorFactory.Setup(x => x.IsValid(It.IsAny<object>(), It.IsAny<IList<IRule>>())).Returns(false);

            // Act
            service.Create(contract);
        }
示例#17
0
 public UserDetailsListModel CreateUserDetailsListModel(string userNameFilter, int pageIndex, int pageSize)
 {
 
     var permissionFactory = new PermissionFactory();
 
     var userDetailsModels = new UserService().GetUsersByName(userNameFilter, pageIndex, pageSize).Select(CreateUserDetailsModel).ToList();
 
     var locations = new LocationService().GetAllLocations();
 
     var permissions = new PermissionService().GetAllPermissions().Select(permissionFactory.CreatePermissionModel).ToList();
 
     return new UserDetailsListModel()
     {
         Locations = locations,
         Permission = permissions,
         Users = new Common.PageableList<UserDetailsModel>(userDetailsModels, pageSize, pageIndex)
     };
 }
示例#18
0
        public IMService(OpCore core)
        {
            Core = core;
            Network = Core.Network;
            Locations = core.Locations;

            Core.SecondTimerEvent += Core_SecondTimer;
            Core.KeepDataCore += new KeepDataHandler(Core_KeepData);

            Network.RudpControl.SessionUpdate += new SessionUpdateHandler(Session_Update);
            Network.RudpControl.SessionData[ServiceID, 0] += new SessionDataHandler(Session_Data);
            Network.RudpControl.KeepActive += new KeepActiveHandler(Session_KeepActive);

            Core.Locations.LocationUpdate += new LocationUpdateHandler(Location_Update);
            Core.Locations.KnowOnline += new KnowOnlineHandler(Location_KnowOnline);

            if (Core.Trust != null)
                Core.Trust.LinkUpdate += new LinkUpdateHandler(Trust_Update);
        }
        public void ValidDetailsSaved()
        {
            const int mappingId = 12;

            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // NB Don't put mappingId here - service assigns it
            var identifier = new MdmId { SystemName = "Test", Identifier = "A" };
            var message = new AmendMappingRequest { MappingId = mappingId, Mapping = identifier, Version = 34 };

            var start = new DateTime(2000, 12, 31);
            var finish = DateUtility.Round(SystemTime.UtcNow().AddDays(5));
            var s1 = new SourceSystem { Name = "Test" };
            var m1 = new LocationMapping { Id = mappingId, System = s1, MappingValue = "1", Version = 34UL.GetVersionByteArray(), Validity = new DateRange(start, DateUtility.MaxDate) };
            var m2 = new LocationMapping { Id = mappingId, System = s1, MappingValue = "1", Validity = new DateRange(start, finish) };

            // NB We deliberately bypasses the business logic
            var entity = new MDM.Location();
            m1.Location = entity;
            entity.Mappings.Add(m1);

            validatorFactory.Setup(x => x.IsValid(It.IsAny<AmendMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);
            repository.Setup(x => x.FindOne<LocationMapping>(mappingId)).Returns(m1);
            mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.MdmId, LocationMapping>(identifier)).Returns(m2);

            // Act
            service.UpdateMapping(message);

            // Assert
            Assert.AreEqual(mappingId, identifier.MappingId, "Mapping identifier differs");
            // Proves we have an update not an add
            Assert.AreEqual(1, entity.Mappings.Count, "Mapping count differs");
            // NB Don't verify result of Update - already covered by LocationMappingFixture
            repository.Verify(x => x.Save(entity));
            repository.Verify(x => x.Flush());
        }
示例#20
0
        public void LocationService_GetAsync_ReturnsLocations()
        {
            //Arrange
            var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>();
            var mockDbContextScope = new Mock<IDbContextReadOnlyScope>();
            var mockEfDbContext = new Mock<EFDbContext>();
            mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object);
            mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object);

            var projectPerson1 = new Person { Id = "dummyUserId1", FirstName = "Firs1", LastName = "Last1" };

            var project1 = new Project { Id = "dummyId1", ProjectName = "Project1", ProjectAltName = "ProjectAlt1", IsActive_bl = true, ProjectCode = "CODE1", 
                ProjectPersons = new List<Person> { projectPerson1 } };

            var dbEntry1 = new Location { Id = "dummyEntryId1", LocName = "Loc1", LocAltName = "LocAlt1", IsActive_bl = false, Comments = "DummyComments1",
                AccessInfo = "DummyInfo1", AssignedToProject = project1 };
            var dbEntry2 = new Location { Id = "dummyEntryId2", LocName = "Loc2", LocAltName = "LocAlt2", IsActive_bl = true, Comments = "DummyComments2",
                AccessInfo = "DummyInfo2", AssignedToProject = project1 };
            var dbEntries = (new List<Location> { dbEntry1, dbEntry2 }).AsQueryable();

            var mockDbSet = new Mock<DbSet<Location>>();
            mockDbSet.As<IDbAsyncEnumerable<Location>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<Location>(dbEntries.GetEnumerator())); 
            mockDbSet.As<IQueryable<Location>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<Location>(dbEntries.Provider));
            mockDbSet.As<IQueryable<Location>>().Setup(m => m.Expression).Returns(dbEntries.Expression);
            mockDbSet.As<IQueryable<Location>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType);
            mockDbSet.As<IQueryable<Location>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator());
            mockDbSet.Setup(x => x.Include(It.IsAny<string>())).Returns(mockDbSet.Object);
            
            mockEfDbContext.Setup(x => x.Locations).Returns(mockDbSet.Object);

            var locationService = new LocationService(mockDbContextScopeFac.Object, projectPerson1.Id);

            //Act
            var resultLocations = locationService.GetAsync(new[] {dbEntry1.Id, dbEntry2.Id}).Result;
            
            //Assert
            Assert.IsTrue(resultLocations.Count == 1);
            Assert.IsTrue(resultLocations[0].LocAltName.Contains("LocAlt2"));
        }
        public AddPriceDialogBox(ClientState clientState, bool domestic)
        {
            InitializeComponent();
            var locationService = new LocationService(clientState);
            foreach (var routeNode in clientState.GetAllRouteNodes())
            {
                var cbi = new ComboBoxItem();
                if (routeNode is DistributionCentre)
                    cbi.Content = ((DistributionCentre)routeNode).Name;
                else if (routeNode is InternationalPort && !domestic)
                    cbi.Content = routeNode.Country.Name;
                cbi.Tag = routeNode.ID;
                this.origin.Items.Add(cbi);

                var cbi2 = new ComboBoxItem();
                if (routeNode is DistributionCentre )
                    cbi2.Content = ((DistributionCentre)routeNode).Name;
                else if (routeNode is InternationalPort && !domestic)
                    cbi2.Content = routeNode.Country.Name;
                cbi2.Tag = routeNode.ID;
                this.dest.Items.Add(cbi2);
            }
        }
示例#22
0
        static void Main()
        {
            var locationService = new LocationService();
            var locations = locationService.GetAll();

            var location = locationService.GetById(locations[0].Id);

            var hotelService = new HotelService();
            var hotel = hotelService.GetById(location.Hotels[0].Id);

            var roomService = new RoomService();
            var room = roomService.GetById(hotel.Rooms[0].Id);

            var photoService = new PhotoService();

            // Delete any existing photos
            foreach (var p in room.Photos)
            {
                photoService.Delete(p.Id);
            }

            Console.WriteLine("Adding photo to: {0}", room.Name);

            var photo = new Photo
            {
                Title = "A view of the room", Description = "A beautiful room with wonderful views of the neighbours walls", RoomId = room.Id
            };

            const string roomPhoto = @"Pictures\roomview.jpg";
            const string roomPhoto2 = @"Pictures\roomview_2.jpg";

            photo.Data = ReadPhotoData(roomPhoto);
            photoService.Insert(photo);

            photo.Data = ReadPhotoData(roomPhoto2);
            photoService.Update(photo);
        }
        public void EntityNotFound()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            var message = new CreateMappingRequest
                {
                    EntityId = 12,
                    Mapping = new MdmId { SystemName = "Test", Identifier = "A" }
                };

            validatorFactory.Setup(x => x.IsValid(It.IsAny<CreateMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);

            // Act
            var candidate = service.CreateMapping(message);

            // Assert
            Assert.IsNull(candidate);
        }
        public void EntityNotFound()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            var cd = new EnergyTrading.MDM.Contracts.Sample.LocationDetails();
            var nexus = new EnergyTrading.Mdm.Contracts.SystemData { StartDate = new DateTime(2012, 1, 1) };
            var contract = new EnergyTrading.MDM.Contracts.Sample.Location { Details = cd, MdmSystemData = nexus };

            validatorFactory.Setup(x => x.IsValid(It.IsAny<EnergyTrading.MDM.Contracts.Sample.Location>(), It.IsAny<IList<IRule>>())).Returns(true);

            // Act
            var response = service.Update(1, 1, contract);

            // Assert
            Assert.IsNotNull(response, "Response is null");
            Assert.IsFalse(response.IsValid, "Response is valid");
            Assert.AreEqual(ErrorType.NotFound, response.Error.Type, "ErrorType differs");
        }
        public void ValidContractIsSaved()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            var location = new Location();
            var contract = new EnergyTrading.MDM.Contracts.Sample.Location();

            validatorFactory.Setup(x => x.IsValid(It.IsAny<EnergyTrading.MDM.Contracts.Sample.Location>(), It.IsAny<IList<IRule>>())).Returns(true);
            mappingEngine.Setup(x => x.Map<EnergyTrading.MDM.Contracts.Sample.Location, Location>(contract)).Returns(location);

            // Act
            var expected = service.Create(contract);

            // Assert
            Assert.AreSame(expected, location, "Location differs");
            repository.Verify(x => x.Add(location));
            repository.Verify(x => x.Flush());
        }
        public ActionResult OldPost(string signature, string timestamp, string nonce, string echostr)
        {
            LocationService locationService = new LocationService();
            EventService    eventService    = new EventService();

            if (!CheckSignature.Check(signature, timestamp, nonce, Token))
            {
                return(Content("参数错误!"));
            }
            XDocument requestDoc = null;

            try
            {
                requestDoc = XDocument.Load(Request.Body);

                var requestMessage = RequestMessageFactory.GetRequestEntity(new DefaultMpMessageContext(), requestDoc);
                //如果不需要记录requestDoc,只需要:
                //var requestMessage = RequestMessageFactory.GetRequestEntity(Request.InputStream);

                requestDoc.Save(ServerUtility.ContentRootMapPath("~/App_Data/" + SystemTime.Now.Ticks + "_Request_" + requestMessage.FromUserName + ".txt"));//测试时可开启,帮助跟踪数据
                ResponseMessageBase responseMessage = null;
                switch (requestMessage.MsgType)
                {
                case RequestMsgType.Text:    //文字
                {
                    //TODO:交给Service处理具体信息,参考/Service/EventSercice.cs 及 /Service/LocationSercice.cs
                    var strongRequestMessage  = requestMessage as RequestMessageText;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage <ResponseMessageText>(requestMessage);
                    strongresponseMessage.Content =
                        string.Format(
                            "您刚才发送了文字信息:{0}\r\n您还可以发送【位置】【图片】【语音】等类型的信息,查看不同格式的回复。\r\nSDK官方地址:http://sdk.weixin.senparc.com",
                            strongRequestMessage.Content);
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Location:    //位置
                {
                    responseMessage = locationService.GetResponseMessage(requestMessage as RequestMessageLocation);
                    break;
                }

                case RequestMsgType.Image:    //图片
                {
                    //TODO:交给Service处理具体信息
                    var strongRequestMessage  = requestMessage as RequestMessageImage;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage <ResponseMessageNews>(requestMessage);
                    strongresponseMessage.Articles.Add(new Article()
                        {
                            Title       = "您刚才发送了图片信息",
                            Description = "您发送的图片将会显示在边上",
                            PicUrl      = strongRequestMessage.PicUrl,
                            Url         = "http://sdk.weixin.senparc.com"
                        });
                    strongresponseMessage.Articles.Add(new Article()
                        {
                            Title       = "第二条",
                            Description = "第二条带连接的内容",
                            PicUrl      = strongRequestMessage.PicUrl,
                            Url         = "http://sdk.weixin.senparc.com"
                        });
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Voice:    //语音
                {
                    //TODO:交给Service处理具体信息
                    var strongRequestMessage  = requestMessage as RequestMessageVoice;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage <ResponseMessageMusic>(requestMessage);
                    strongresponseMessage.Music.MusicUrl = "http://sdk.weixin.senparc.com/Content/music1.mp3";
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Event:    //事件
                {
                    responseMessage = eventService.GetResponseMessage(requestMessage as RequestMessageEventBase);
                    break;
                }

                default:
                    throw new ArgumentOutOfRangeException();
                }
                var responseDoc = Senparc.NeuChar.Helpers.EntityHelper.ConvertEntityToXml(responseMessage);
                responseDoc.Save(ServerUtility.ContentRootMapPath("~/App_Data/" + SystemTime.Now.Ticks + "_Response_" + responseMessage.ToUserName + ".txt"));//测试时可开启,帮助跟踪数据

                return(Content(responseDoc.ToString()));
                //如果不需要记录responseDoc,只需要:
                //return Content(responseMessage.ConvertEntityToXmlString());
            }
            catch (Exception ex)
            {
                using (
                    TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + SystemTime.Now.Ticks + ".txt")))
                {
                    tw.WriteLine(ex.Message);
                    tw.WriteLine(ex.InnerException.Message);
                    if (requestDoc != null)
                    {
                        tw.WriteLine(requestDoc.ToString());
                    }
                    tw.Flush();
                    tw.Close();
                }
                return(Content(""));
            }
        }
示例#27
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Device device = null;

            var rockContext      = new RockContext();
            var deviceService    = new DeviceService(rockContext);
            var attributeService = new AttributeService(rockContext);
            var locationService  = new LocationService(rockContext);

            int deviceId = hfDeviceId.Value.AsInteger();

            if (deviceId != 0)
            {
                device = deviceService.Get(deviceId);
            }

            if (device == null)
            {
                // Check for existing
                var existingDevice = deviceService.Queryable()
                                     .Where(d => d.Name == tbName.Text)
                                     .FirstOrDefault();

                if (existingDevice != null)
                {
                    nbDuplicateDevice.Text    = string.Format("A device already exists with the name '{0}'. Please use a different device name.", existingDevice.Name);
                    nbDuplicateDevice.Visible = true;
                }
                else
                {
                    device = new Device();
                    deviceService.Add(device);
                }
            }

            if (device != null)
            {
                device.Name              = tbName.Text;
                device.Description       = tbDescription.Text;
                device.IPAddress         = tbIpAddress.Text;
                device.DeviceTypeValueId = ddlDeviceType.SelectedValueAsInt().Value;
                device.PrintToOverride   = ( PrintTo )System.Enum.Parse(typeof(PrintTo), ddlPrintTo.SelectedValue);
                device.PrinterDeviceId   = ddlPrinter.SelectedValueAsInt();
                device.PrintFrom         = ( PrintFrom )System.Enum.Parse(typeof(PrintFrom), ddlPrintFrom.SelectedValue);

                if (device.Location == null)
                {
                    device.Location = new Location();
                }

                device.Location.GeoPoint = geopPoint.SelectedValue;
                device.Location.GeoFence = geopFence.SelectedValue;

                device.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, device);

                if (!device.IsValid || !Page.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                // Remove any deleted locations
                foreach (var location in device.Locations
                         .Where(l => !Locations.Keys.Contains(l.Id))
                         .ToList())
                {
                    device.Locations.Remove(location);
                }

                // Add any new locations
                var existingLocationIDs = device.Locations.Select(l => l.Id).ToList();
                foreach (var location in locationService.Queryable()
                         .Where(l =>
                                Locations.Keys.Contains(l.Id) &&
                                !existingLocationIDs.Contains(l.Id)))
                {
                    device.Locations.Add(location);
                }

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    device.SaveAttributeValues(rockContext);
                });

                Rock.CheckIn.KioskDevice.Remove(device.Id);

                NavigateToParentPage();
            }
        }
示例#28
0
    /// <summary>
    /// the game board is initialized, dots and background tiles are created
    /// </summary>
    void Start()
    {
        ownedCoinsText.text = "$" + StartGame.coins;
        if (StartGame.activeUpgrade == null)
        {
            bonusMoveImg.enabled = false;
        }
        else
        {
            bonusMoveImg.sprite  = StartGame.activeUpgrade.upgradeImg;
            bonusMoveImg.enabled = true;
        }
        location.text          = LevelSelection.districtName;
        isMultiplayer          = LevelSelection.isMultiplayer;
        playerNickname.enabled = false;

        if (isMultiplayer)
        {
            ownedCoinsText.enabled = false;
            curPlayerText.text     = curPlayer;
            slider.image.sprite    = MultiplayerMenu.player1Sprite;
            playerName.text        = player1Nickname;
            player2Name.text       = player2Nickname;
            player2Slider.gameObject.SetActive(true);
            player2Slider.image.sprite = MultiplayerMenu.player2Sprite;
            coinsText.enabled          = false;
            playerNickname.text        = curPlayer;
            playerNickname.enabled     = true;
        }
        else if (isOnlineMultiplayer)
        {
            ownedCoinsText.enabled = false;
            coinsText.enabled      = false;
            movesText.enabled      = false;
            if (Matchmaking.role == "host")
            {
                slider.image.sprite        = localCar;
                player2Slider.image.sprite = opponentCar;
            }
            else
            {
                curDistr = Matchmaking.level;
                player2Slider.image.sprite = localCar;
                slider.image.sprite        = opponentCar;
                curDistr = Matchmaking.level;
            }
            playerName.text  = Matchmaking.hostName;
            player2Name.text = Matchmaking.guestName;
            player2Slider.gameObject.SetActive(true);
            RestClient.Get("https://energyracer.firebaseio.com/lobby/" + Matchmaking.matchID + ".json").Then(response => {
                var result = JSON.Parse(response.Text);
                if (result == null)
                {
                    SceneManager.LoadScene("StartScene");
                }
                else
                {
                    InvokeRepeating("GetOpponentScore", 0.0f, 5f);
                }
            });
        }
        else if (!isMultiplayer && !isOnlineMultiplayer)
        {
            player2Name.enabled = false;
            playerName.enabled  = false;
            curPlayerText.text  = " ";
            player2Slider.gameObject.SetActive(false);
        }

        gameController = GameObject.Find("GameController");

        earnedCoins    = 30;
        coinsText.text = "+" + earnedCoins;

        width    = 7;
        height   = 7;
        allTiles = new BackgroundTile[width, height];
        allDots  = new GameObject[width, height];

        locationService = gameController.GetComponent <LocationService>();
        locationService.SendWeatherRequest();

        movesText.text = remainingMoves.ToString();
        if (!isMultiplayer && !isOnlineMultiplayer)
        {
            carImg = StartGame.activeCar.img;
            slider.image.sprite = carImg;
        }
    }
示例#29
0
        /// <summary>
        /// Shows the report.
        /// </summary>
        private void ShowMap()
        {
            string mapStylingFormat = @"
                        <style>
                            #map_wrapper {{
                                height: {0}px;
                            }}

                            #map_canvas {{
                                width: 100%;
                                height: 100%;
                                border-radius: 8px;
                            }}
                        </style>";

            lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight"));

            // add styling to map
            string styleCode = "null";

            DefinedValueCache dvcMapStyle = DefinedValueCache.Read(GetAttributeValue("MapStyle").AsGuid());

            if (dvcMapStyle != null)
            {
                styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle");
            }

            var    polygonColorList = GetAttributeValue("PolygonColors").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            string polygonColors    = polygonColorList.AsDelimited(",");

            string latitude    = "39.8282";
            string longitude   = "-98.5795";
            string zoom        = "4";
            var    orgLocation = GlobalAttributesCache.Read().OrganizationLocation;

            if (orgLocation != null && orgLocation.GeoPoint != null)
            {
                latitude  = orgLocation.GeoPoint.Latitude.Value.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
                longitude = orgLocation.GeoPoint.Longitude.Value.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
                zoom      = "12";
            }

            var rockContext     = new RockContext();
            var campuses        = CampusCache.All();
            var locationService = new LocationService(rockContext);

            CampusMarkersData = string.Empty;
            if (cbShowCampusLocations.Checked)
            {
                foreach (var campus in campuses)
                {
                    if (campus.LocationId.HasValue)
                    {
                        var location = locationService.Get(campus.LocationId.Value);
                        if (location != null && location.GeoPoint != null)
                        {
                            CampusMarkersData += string.Format("{{ location: new google.maps.LatLng({0},{1}), campusName:'{2}' }},", location.GeoPoint.Latitude, location.GeoPoint.Longitude, campus.Name);
                        }
                    }
                }

                CampusMarkersData.TrimEnd(new char[] { ',' });
            }

            // show geofences if a group was specified
            this.GroupId = this.PageParameter("GroupId").AsIntegerOrNull();
            if (!this.GroupId.HasValue && gpGroupToMap.Visible)
            {
                // if a page parameter wasn't specified, use the selected group from the filter
                this.GroupId = gpGroupToMap.SelectedValue.AsIntegerOrNull();
            }

            var groupMemberService      = new GroupMemberService(rockContext);
            var groupTypeFamily         = GroupTypeCache.GetFamilyGroupType();
            int groupTypeFamilyId       = groupTypeFamily.Id;
            var groupRoleAdultId        = groupTypeFamily.Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
            var groupLocationTypeHomeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()).Id;

            int[] connectionStatusValueIds = new[] {
                DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE.AsGuid()).Id,
                DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER.AsGuid()).Id
            };

            int recordStatusActiveId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;

            // if there is a DataViewId page parameter, use that instead of the Block or Filter dataview setting (the filter control won't be visible if there is a DataViewId page parameter)
            int? dataViewId   = this.PageParameter("DataViewId").AsIntegerOrNull();
            Guid?dataViewGuid = null;

            if (!dataViewId.HasValue)
            {
                dataViewGuid = this.GetAttributeValue("DataView").AsGuidOrNull();
            }

            if (ddlUserDataView.Visible)
            {
                dataViewGuid = ddlUserDataView.SelectedValue.AsGuidOrNull();
            }

            IQueryable <int> qryPersonIds = null;

            if (dataViewId.HasValue || dataViewGuid.HasValue)
            {
                DataView dataView = null;

                // if a DataViewId page parameter was specified, use that, otherwise use the blocksetting or filter selection
                if (dataViewId.HasValue)
                {
                    dataView = new DataViewService(rockContext).Get(dataViewId.Value);
                }
                else
                {
                    dataView = new DataViewService(rockContext).Get(dataViewGuid.Value);
                }

                if (dataView != null)
                {
                    List <string> errorMessages;
                    qryPersonIds = dataView.GetQuery(null, rockContext, null, out errorMessages).OfType <Person>().Select(a => a.Id);
                }
            }

            if (qryPersonIds == null)
            {
                // if no dataview was specified, show nothing
                qryPersonIds = new PersonService(rockContext).Queryable().Where(a => false).Select(a => a.Id);
            }

            var qryGroupMembers = groupMemberService.Queryable();

            var campusIds = cpCampuses.SelectedCampusIds;

            if (campusIds.Any())
            {
                qryGroupMembers = qryGroupMembers.Where(a => a.Group.CampusId.HasValue && campusIds.Contains(a.Group.CampusId.Value));
            }

            var qryLocationGroupMembers = qryGroupMembers
                                          .Where(a => a.Group.GroupTypeId == groupTypeFamilyId)
                                          .Where(a => a.Group.IsActive)
                                          .Select(a => new
            {
                GroupGeoPoint = a.Group.GroupLocations.Where(gl => gl.IsMappedLocation && gl.GroupLocationTypeValueId == groupLocationTypeHomeId && gl.Location.IsActive && gl.Location.GeoPoint != null).Select(x => x.Location.GeoPoint).FirstOrDefault(),
                a.Group.CampusId,
                a.PersonId
            })
                                          .Where(a => (a.GroupGeoPoint != null) && qryPersonIds.Contains(a.PersonId))
                                          .GroupBy(a => new { a.GroupGeoPoint.Latitude, a.GroupGeoPoint.Longitude })
                                          .Select(s => new
            {
                s.Key.Longitude,
                s.Key.Latitude,
                MemberCount = s.Count()
            });

            var locationList = qryLocationGroupMembers.ToList()
                               .Select(a => new LatLongWeighted(a.Latitude.Value, a.Longitude.Value, a.MemberCount))
                               .ToList();

            List <LatLongWeighted> points = locationList;

            // cluster points that are close together
            double?milesPerGrouping = this.GetAttributeValue("PointGrouping").AsDoubleOrNull();

            if (!milesPerGrouping.HasValue)
            {
                // default to a 1/10th of a mile
                milesPerGrouping = 0.10;
            }

            if (milesPerGrouping.HasValue && milesPerGrouping > 0)
            {
                var metersPerLatitudePHX  = 110886.79;
                var metersPerLongitudePHX = 94493.11;

                double metersPerMile = 1609.34;

                var squareLengthHeightMeters = metersPerMile * milesPerGrouping.Value;

                var longitudeRoundFactor = metersPerLongitudePHX / squareLengthHeightMeters;
                var latitudeRoundFactor  = metersPerLatitudePHX / squareLengthHeightMeters;

                points = points.GroupBy(a => new
                {
                    rLat  = Math.Round(a.Lat * latitudeRoundFactor),
                    rLong = Math.Round(a.Lat * longitudeRoundFactor),
                }).Select(a => new LatLongWeighted(a.Average(x => x.Lat), a.Average(x => x.Long), a.Sum(x => x.Weight))).ToList();
            }

            this.HeatMapData = points.Select(a => a.Weight > 1
                ? string.Format("{{location: new google.maps.LatLng({0}, {1}), weight: {2}}}", a.Lat, a.Long, a.Weight)
                : string.Format("new google.maps.LatLng({0}, {1})", a.Lat, a.Long)).ToList().AsDelimited(",\n");

            StyleCode               = styleCode;
            hfPolygonColors.Value   = polygonColors;
            hfCenterLatitude.Value  = latitude.ToString();
            hfCenterLongitude.Value = longitude.ToString();
            hfZoom.Value            = zoom.ToString();
        }
示例#30
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            if (_group != null && _occurrence != null)
            {
                var rockContext        = new RockContext();
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var locationService    = new LocationService(rockContext);

                bool dateAdjusted = false;

                DateTime startDate = _occurrence.Date;

                // If this is a manuall entered occurrence, check to see if date was changed
                if (!_occurrence.ScheduleId.HasValue)
                {
                    DateTime?originalDate = PageParameter("Date").AsDateTime();
                    if (originalDate.HasValue && originalDate.Value.Date != startDate.Date)
                    {
                        startDate    = originalDate.Value.Date;
                        dateAdjusted = true;
                    }
                }
                DateTime endDate = startDate.AddDays(1);

                var existingAttendees = attendanceService
                                        .Queryable("PersonAlias")
                                        .Where(a =>
                                               a.GroupId == _group.Id &&
                                               a.LocationId == _occurrence.LocationId &&
                                               a.ScheduleId == _occurrence.ScheduleId &&
                                               a.StartDateTime >= startDate &&
                                               a.StartDateTime < endDate);

                if (dateAdjusted)
                {
                    foreach (var attendee in existingAttendees)
                    {
                        attendee.StartDateTime = _occurrence.Date;
                    }
                }

                // If did not meet was selected and this was a manually entered occurrence (not based on a schedule/location)
                // then just delete all the attendance records instead of tracking a 'did not meet' value
                if (cbDidNotMeet.Checked && !_occurrence.ScheduleId.HasValue)
                {
                    foreach (var attendance in existingAttendees)
                    {
                        attendanceService.Delete(attendance);
                    }
                }
                else
                {
                    int?campusId = locationService.GetCampusIdForLocation(_occurrence.LocationId);
                    if (!campusId.HasValue)
                    {
                        campusId = _group.CampusId;
                    }
                    if (!campusId.HasValue && _allowCampusFilter)
                    {
                        var campus = CampusCache.Read(bddlCampus.SelectedValueAsInt() ?? 0);
                        if (campus != null)
                        {
                            campusId = campus.Id;
                        }
                    }

                    if (cbDidNotMeet.Checked)
                    {
                        // If the occurrence is based on a schedule, set the did not meet flags
                        foreach (var attendance in existingAttendees)
                        {
                            attendance.DidAttend   = null;
                            attendance.DidNotOccur = true;
                        }
                    }

                    foreach (var attendee in _attendees)
                    {
                        var attendance = existingAttendees
                                         .Where(a => a.PersonAlias.PersonId == attendee.PersonId)
                                         .FirstOrDefault();

                        if (attendance == null)
                        {
                            int?personAliasId = personAliasService.GetPrimaryAliasId(attendee.PersonId);
                            if (personAliasId.HasValue)
                            {
                                attendance               = new Attendance();
                                attendance.GroupId       = _group.Id;
                                attendance.ScheduleId    = _group.ScheduleId;
                                attendance.PersonAliasId = personAliasId;
                                attendance.StartDateTime = _occurrence.Date.Date.Add(_occurrence.StartTime);
                                attendance.LocationId    = _occurrence.LocationId;
                                attendance.CampusId      = campusId;
                                attendance.ScheduleId    = _occurrence.ScheduleId;

                                // check that the attendance record is valid
                                cvAttendance.IsValid = attendance.IsValid;
                                if (!cvAttendance.IsValid)
                                {
                                    cvAttendance.ErrorMessage = attendance.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                                    return;
                                }

                                attendanceService.Add(attendance);
                            }
                        }

                        if (attendance != null)
                        {
                            if (cbDidNotMeet.Checked)
                            {
                                attendance.DidAttend   = null;
                                attendance.DidNotOccur = true;
                            }
                            else
                            {
                                attendance.DidAttend   = attendee.Attended;
                                attendance.DidNotOccur = null;
                            }
                        }
                    }
                }

                if (_occurrence.LocationId.HasValue)
                {
                    Rock.CheckIn.KioskLocationAttendance.Flush(_occurrence.LocationId.Value);
                }

                rockContext.SaveChanges();

                Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowType = WorkflowTypeCache.Read(workflowTypeGuid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        try
                        {
                            var workflow = Workflow.Activate(workflowType, _group.Name);

                            workflow.SetAttributeValue("StartDateTime", _occurrence.Date.ToString("o"));
                            workflow.SetAttributeValue("Schedule", _group.Schedule.Guid.ToString());

                            List <string> workflowErrors;
                            new WorkflowService(rockContext).Process(workflow, _group, out workflowErrors);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }

                var qryParams = new Dictionary <string, string> {
                    { "GroupId", _group.Id.ToString() }
                };

                var groupTypeIds = PageParameter("GroupTypeIds");
                if (!string.IsNullOrWhiteSpace(groupTypeIds))
                {
                    qryParams.Add("GroupTypeIds", groupTypeIds);
                }

                NavigateToParentPage(qryParams);
            }
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            StringBuilder sbErrorMessages = new StringBuilder();

            if (!action.IsNotNull())
            {
                action.AddLogEntry("ReferenceValidation: Input (action) is null.");
                return(false);
            }

            int    refCount    = action.Activity.Workflow.GetAttributeValue("ReferenceCount").AsInteger();
            int    maxRef      = action.Activity.Workflow.GetAttributeValue("ReferenceLimit").AsInteger();
            string firstName   = action.Activity.GetAttributeValue("Firstname");
            string lastName    = action.Activity.GetAttributeValue("Lastname");
            string phoneNumber = action.Activity.GetAttributeValue("Phone");
            string phoneType   = action.Activity.GetAttributeValue("PhoneType");
            string email       = action.Activity.GetAttributeValue("Email");
            Guid?  addressGuid = action.Activity.GetAttributeValue("Address").AsGuidOrNull();

            if (refCount < maxRef)
            {
                validateName(firstName, lastName, sbErrorMessages);
                validatePhone(phoneNumber, phoneType, sbErrorMessages);
                validateEmail(email, sbErrorMessages);
                validateRelationships(action, refCount, maxRef, sbErrorMessages);

                LocationService locationService = new LocationService(new RockContext());
                Location        location        = locationService.Get(addressGuid.Value);
                if (addressGuid.HasValue && addressGuid != new Guid())
                {
                    validateAddress(location, sbErrorMessages);
                }
                else
                {
                    sbErrorMessages.AppendLine("<li> A valid address is required.</li>");
                }

                if (sbErrorMessages.Length == 0)
                {
                    ContactInfo userInfo = new ContactInfo();
                    userInfo.name        = formatName(firstName, lastName);
                    userInfo.address     = formatAddress(location);
                    userInfo.phoneNumber = formatPhone(phoneNumber);
                    userInfo.email       = email.Trim();

                    //if this is the 1st successful entry,
                    //store in the list for future comparison.
                    if (refCount == 0)
                    {
                        Reference.Clear();
                        Reference.Add(userInfo);
                    }
                    else if (refCount > 0 && refCount < maxRef)
                    {
                        for (var i = 0; i < Reference.Count; i++)
                        {
                            string fieldCorrectionStr = "";
                            if (checkForDuplicates(Reference[i], userInfo, out fieldCorrectionStr))
                            {
                                if (!String.IsNullOrEmpty(fieldCorrectionStr))
                                {
                                    string[] words = fieldCorrectionStr.Trim().Split(' ');
                                    foreach (var word in words)
                                    {
                                        sbErrorMessages.AppendFormat("<li>This reference's {0} matches that of reference {1}, Please correct.</li>", word.Trim(), i + 1);
                                    }
                                }
                                else
                                {
                                    action.AddLogEntry("ReferenceValidation: CheckForDuplicates returns true, but correction string is empty.");
                                }
                            }
                        }
                        if (sbErrorMessages.Length == 0)
                        {
                            Reference.Add(userInfo);
                        }
                    }
                }
            }
            Guid ErMsg = GetActionAttributeValue(action, "ErrorMessages").AsGuid();

            if (sbErrorMessages.Length > 0)
            {
                // If we get here, validation has failed
                SetWorkflowAttributeValue(action, ErMsg, sbErrorMessages.ToString());
                action.AddLogEntry("ReferenceValidation: Validation failed");
                return(reactivateCurrentActions(rockContext, action));
            }
            // If we get here, validation was successful
            SetWorkflowAttributeValue(action, ErMsg, string.Empty);
            action.AddLogEntry("ReferenceValidation: Validation successful");
            return(true);
        }
示例#32
0
 private void Awake()
 {
     _locationService = new LocationService();
     _locationService.Start();
 }
        public async void GetAllAvailableSpotsCount()
        {
            using (var transaction = Fixture.Connection.BeginTransaction())
            {
                using (var context = Fixture.CreateContext(transaction))
                {
                    // Arrange
                    var locationService = new LocationService(context);
                    var marinaService   = new MarinaService(context, locationService);
                    var service         = new BookingFormService(context, marinaService);
                    List <BookingLine> bookingLines1 = new List <BookingLine>
                    {
                        new BookingLine {
                            StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(2), BookingId = 1
                        },
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(3), EndDate = DateTime.Now.AddDays(5), BookingId = 1
                        },
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(6), EndDate = DateTime.Now.AddDays(9), BookingId = 1
                        },
                    };
                    List <BookingLine> bookingLines2 = new List <BookingLine>
                    {
                        new BookingLine {
                            StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(2), BookingId = 1
                        },
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(3), EndDate = DateTime.Now.AddDays(5), BookingId = 1
                        },
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(6), EndDate = DateTime.Now.AddDays(9), BookingId = 1
                        },
                    };
                    List <BookingLine> bookingLines3 = new List <BookingLine>
                    {
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(8), EndDate = DateTime.Now.AddDays(12), BookingId = 1
                        },
                    };
                    List <Spot> spots = new List <Spot>
                    {
                        new Spot {
                            SpotNumber = 1, MarinaId = 1, MaxDepth = 10, MaxLength = 20, MaxWidth = 30, BookingLines = bookingLines1, Available = true
                        },
                        new Spot {
                            SpotNumber = 2, MarinaId = 1, MaxDepth = 30, MaxLength = 40, MaxWidth = 30, BookingLines = bookingLines2, Available = true
                        },
                        new Spot {
                            SpotNumber = 3, MarinaId = 1, MaxDepth = 30, MaxLength = 30, MaxWidth = 30, BookingLines = bookingLines3, Available = true
                        }
                    };

                    List <Spot> spots2 = new List <Spot>
                    {
                        new Spot {
                            SpotNumber = 1, MarinaId = 1, MaxDepth = 10, MaxLength = 20, MaxWidth = 30, BookingLines = bookingLines1, Available = true
                        },
                        new Spot {
                            SpotNumber = 2, MarinaId = 1, MaxDepth = 30, MaxLength = 40, MaxWidth = 30, BookingLines = bookingLines2, Available = true
                        },
                        new Spot {
                            SpotNumber = 3, MarinaId = 1, MaxDepth = 30, MaxLength = 30, MaxWidth = 30, BookingLines = bookingLines3, Available = true
                        }
                    };

                    Marina marina = new Marina {
                        Name = "Hello", Spots = spots, MarinaOwnerId = 1
                    };
                    Marina marina2 = new Marina {
                        Name = "Better Marina", Spots = spots2, MarinaOwnerId = 1
                    };

                    Boat boat = new Boat {
                        Depth = 30, Length = 30, Width = 30, BoatOwnerId = 1
                    };
                    DateTime startDate = DateTime.Now;
                    DateTime endDate   = DateTime.Now.AddDays(1);

                    context.AddRange(spots);
                    context.AddRange(spots2);
                    context.Add(marina);
                    context.Add(marina2);
                    context.Add(boat);

                    context.SaveChanges();

                    // Act

                    var result = await service.GetAllAvailableSpotsCount(
                        new List <int> {
                        marina.MarinaId, marina2.MarinaId
                    },
                        boat.BoatId,
                        startDate,
                        endDate);

                    // Assert
                    Assert.NotNull(result);
                    output.WriteLine(HelperMethods.Serialize(result));
                }
            }
        }
示例#34
0
        public void GetLocationsInRadius_InvalidZipCodeInvalidRadiusExistingLocationsNearby_ThrowsArgumentOutOfRangeException()
        {
            var locationService = new LocationService(new FakeLocationRepository());

            var ex = Assert.Throws<ArgumentOutOfRangeException>(() => locationService.GetLocationsInRadius("abcdefkjkjkjkjk", -3.14159));
            Assert.True(ex.Message.StartsWith("Radius must be greater than 0"));
        }
示例#35
0
        public void GetLocationsInRadius_ValidZipCodeValidRadiusExistingLocationsNearby_ReturnsNonEmptyList()
        {
            var locationService = new LocationService(new FakeLocationRepository());

            IEnumerable<LocationInRadius> locationsNearby = locationService.GetLocationsInRadius("95814", 5.0);

            Assert.AreNotEqual(0, locationsNearby.Count());
        }
示例#36
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail(string itemKey, int itemKeyValue)
        {
            if (!itemKey.Equals("DeviceId"))
            {
                return;
            }

            using (new Rock.Data.UnitOfWorkScope())
            {
                pnlDetails.Visible = true;
                Device Device = null;

                if (!itemKeyValue.Equals(0))
                {
                    Device            = new DeviceService().Get(itemKeyValue);
                    lActionTitle.Text = ActionTitle.Edit(Device.FriendlyTypeName).FormatAsHtmlTitle();
                }
                else
                {
                    Device = new Device {
                        Id = 0
                    };
                    lActionTitle.Text = ActionTitle.Add(Device.FriendlyTypeName).FormatAsHtmlTitle();
                }

                LoadDropDowns();

                hfDeviceId.Value = Device.Id.ToString();

                tbName.Text        = Device.Name;
                tbDescription.Text = Device.Description;
                tbIpAddress.Text   = Device.IPAddress;
                ddlDeviceType.SetValue(Device.DeviceTypeValueId);
                ddlPrintTo.SetValue(Device.PrintToOverride.ConvertToInt().ToString());
                ddlPrinter.SetValue(Device.PrinterDeviceId);
                ddlPrintFrom.SetValue(Device.PrintFrom.ConvertToInt().ToString());

                string orgLocGuid = GlobalAttributesCache.Read().GetValue("OrganizationAddress");
                if (!string.IsNullOrWhiteSpace(orgLocGuid))
                {
                    Guid locGuid = Guid.Empty;
                    if (Guid.TryParse(orgLocGuid, out locGuid))
                    {
                        var location = new LocationService().Get(locGuid);
                        if (location != null)
                        {
                            gpGeoPoint.CenterPoint = location.GeoPoint;
                            gpGeoFence.CenterPoint = location.GeoPoint;
                        }
                    }
                }

                if (Device.Location != null)
                {
                    gpGeoPoint.SetValue(Device.Location.GeoPoint);
                    gpGeoFence.SetValue(Device.Location.GeoFence);
                }

                // render UI based on Authorized and IsSystem
                bool readOnly = false;

                nbEditModeMessage.Text = string.Empty;
                if (!IsUserAuthorized("Edit"))
                {
                    readOnly = true;
                    nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Device.FriendlyTypeName);
                }

                if (readOnly)
                {
                    lActionTitle.Text = ActionTitle.View(Device.FriendlyTypeName);
                    btnCancel.Text    = "Close";
                }

                tbName.ReadOnly        = readOnly;
                tbDescription.ReadOnly = readOnly;
                tbIpAddress.ReadOnly   = readOnly;
                ddlDeviceType.Enabled  = !readOnly;
                ddlPrintTo.Enabled     = !readOnly;
                ddlPrinter.Enabled     = !readOnly;
                ddlPrintFrom.Enabled   = !readOnly;

                btnSave.Visible = !readOnly;
            }
        }
示例#37
0
        /// <inheritdoc/>
        public string ToDelimitedString()
        {
            CultureInfo culture = CultureInfo.CurrentCulture;

            return(string.Format(
                       culture,
                       StringHelper.StringFormatSequence(0, 13, Configuration.FieldSeparator),
                       Id,
                       PrimaryKeyValueLdp?.ToDelimitedString(),
                       LocationDepartment?.ToDelimitedString(),
                       LocationService != null ? string.Join(Configuration.FieldRepeatSeparator, LocationService.Select(x => x.ToDelimitedString())) : null,
                       SpecialtyType != null ? string.Join(Configuration.FieldRepeatSeparator, SpecialtyType.Select(x => x.ToDelimitedString())) : null,
                       ValidPatientClasses != null ? string.Join(Configuration.FieldRepeatSeparator, ValidPatientClasses.Select(x => x.ToDelimitedString())) : null,
                       ActiveInactiveFlag,
                       ActivationDateLdp.HasValue ? ActivationDateLdp.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       InactivationDateLdp.HasValue ? InactivationDateLdp.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       InactivatedReason,
                       VisitingHours != null ? string.Join(Configuration.FieldRepeatSeparator, VisitingHours.Select(x => x.ToDelimitedString())) : null,
                       ContactPhone?.ToDelimitedString(),
                       LocationCostCenter?.ToDelimitedString()
                       ).TrimEnd(Configuration.FieldSeparator.ToCharArray()));
        }
        /// <summary>
        /// Handles the Click event of the btnRegister control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            // Check _isValidSettings in case the form was showing and they clicked the visible register button.
            if (Page.IsValid && _isValidSettings)
            {
                var rockContext   = new RockContext();
                var personService = new PersonService(rockContext);

                Person        person       = null;
                Person        spouse       = null;
                Group         family       = null;
                GroupLocation homeLocation = null;
                bool          isMatch      = false;

                // Only use current person if the name entered matches the current person's name and autofill mode is true
                if (_autoFill)
                {
                    if (CurrentPerson != null && CurrentPerson.NickName.IsNotNullOrWhiteSpace() && CurrentPerson.LastName.IsNotNullOrWhiteSpace() &&
                        tbFirstName.Text.Trim().Equals(CurrentPerson.NickName.Trim(), StringComparison.OrdinalIgnoreCase) &&
                        tbLastName.Text.Trim().Equals(CurrentPerson.LastName.Trim(), StringComparison.OrdinalIgnoreCase))
                    {
                        person  = personService.Get(CurrentPerson.Id);
                        isMatch = true;
                    }
                }

                // Try to find person by name/email
                if (person == null)
                {
                    var personQuery = new PersonService.PersonMatchQuery(tbFirstName.Text.Trim(), tbLastName.Text.Trim(), tbEmail.Text.Trim(), pnCell.Text.Trim());
                    person = personService.FindPerson(personQuery, true);
                    if (person != null)
                    {
                        isMatch = true;
                    }
                }

                // Check to see if this is a new person
                if (person == null)
                {
                    // If so, create the person and family record for the new person
                    person                         = new Person();
                    person.FirstName               = tbFirstName.Text.Trim();
                    person.LastName                = tbLastName.Text.Trim();
                    person.Email                   = tbEmail.Text.Trim();
                    person.IsEmailActive           = true;
                    person.EmailPreference         = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    person.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                    person.RecordStatusValueId     = _dvcRecordStatus.Id;
                    person.Gender                  = Gender.Unknown;

                    family = PersonService.SaveNewPerson(person, rockContext, _group.CampusId, false);
                }
                else
                {
                    // updating current existing person
                    person.Email = tbEmail.Text;

                    // Get the current person's families
                    var families = person.GetFamilies(rockContext);

                    // If address can being entered, look for first family with a home location
                    if (!IsSimple)
                    {
                        foreach (var aFamily in families)
                        {
                            homeLocation = aFamily.GroupLocations
                                           .Where(l =>
                                                  l.GroupLocationTypeValueId == _homeAddressType.Id &&
                                                  l.IsMappedLocation)
                                           .FirstOrDefault();
                            if (homeLocation != null)
                            {
                                family = aFamily;
                                break;
                            }
                        }
                    }

                    // If a family wasn't found with a home location, use the person's first family
                    if (family == null)
                    {
                        family = families.FirstOrDefault();
                    }
                }

                // If using a 'Full' view, save the phone numbers and address
                if (!IsSimple)
                {
                    if (!isMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                    {
                        SetPhoneNumber(rockContext, person, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid());
                    }
                    if (!isMatch || !string.IsNullOrWhiteSpace(pnCell.Number))
                    {
                        SetPhoneNumber(rockContext, person, pnCell, cbSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
                    }

                    if (!isMatch || !string.IsNullOrWhiteSpace(acAddress.Street1))
                    {
                        string oldLocation = homeLocation != null?homeLocation.Location.ToString() : string.Empty;

                        string newLocation = string.Empty;

                        var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                        if (location != null)
                        {
                            if (homeLocation == null)
                            {
                                homeLocation = new GroupLocation();
                                homeLocation.GroupLocationTypeValueId = _homeAddressType.Id;
                                family.GroupLocations.Add(homeLocation);
                            }
                            else
                            {
                                oldLocation = homeLocation.Location.ToString();
                            }

                            homeLocation.Location = location;
                            newLocation           = location.ToString();
                        }
                        else
                        {
                            if (homeLocation != null)
                            {
                                homeLocation.Location = null;
                                family.GroupLocations.Remove(homeLocation);
                                new GroupLocationService(rockContext).Delete(homeLocation);
                            }
                        }
                    }

                    // Check for the spouse
                    if (IsFullWithSpouse && tbSpouseFirstName.Text.IsNotNullOrWhiteSpace() && tbSpouseLastName.Text.IsNotNullOrWhiteSpace())
                    {
                        spouse = person.GetSpouse(rockContext);
                        bool isSpouseMatch = true;

                        if (spouse == null ||
                            !tbSpouseFirstName.Text.Trim().Equals(spouse.FirstName.Trim(), StringComparison.OrdinalIgnoreCase) ||
                            !tbSpouseLastName.Text.Trim().Equals(spouse.LastName.Trim(), StringComparison.OrdinalIgnoreCase))
                        {
                            spouse        = new Person();
                            isSpouseMatch = false;

                            spouse.FirstName = tbSpouseFirstName.Text.FixCase();
                            spouse.LastName  = tbSpouseLastName.Text.FixCase();

                            spouse.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                            spouse.RecordStatusValueId     = _dvcRecordStatus.Id;
                            spouse.Gender = Gender.Unknown;

                            spouse.IsEmailActive   = true;
                            spouse.EmailPreference = EmailPreference.EmailAllowed;

                            var groupMember = new GroupMember();
                            groupMember.GroupRoleId = _adultRole.Id;
                            groupMember.Person      = spouse;

                            family.Members.Add(groupMember);

                            spouse.MaritalStatusValueId = _married.Id;
                            person.MaritalStatusValueId = _married.Id;
                        }

                        spouse.Email = tbSpouseEmail.Text;

                        if (!isSpouseMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                        {
                            SetPhoneNumber(rockContext, spouse, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid());
                        }

                        if (!isSpouseMatch || !string.IsNullOrWhiteSpace(pnSpouseCell.Number))
                        {
                            SetPhoneNumber(rockContext, spouse, pnSpouseCell, cbSpouseSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
                        }
                    }
                }

                // Save the person/spouse and change history
                rockContext.SaveChanges();

                // Check to see if a workflow should be launched for each person
                WorkflowTypeCache workflowType = null;
                Guid?workflowTypeGuid          = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
                }

                // Save the registrations ( and launch workflows )
                var newGroupMembers = new List <GroupMember>();
                AddPersonToGroup(rockContext, person, workflowType, newGroupMembers);
                AddPersonToGroup(rockContext, spouse, workflowType, newGroupMembers);

                // Show the results
                pnlView.Visible   = false;
                pnlResult.Visible = true;

                // Show lava content
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("Group", _group);
                mergeFields.Add("GroupMembers", newGroupMembers);

                string template = GetAttributeValue("ResultLavaTemplate");
                lResult.Text = template.ResolveMergeFields(mergeFields);

                // Will only redirect if a value is specifed
                NavigateToLinkedPage("ResultPage");
            }
        }
示例#39
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        public void ShowDetail(int deviceId)
        {
            pnlDetails.Visible = true;
            Device device = null;

            var rockContext = new RockContext();

            if (!deviceId.Equals(0))
            {
                device            = new DeviceService(rockContext).Get(deviceId);
                lActionTitle.Text = ActionTitle.Edit(Device.FriendlyTypeName).FormatAsHtmlTitle();
                pdAuditDetails.SetEntity(device, ResolveRockUrl("~"));
            }

            if (device == null)
            {
                device = new Device {
                    Id = 0
                };
                lActionTitle.Text = ActionTitle.Add(Device.FriendlyTypeName).FormatAsHtmlTitle();

                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            LoadDropDowns();

            hfDeviceId.Value = device.Id.ToString();

            tbName.Text        = device.Name;
            tbDescription.Text = device.Description;
            tbIpAddress.Text   = device.IPAddress;
            ddlDeviceType.SetValue(device.DeviceTypeValueId);
            ddlPrintTo.SetValue(device.PrintToOverride.ConvertToInt().ToString());
            ddlPrinter.SetValue(device.PrinterDeviceId);
            ddlPrintFrom.SetValue(device.PrintFrom.ConvertToInt().ToString());

            SetPrinterVisibility();
            SetPrinterSettingsVisibility();

            Guid?orgLocGuid = GlobalAttributesCache.Get().GetValue("OrganizationAddress").AsGuidOrNull();

            if (orgLocGuid.HasValue)
            {
                var locationGeoPoint = new LocationService(rockContext).GetSelect(orgLocGuid.Value, a => a.GeoPoint);
                if (locationGeoPoint != null)
                {
                    geopPoint.CenterPoint = locationGeoPoint;
                    geopFence.CenterPoint = locationGeoPoint;
                }
            }

            if (device.Location != null)
            {
                geopPoint.SetValue(device.Location.GeoPoint);
                geopFence.SetValue(device.Location.GeoFence);
            }

            Locations = new Dictionary <int, string>();
            foreach (var location in device.Locations)
            {
                string path           = location.Name;
                var    parentLocation = location.ParentLocation;
                while (parentLocation != null)
                {
                    path           = parentLocation.Name + " > " + path;
                    parentLocation = parentLocation.ParentLocation;
                }

                Locations.Add(location.Id, path);
            }

            BindLocations();

            Guid mapStyleValueGuid = GetAttributeValue("MapStyle").AsGuid();

            geopPoint.MapStyleValueGuid = mapStyleValueGuid;
            geopFence.MapStyleValueGuid = mapStyleValueGuid;

            UpdateControlsForDeviceType(device);

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized(Authorization.EDIT))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Device.FriendlyTypeName);
            }

            if (readOnly)
            {
                lActionTitle.Text = ActionTitle.View(Device.FriendlyTypeName);
                btnCancel.Text    = "Close";
            }

            tbName.ReadOnly        = readOnly;
            tbDescription.ReadOnly = readOnly;
            tbIpAddress.ReadOnly   = readOnly;
            ddlDeviceType.Enabled  = !readOnly;
            ddlPrintTo.Enabled     = !readOnly;
            ddlPrinter.Enabled     = !readOnly;
            ddlPrintFrom.Enabled   = !readOnly;

            btnSave.Visible = !readOnly;
        }
示例#40
0
        /// <summary>
        /// Creates the person.
        /// </summary>
        /// <returns></returns>
        private Person CreatePerson()
        {
            var rockContext = new RockContext();

            DefinedValueCache dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid());
            DefinedValueCache dvcRecordStatus     = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid());

            Person person = new Person();

            person.FirstName         = tbFirstName.Text;
            person.LastName          = tbLastName.Text;
            person.Email             = tbEmail.Text;
            person.IsEmailActive     = true;
            person.EmailPreference   = EmailPreference.EmailAllowed;
            person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            if (dvcConnectionStatus != null)
            {
                person.ConnectionStatusValueId = dvcConnectionStatus.Id;
            }

            if (dvcRecordStatus != null)
            {
                person.RecordStatusValueId = dvcRecordStatus.Id;
            }

            switch (ddlGender.SelectedValue)
            {
            case "M":
                person.Gender = Gender.Male;
                break;

            case "F":
                person.Gender = Gender.Female;
                break;

            default:
                person.Gender = Gender.Unknown;
                break;
            }

            var birthday = bdaypBirthDay.SelectedDate;

            if (birthday.HasValue)
            {
                person.BirthMonth = birthday.Value.Month;
                person.BirthDay   = birthday.Value.Day;
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    person.BirthYear = birthday.Value.Year;
                }
            }

            bool smsSelected = false;

            foreach (RepeaterItem item in rPhoneNumbers.Items)
            {
                HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var phoneNumber = new PhoneNumber {
                            NumberTypeValueId = phoneNumberTypeId
                        };
                        person.PhoneNumbers.Add(phoneNumber);
                        phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                        phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                        // Only allow one number to have SMS selected
                        if (smsSelected)
                        {
                            phoneNumber.IsMessagingEnabled = false;
                        }
                        else
                        {
                            phoneNumber.IsMessagingEnabled = cbSms.Checked;
                            smsSelected = cbSms.Checked;
                        }

                        phoneNumber.IsUnlisted = cbUnlisted.Checked;
                    }
                }
            }

            PersonService.SaveNewPerson(person, rockContext, null, false);

            // save address
            if (pnlAddress.Visible)
            {
                if (acAddress.IsValid && !string.IsNullOrWhiteSpace(acAddress.Street1) && !string.IsNullOrWhiteSpace(acAddress.City) && !string.IsNullOrWhiteSpace(acAddress.PostalCode))
                {
                    Guid locationTypeGuid = GetAttributeValue("LocationType").AsGuid();
                    if (locationTypeGuid != Guid.Empty)
                    {
                        Guid                 familyGroupTypeGuid  = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                        GroupService         groupService         = new GroupService(rockContext);
                        GroupLocationService groupLocationService = new GroupLocationService(rockContext);
                        var family = groupService.Queryable().Where(g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any(m => m.PersonId == person.Id)).FirstOrDefault();

                        var groupLocation = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocationService.Add(groupLocation);

                        var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                        groupLocation.Location = location;

                        groupLocation.GroupLocationTypeValueId = DefinedValueCache.Get(locationTypeGuid).Id;
                        groupLocation.IsMailingLocation        = true;
                        groupLocation.IsMappedLocation         = true;

                        rockContext.SaveChanges();
                    }
                }
            }

            return(person);
        }
示例#41
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var attribute = AttributeCache.Get(GetAttributeValue(action, "PersonAttribute").AsGuid(), rockContext);

            if (attribute != null)
            {
                var      mergeFields        = GetMergeFields(action);
                string   firstName          = GetAttributeValue(action, "FirstName", true).ResolveMergeFields(mergeFields);
                string   lastName           = GetAttributeValue(action, "LastName", true).ResolveMergeFields(mergeFields);
                string   email              = GetAttributeValue(action, "Email", true).ResolveMergeFields(mergeFields);
                string   phone              = GetAttributeValue(action, "Phone", true).ResolveMergeFields(mergeFields);
                DateTime?dateofBirth        = GetAttributeValue(action, "DOB", true).AsDateTime();
                Guid?    addressGuid        = GetAttributeValue(action, "Address", true).AsGuidOrNull();
                Guid?    familyOrPersonGuid = GetAttributeValue(action, "FamilyAttribute", true).AsGuidOrNull();
                Location address            = null;
                // Set the street and postal code if we have an address
                if (addressGuid.HasValue)
                {
                    LocationService addressService = new LocationService(rockContext);
                    address = addressService.Get(addressGuid.Value);
                }


                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) &&
                     string.IsNullOrWhiteSpace(phone) &&
                     !dateofBirth.HasValue &&
                     (address == null || address != null && string.IsNullOrWhiteSpace(address.Street1)))
                    )
                {
                    errorMessages.Add("First Name, Last Name, and one of Email, Phone, DoB, or Address Street are required. One or more of these values was not provided!");
                }
                else
                {
                    Rock.Model.Person person      = null;
                    PersonAlias       personAlias = null;
                    var personService             = new PersonService(rockContext);
                    var people = personService.GetByMatch(firstName, lastName, dateofBirth, email, phone, address?.Street1, address?.PostalCode).ToList();
                    if (people.Count == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(email) ||
                         (people.First().Email != null &&
                          email.ToLower().Trim() == people.First().Email.ToLower().Trim()))
                        )
                    {
                        person      = people.First();
                        personAlias = person.PrimaryAlias;
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        // Add New Person
                        person               = new Rock.Model.Person();
                        person.FirstName     = firstName;
                        person.LastName      = lastName;
                        person.IsEmailActive = true;
                        person.Email         = email;
                        if (dateofBirth.HasValue)
                        {
                            person.BirthDay   = dateofBirth.Value.Day;
                            person.BirthMonth = dateofBirth.Value.Month;
                            person.BirthYear  = dateofBirth.Value.Year;
                        }
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

                        var defaultConnectionStatus = DefinedValueCache.Get(GetAttributeValue(action, "DefaultConnectionStatus").AsGuid());
                        if (defaultConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = defaultConnectionStatus.Id;
                        }

                        var defaultRecordStatus = DefinedValueCache.Get(GetAttributeValue(action, "DefaultRecordStatus").AsGuid());
                        if (defaultRecordStatus != null)
                        {
                            person.RecordStatusValueId = defaultRecordStatus.Id;
                        }

                        var defaultCampus = CampusCache.Get(GetAttributeValue(action, "DefaultCampus", true).AsGuid());

                        // Get the default family if applicable
                        Group family = null;
                        if (familyOrPersonGuid.HasValue)
                        {
                            PersonAliasService personAliasService = new PersonAliasService(rockContext);
                            family = personAliasService.Get(familyOrPersonGuid.Value)?.Person?.GetFamily();
                            if (family == null)
                            {
                                GroupService groupService = new GroupService(rockContext);
                                family = groupService.Get(familyOrPersonGuid.Value);
                            }
                        }
                        var familyGroup = SaveNewPerson(person, family, (defaultCampus != null ? defaultCampus.Id : ( int? )null), rockContext);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            personAlias = person.PrimaryAlias;

                            // If we have an address, go ahead and save it here.
                            if (address != null)
                            {
                                GroupLocation location = new GroupLocation();
                                location.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                location.Location = address;
                                familyGroup.GroupLocations.Add(location);
                            }
                        }
                    }

                    // Save/update the phone number
                    if (!string.IsNullOrWhiteSpace(phone))
                    {
                        List <string> changes    = new List <string>();
                        var           numberType = DefinedValueCache.Get(GetAttributeValue(action, "PhoneNumberType").AsGuid());
                        if (numberType != null)
                        {
                            // gets value indicating if phone number is unlisted
                            string unlistedValue     = GetAttributeValue(action, "Unlisted");
                            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();
                            if (unlistedValueGuid.HasValue)
                            {
                                unlistedValue = action.GetWorklowAttributeValue(unlistedValueGuid.Value);
                            }
                            else
                            {
                                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool unlisted = unlistedValue.AsBoolean();

                            // gets value indicating if messaging should be enabled for phone number
                            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
                            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();
                            if (smsEnabledValueGuid.HasValue)
                            {
                                smsEnabledValue = action.GetWorklowAttributeValue(smsEnabledValueGuid.Value);
                            }
                            else
                            {
                                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool smsEnabled = smsEnabledValue.AsBoolean();


                            var    phoneModel     = person.PhoneNumbers.FirstOrDefault(p => p.NumberTypeValueId == numberType.Id);
                            string oldPhoneNumber = phoneModel != null ? phoneModel.NumberFormattedWithCountryCode : string.Empty;
                            string newPhoneNumber = PhoneNumber.CleanNumber(phone);

                            if (newPhoneNumber != string.Empty && newPhoneNumber != oldPhoneNumber)
                            {
                                if (phoneModel == null)
                                {
                                    phoneModel = new PhoneNumber();
                                    person.PhoneNumbers.Add(phoneModel);
                                    phoneModel.NumberTypeValueId = numberType.Id;
                                }
                                else
                                {
                                    oldPhoneNumber = phoneModel.NumberFormattedWithCountryCode;
                                }
                                phoneModel.Number             = newPhoneNumber;
                                phoneModel.IsUnlisted         = unlisted;
                                phoneModel.IsMessagingEnabled = smsEnabled;
                            }
                        }
                    }

                    if (person != null && personAlias != null)
                    {
                        SetWorkflowAttributeValue(action, attribute.Guid, personAlias.Guid.ToString());
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName));
                        return(true);
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        errorMessages.Add("Person or Primary Alias could not be determined!");
                    }
                }
            }
            else
            {
                errorMessages.Add("Person Attribute could not be found!");
            }

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                if (GetAttributeValue(action, "ContinueOnError").AsBoolean())
                {
                    errorMessages.Clear();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
        public async void GetAvailableSpots_FoundOne()
        {
            using (var transaction = Fixture.Connection.BeginTransaction())
            {
                using (var context = Fixture.CreateContext(transaction))
                {
                    // Arrange
                    var locationService = new LocationService(context);
                    var marinaService   = new MarinaService(context, locationService);
                    var service         = new BookingFormService(context, marinaService);
                    List <BookingLine> bookingLines1 = new List <BookingLine>
                    {
                        new BookingLine {
                            StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(2), BookingId = 1
                        },
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(5), EndDate = DateTime.Now.AddDays(5), BookingId = 1
                        },
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(6), EndDate = DateTime.Now.AddDays(9), BookingId = 1
                        },
                    };
                    List <BookingLine> bookingLines2 = new List <BookingLine>
                    {
                        new BookingLine {
                            StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(2), BookingId = 1
                        },
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(5), EndDate = DateTime.Now.AddDays(5), BookingId = 1
                        },
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(6), EndDate = DateTime.Now.AddDays(9), BookingId = 1
                        },
                    };
                    List <BookingLine> bookingLines3 = new List <BookingLine>
                    {
                        new BookingLine {
                            StartDate = DateTime.Now.AddDays(8), EndDate = DateTime.Now.AddDays(12), BookingId = 1
                        },
                    };
                    List <Spot> spots = new List <Spot>
                    {
                        new Spot {
                            SpotNumber = 1, MarinaId = 1, MaxDepth = 10, MaxLength = 20, MaxWidth = 30, BookingLines = bookingLines1, Available = true
                        },
                        new Spot {
                            SpotNumber = 2, MarinaId = 1, MaxDepth = 30, MaxLength = 40, MaxWidth = 30, BookingLines = bookingLines2, Available = true
                        },
                        new Spot {
                            SpotNumber = 3, MarinaId = 1, MaxDepth = 30, MaxLength = 30, MaxWidth = 30, BookingLines = bookingLines3, Available = true
                        }
                    };

                    Marina marina = new Marina {
                        Name = "Hello", Spots = spots, MarinaOwnerId = 1
                    };
                    Boat boat = new Boat {
                        Depth = 1, Length = 2, Width = 3, BoatOwnerId = 1
                    };
                    DateTime startDate = DateTime.Now.AddDays(3);
                    DateTime endDate   = DateTime.Now.AddDays(4);

                    context.AddRange(spots);
                    context.Add(marina);
                    context.Add(boat);

                    context.SaveChanges();

                    // Act
                    var result = await service.GetAvailableSpots(
                        marina.MarinaId,
                        boat.BoatId,
                        startDate,
                        endDate);

                    // Assert
                    Assert.NotNull(result);
                    //Assert.Single(result);
                    Assert.Equal(1, result.First().SpotNumber);
                }
            }
        }
 public LocationController()
 {
     this.locationService = new LocationService();
 }
示例#44
0
 public RegisterProcessor(LocationService service, Register op) : base(op)
 {
     this.service = service;
 }
示例#45
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext           = new RockContext();
            var         person                = GetPerson();
            var         personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));
            var         changeRequest         = new ChangeRequest
            {
                EntityTypeId     = personAliasEntityType.Id,
                EntityId         = person.PrimaryAliasId ?? 0,
                RequestorAliasId = CurrentPersonAliasId ?? 0,
                RequestorComment = tbComments.Text
            };

            changeRequest.EvaluatePropertyChange(person, "PhotoId", iuPhoto.BinaryFileId);
            changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
            changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
            changeRequest.EvaluatePropertyChange(person, "MiddleName", tbMiddleName.Text);
            var lastNameRecord = changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);

            //Store the person's old last name as a previous name
            if (lastNameRecord != null)
            {
                changeRequest.AddEntity(new PersonPreviousName
                {
                    LastName                = person.LastName,
                    PersonAliasId           = person.PrimaryAliasId ?? 0,
                    CreatedByPersonAliasId  = CurrentPersonAliasId,
                    ModifiedByPersonAliasId = CurrentPersonAliasId
                },
                                        rockContext,
                                        true);
            }

            changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

            var families = person.GetFamilies();

            if (families.Count() == 1)
            {
                var groupMember = person.PrimaryFamily.Members.Where(gm => gm.PersonId == person.Id).FirstOrDefault();
                if (groupMember != null)
                {
                    GroupTypeRole        groupTypeRole        = null;
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    if (ddlFamilyRole.SelectedValue == "A")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid());
                    }
                    else if (ddlFamilyRole.SelectedValue == "C")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid());
                    }
                    changeRequest.EvaluatePropertyChange(groupMember, "GroupRole", groupTypeRole, true);
                }
            }

            //Evaluate PhoneNumbers
            var  phoneNumberTypeIds = new List <int>();
            bool smsSelected        = false;

            foreach (RepeaterItem item in rContactInfo.Items)
            {
                HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                if (hfPhoneType != null &&
                    pnbPhone != null &&
                    cbSms != null &&
                    cbUnlisted != null)
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var    phoneNumber    = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                        string oldPhoneNumber = string.Empty;
                        if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                        {
                            phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                            changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNullOrWhiteSpace())   // delete number
                        {
                            var phoneComment = string.Format("{0}: {1}.", phoneNumber.NumberTypeValue.Value, phoneNumber.NumberFormatted);
                            changeRequest.DeleteEntity(phoneNumber, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                        {
                            changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                        }

                        if (hfPhoneType.Value.AsInteger() == DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()))
                        {
                            var validationInfo = ValidateMobilePhoneNumber(PhoneNumber.CleanNumber(pnbPhone.Number));
                            if (validationInfo.IsNotNullOrWhiteSpace())
                            {
                                changeRequest.RequestorComment += "<h4>Dynamically Generated Warnings:</h4>" + validationInfo;
                            }
                        }
                    }
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text);
            changeRequest.EvaluatePropertyChange(person, "IsEmailActive", cbIsEmailActive.Checked);
            changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
            changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());


            var birthday = bpBirthday.SelectedDate;

            if (birthday.HasValue)
            {
                changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                }
                else
                {
                    int?year = null;
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", year);
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Gender", ddlGender.SelectedValueAsEnum <Gender>());
            changeRequest.EvaluatePropertyChange(person, "MaritalStatusValue", DefinedValueCache.Get(ddlMaritalStatus.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "AnniversaryDate", dpAnniversaryDate.SelectedDate);
            changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);

            var groupEntity         = EntityTypeCache.Get(typeof(Group));
            var groupLocationEntity = EntityTypeCache.Get(typeof(GroupLocation));
            var family = person.GetFamily();

            var familyChangeRequest = new ChangeRequest()
            {
                EntityTypeId     = groupEntity.Id,
                EntityId         = family.Id,
                RequestorAliasId = CurrentPersonAliasId ?? 0
            };

            familyChangeRequest.EvaluatePropertyChange(family, "Campus", CampusCache.Get(ddlCampus.SelectedValueAsInt() ?? 0));

            var      currentLocation = person.GetHomeLocation();
            Location location        = new Location
            {
                Street1    = acAddress.Street1,
                Street2    = acAddress.Street2,
                City       = acAddress.City,
                State      = acAddress.State,
                PostalCode = acAddress.PostalCode,
            };
            var globalAttributesCache = GlobalAttributesCache.Get();

            location.Country = globalAttributesCache.OrganizationCountry;
            location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

            if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                (currentLocation != null && currentLocation.Street1 != location.Street1))
            {
                LocationService locationService = new LocationService(rockContext);
                locationService.Add(location);
                rockContext.SaveChanges();

                var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                GroupLocation groupLocation = new GroupLocation
                {
                    CreatedByPersonAliasId  = CurrentPersonAliasId,
                    ModifiedByPersonAliasId = CurrentPersonAliasId,
                    GroupId    = family.Id,
                    LocationId = location.Id,
                    GroupLocationTypeValueId = homeLocationType.Id,
                    IsMailingLocation        = true,
                    IsMappedLocation         = true
                };

                var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                var homelocations = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                foreach (var homelocation in homelocations)
                {
                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "GroupLocationTypeValue",
                        previousLocationType,
                        true,
                        homelocation.Location.ToString());

                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "IsMailingLocation",
                        false,
                        true,
                        homelocation.Location.ToString());
                }
            }

            //Adding a new family member
            if (pAddPerson.SelectedValue.HasValue)
            {
                PersonService personService = new PersonService(rockContext);
                var           insertPerson  = personService.Get(pAddPerson.SelectedValue.Value);
                if (insertPerson != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                    var familyGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

                    //Remove all other group members
                    if (cbRemovePerson.Checked)
                    {
                        var members = groupMemberService.Queryable()
                                      .Where(m => m.PersonId == pAddPerson.SelectedValue.Value && m.Group.GroupTypeId == familyGroupTypeId);
                        foreach (var member in members)
                        {
                            var comment = string.Format("Removed {0} from {1}", insertPerson.FullName, member.Group.Name);
                            familyChangeRequest.DeleteEntity(member, true, comment);
                        }
                    }

                    var personFamilies = person.GetFamilies().ToList();

                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);

                    var roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
                    if (insertPerson.Age.HasValue && insertPerson.Age.Value < 18)
                    {
                        roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
                    }

                    foreach (var personFamily in personFamilies)
                    {
                        //Make a new group member
                        GroupMember familyMember = new GroupMember
                        {
                            PersonId          = pAddPerson.SelectedValue.Value,
                            GroupId           = personFamily.Id,
                            GroupMemberStatus = GroupMemberStatus.Active,
                            Guid        = Guid.NewGuid(),
                            GroupRoleId = roleId
                        };
                        var insertComment = string.Format("Added {0} to {1}", insertPerson.FullName, personFamily.Name);
                        familyChangeRequest.AddEntity(familyMember, rockContext, true, insertComment);
                    }
                }
            }

            bool          autoApply = CanAutoApply(person);
            List <string> errors;

            if (changeRequest.ChangeRecords.Any() ||
                (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
            {
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                changeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (familyChangeRequest.ChangeRecords.Any())
            {
                familyChangeRequest.RequestorComment = tbComments.Text;
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(familyChangeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
                familyChangeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (autoApply)
            {
                NavigateToPerson();
            }
            else
            {
                pnlMain.Visible     = false;
                pnlNoPerson.Visible = false;
                pnlDone.Visible     = true;
            }
        }
示例#46
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var changes       = new List <string>();
                Person business   = null;

                if (int.Parse(hfBusinessId.Value) != 0)
                {
                    business = personService.Get(int.Parse(hfBusinessId.Value));
                }

                if (business == null)
                {
                    business = new Person();
                    personService.Add(business);
                }

                // Business Name
                History.EvaluateChange(changes, "Last Name", business.LastName, tbBusinessName.Text);
                business.LastName = tbBusinessName.Text;

                // Phone Number
                var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id;

                string oldPhoneNumber = string.Empty;
                string newPhoneNumber = string.Empty;

                var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);
                if (phoneNumber != null)
                {
                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }

                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    if (phoneNumber == null)
                    {
                        phoneNumber = new PhoneNumber {
                            NumberTypeValueId = businessPhoneTypeId
                        };
                        business.PhoneNumbers.Add(phoneNumber);
                    }
                    phoneNumber.CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                    phoneNumber.Number             = PhoneNumber.CleanNumber(pnbPhone.Number);
                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                    phoneNumber.IsUnlisted         = cbUnlisted.Checked;

                    newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }
                else
                {
                    if (phoneNumber != null)
                    {
                        business.PhoneNumbers.Remove(phoneNumber);
                        new PhoneNumberService(rockContext).Delete(phoneNumber);
                    }
                }

                History.EvaluateChange(
                    changes,
                    string.Format("{0} Phone", DefinedValueCache.GetName(businessPhoneTypeId)),
                    oldPhoneNumber,
                    newPhoneNumber);

                // Record Type - this is always "business". it will never change.
                business.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

                // Record Status
                int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(business.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId));
                business.RecordStatusValueId = newRecordStatusId;

                // Record Status Reason
                int?newRecordStatusReasonId = null;
                if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
                {
                    newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                }

                History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(business.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                business.RecordStatusReasonValueId = newRecordStatusReasonId;

                // Email
                business.IsEmailActive = true;
                History.EvaluateChange(changes, "Email", business.Email, tbEmail.Text);
                business.Email = tbEmail.Text.Trim();

                var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                History.EvaluateChange(changes, "EmailPreference", business.EmailPreference, newEmailPreference);
                business.EmailPreference = newEmailPreference;

                if (business.IsValid)
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                business.Id,
                                changes);
                        }
                    }
                }

                // Add/Update Family Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                int adultRoleId     = familyGroupType.Roles
                                      .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()))
                                      .Select(r => r.Id)
                                      .FirstOrDefault();
                var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext);
                business.GivingGroup  = adultFamilyMember.Group;

                // Add/Update Known Relationship Group Type
                var knownRelationshipGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles
                                                   .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                                   .Select(r => r.Id)
                                                   .FirstOrDefault();
                var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext);

                // Add/Update Implied Relationship Group Type
                var impliedRelationshipGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid());
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid()))
                                                     .Select(r => r.Id)
                                                     .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext);

                rockContext.SaveChanges();

                // Location
                int workLocationTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id;

                var groupLocationService = new GroupLocationService(rockContext);
                var workLocation         = groupLocationService.Queryable("Location")
                                           .Where(gl =>
                                                  gl.GroupId == adultFamilyMember.Group.Id &&
                                                  gl.GroupLocationTypeValueId == workLocationTypeId)
                                           .FirstOrDefault();

                if (string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    if (workLocation != null)
                    {
                        groupLocationService.Delete(workLocation);
                        History.EvaluateChange(changes, "Address", workLocation.Location.ToString(), string.Empty);
                    }
                }
                else
                {
                    var oldValue = string.Empty;

                    var newLocation = new LocationService(rockContext).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);

                    if (workLocation != null)
                    {
                        oldValue = workLocation.Location.ToString();
                    }
                    else
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;

                    History.EvaluateChange(changes, "Address", oldValue, newLocation.ToString());
                }

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();
            });

            ShowSummary(hfBusinessId.Value.AsInteger());
        }
        private Location GetLocationById(int id, RockContext rockContext)
        {
            var locationService = new LocationService(rockContext);

            return(locationService.Get(id));
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            PersonAliasService personAliasService = new PersonAliasService(rockContext);
            Person             person             = personAliasService.Get(action.Activity.Workflow.GetAttributeValue("Person").AsGuid()).Person;

            LocationService locationService        = new LocationService(rockContext);
            Location        currentMailingAddress  = locationService.Get(action.Activity.Workflow.GetAttributeValue("CurrentMailingAddress").AsGuid());
            Location        previousMailingAddress = locationService.Get(action.Activity.Workflow.GetAttributeValue("PreviousMailingAddress").AsGuid());

            if (previousMailingAddress == null)
            {
                previousMailingAddress = new Location();
            }
            Location reference1Address = locationService.Get(action.Activity.Workflow.GetAttributeValue("Reference1Address").AsGuid());
            Location reference2Address = locationService.Get(action.Activity.Workflow.GetAttributeValue("Reference2Address").AsGuid());
            Location reference3Address = locationService.Get(action.Activity.Workflow.GetAttributeValue("Reference3Address").AsGuid());
            Location reference4Address = locationService.Get(action.Activity.Workflow.GetAttributeValue("Reference4Address").AsGuid());

            Dictionary <string, string> fields = new Dictionary <string, string>()
            {
                { "ministryOfInterest", action.Activity.Workflow.GetAttributeValue("MinistryOfInterest") },
                { "intPersonID", person.Id.ToString() },

                { "txtLastName", action.Activity.Workflow.GetAttributeValue("LastName") },
                { "txtFirstName", action.Activity.Workflow.GetAttributeValue("FirstName") },
                { "txtMiddleName", action.Activity.Workflow.GetAttributeValue("MiddleName") },
                { "txtMaidenOtherName", action.Activity.Workflow.GetAttributeValue("MaidenOtherNames") },
                { "txtParent", action.Activity.Workflow.GetAttributeValue("Parent") },
                { "txtParentEmail", action.Activity.Workflow.GetAttributeValue("ParentEmail") },
                { "txtParentHomePhone", action.Activity.Workflow.GetAttributeValue("ParentHomePhone") },
                { "txtParentCellPhone", action.Activity.Workflow.GetAttributeValue("ParentCellPhone") },

                { "txtDateOfBirth", action.Activity.Workflow.GetAttributeValue("DateofBirth").AsDateTime().Value.ToShortDateString() },
                //{"txtSSN", action.Activity.Workflow.GetAttributeValue("")},
                { "radGender", action.Activity.Workflow.GetAttributeValue("") },
                { "radMale", action.Activity.Workflow.GetAttributeValue("Gender") == "Male"?"Yes":"No" },
                { "radFemale", action.Activity.Workflow.GetAttributeValue("Gender") == "Female"?"Yes":"No" },
                { "txtSCCAttendanceDuration", action.Activity.Workflow.GetAttributeValue("HowLongAttended") },
                { "txtSCCMember", person.ConnectionStatusValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER.AsGuid()?"Yes":"No" },
                { "txtSCCMemberPDFNo", person.ConnectionStatusValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER.AsGuid()?"No":"Yes" },
                { "txtSCCInvolvement", action.Activity.Workflow.GetAttributeValue("CurrentParticipation") },
                { "txtChurch", action.Activity.Workflow.GetAttributeValue("ChurchAtttended") },

                { "txtStreet", currentMailingAddress.Street1 },
                { "txtCity", currentMailingAddress.City },
                { "txtState", currentMailingAddress.State },
                { "txtZip", currentMailingAddress.PostalCode },
                { "SaveUpToThisPoint", "" },
                { "txtPrevStreet", previousMailingAddress.Street1 },
                { "txtPrevCity", previousMailingAddress.City },
                { "txtPrevState", previousMailingAddress.State },
                { "txtPrevZip", previousMailingAddress.PostalCode },
                { "radOutOfState", action.Activity.Workflow.GetAttributeValue("OutsideKentuckyIndiana") },
                { "radOutOfStatePDFYes", action.Activity.Workflow.GetAttributeValue("OutsideKentuckyIndiana").AsBoolean()?"Yes":"No" },
                { "radOutOfStatePDFNo", action.Activity.Workflow.GetAttributeValue("OutsideKentuckyIndiana").AsBoolean()?"No":"Yes" },
                { "txtOutOfState_Dates", action.Activity.Workflow.GetAttributeValue("WhenOutsideKentuckyIndiana") },
                { "txtOutOfState_State", action.Activity.Workflow.GetAttributeValue("StatesOutsideKentuckyIndiana") },
                { "txtEmployer", action.Activity.Workflow.GetAttributeValue("CurrentEmployer") },
                { "txtPosition", action.Activity.Workflow.GetAttributeValue("PositionHeld") },
                { "txtWorkPhone", action.Activity.Workflow.GetAttributeValue("WorkPhone") },
                { "txtHomePhone", action.Activity.Workflow.GetAttributeValue("HomePhone") },
                { "txtCellPhone", action.Activity.Workflow.GetAttributeValue("CellPhone") },

                //{"txtWorkEmail", action.Activity.Workflow.GetAttributeValue("")},

                { "txtEmail", person.Email },

                { "txtRef1Name", action.Activity.Workflow.GetAttributeValue("Reference1Name") },
                //{"txtRef1Relationship", action.Activity.Workflow.GetAttributeValue("")},
                { "radRef1YearsKnow", action.Activity.Workflow.GetAttributeValue("Reference1Relationship")
                  + "/" + action.Activity.Workflow.GetAttributeValue("Reference1YearsKnown") },
                { "txtRef1Address", reference1Address.Street1 },
                { "txtRef1City", reference1Address.City },
                { "txtRef1State", reference1Address.State },
                { "txtRef1Zip", reference1Address.PostalCode },
                //{"txtRef1PersPhone", action.Activity.Workflow.GetAttributeValue("")},
                //{"txtRef1PersPhoneTime", action.Activity.Workflow.GetAttributeValue("")},
                { "txtRef1WorkPhone", action.Activity.Workflow.GetAttributeValue("Reference1WorkPhone") },
                //{"txtRef1WorkPhoneTime", action.Activity.Workflow.GetAttributeValue("")},
                { "txtRef1HomePhone", action.Activity.Workflow.GetAttributeValue("Reference1HomePhone") },
                { "txtRef1CellPhone", action.Activity.Workflow.GetAttributeValue("Reference1CellPhone") },
                { "txtRef1Email", action.Activity.Workflow.GetAttributeValue("Reference1Email") },

                { "txtRef2Name", action.Activity.Workflow.GetAttributeValue("Reference2Name") },
                //{"txtRef2Relationship", action.Activity.Workflow.GetAttributeValue("")},
                { "radRef2YearsKnow", action.Activity.Workflow.GetAttributeValue("Reference2Relationship")
                  + "/" + action.Activity.Workflow.GetAttributeValue("Reference2YearsKnown") },
                { "txtRef2Address", reference2Address.Street1 },
                { "txtRef2City", reference2Address.City },
                { "txtRef2State", reference2Address.State },
                { "txtRef2Zip", reference2Address.PostalCode },
                //{"txtRef2PersPhone", action.Activity.Workflow.GetAttributeValue("")},
                //{"txtRef2PersPhoneTime", action.Activity.Workflow.GetAttributeValue("")},
                { "txtRef2WorkPhone", action.Activity.Workflow.GetAttributeValue("Reference2WorkPhone") },
                //{"txtRef2WorkPhoneTime", action.Activity.Workflow.GetAttributeValue("")},
                { "txtRef2HomePhone", action.Activity.Workflow.GetAttributeValue("Reference2HomePhone") },
                { "txtRef2CellPhone", action.Activity.Workflow.GetAttributeValue("Reference2CellPhone") },
                { "txtRef2Email", action.Activity.Workflow.GetAttributeValue("Reference2Email") },

                { "txtRef3Name", action.Activity.Workflow.GetAttributeValue("Reference3Name") },
                //{"txtRef3Relationship", action.Activity.Workflow.GetAttributeValue("")},
                { "radRef3YearsKnow", action.Activity.Workflow.GetAttributeValue("Reference3Relationship")
                  + "/" + action.Activity.Workflow.GetAttributeValue("Reference3YearsKnown") },
                { "txtRef3Address", reference3Address.Street1 },
                { "txtRef3City", reference3Address.City },
                { "txtRef3State", reference3Address.State },
                { "txtRef3Zip", reference3Address.PostalCode },
                //{"txtRef3PersPhone", action.Activity.Workflow.GetAttributeValue("")},
                //{"txtRef3PersPhoneTime", action.Activity.Workflow.GetAttributeValue("")},
                { "txtRef3WorkPhone", action.Activity.Workflow.GetAttributeValue("Reference3WorkPhone") },
                //{"txtRef3WorkPhoneTime", action.Activity.Workflow.GetAttributeValue("")},
                { "txtRef3HomePhone", action.Activity.Workflow.GetAttributeValue("Reference3HomePhone") },
                { "txtRef3CellPhone", action.Activity.Workflow.GetAttributeValue("Reference3CellPhone") },
                { "txtRef3Email", action.Activity.Workflow.GetAttributeValue("Reference3Email") },

                { "txtRef4Name", action.Activity.Workflow.GetAttributeValue("Reference4Name") },
                //{"txtRef4Relationship", action.Activity.Workflow.GetAttributeValue("")},
                { "radRef4YearsKnow", action.Activity.Workflow.GetAttributeValue("Reference4Relationship")
                  + "/" + action.Activity.Workflow.GetAttributeValue("Reference4YearsKnown") },
                { "txtRef4Address", reference4Address.Street1 },
                { "txtRef4City", reference4Address.City },
                { "txtRef4State", reference4Address.State },
                { "txtRef4Zip", reference4Address.PostalCode },
                //{"txtRef4PersPhone", action.Activity.Workflow.GetAttributeValue("")},
                //{"txtRef4PersPhoneTime", action.Activity.Workflow.GetAttributeValue("")},
                { "txtRef4WorkPhone", action.Activity.Workflow.GetAttributeValue("Reference4WorkPhone") },
                //{"txtRef4WorkPhoneTime", action.Activity.Workflow.GetAttributeValue("")},
                { "txtRef4HomePhone", action.Activity.Workflow.GetAttributeValue("Reference4HomePhone") },
                { "txtRef4CellPhone", action.Activity.Workflow.GetAttributeValue("Reference4CellPhone") },
                { "txtRef4Email", action.Activity.Workflow.GetAttributeValue("Reference4Email") },

                //{"txtPhysLimitations", action.Activity.Workflow.GetAttributeValue("")},
                { "txtPhysLimitations", action.Activity.Workflow.GetAttributeValue("PhysicalLimitationsExplanation") },
                { "txtPhysLimitationsPDF", action.Activity.Workflow.GetAttributeValue("PhysicalLimitationsExplanation") },
                { "radPhysLimitationsPDFYes", action.Activity.Workflow.GetAttributeValue("PhysicalLimitations").AsBoolean()?"Yes":"No" },
                { "radPhysLimitationsPDFNo", action.Activity.Workflow.GetAttributeValue("PhysicalLimitations").AsBoolean()?"No":"Yes" },
                { "radCrimePersons", action.Activity.Workflow.GetAttributeValue("Crime").AsBoolean()?"Yes":"No" },
                { "radCrimePersonsPDFNo", action.Activity.Workflow.GetAttributeValue("Crime").AsBoolean()?"No":"Yes" },
                //{"radCrimeProperty", action.Activity.Workflow.GetAttributeValue("")},
                { "radThreatToMinors", action.Activity.Workflow.GetAttributeValue("Threat").AsBoolean()?"Yes":"No" },
                { "radThreatToMinorsPDFNo", action.Activity.Workflow.GetAttributeValue("Threat").AsBoolean()?"No":"Yes" },
                { "radCrimeCounseled", action.Activity.Workflow.GetAttributeValue("CrimeCounsel").AsBoolean()?"Yes":"No" },
                { "radCrimeCounseledPDFYes", action.Activity.Workflow.GetAttributeValue("CrimeCounsel").AsBoolean()?"Yes":"No" },
                { "radCrimeCounseledPDFNo", action.Activity.Workflow.GetAttributeValue("CrimeCounsel").AsBoolean()?"No":"Yes" },
                { "radNeedsStaffContact", action.Activity.Workflow.GetAttributeValue("Contact").AsBoolean()?"Yes":"No" },
                { "radNeedsStaffContactPDFNo", action.Activity.Workflow.GetAttributeValue("Contact").AsBoolean()?"No":"Yes" },
                { "personDetailPage", GlobalAttributesCache.Value("InternalApplicationRoot") + "/Person/" + person.Id },

                { "txtAppSigned", "{{t:s;r:y;o:\"Applicant\";}}" },
                { "txtAppDated", "{{t:d;r:y;o:\"Applicant\";l:\"Date\";dd:\"" + DateTime.Now.ToShortDateString() + "\";}}" },
                { "txtAppPrintedName", person.FullNameFormal },

                { "txtSOFSigned", "{{t:s;r:n;o:\"Applicant\";}}" },
                { "txtSOFDated", "{{t:d;r:n;o:\"Applicant\";l:\"Date\";dd:\"" + DateTime.Now.ToShortDateString() + "\";}}" },
                { "txtSOFPrintedName", person.FullNameFormal },

                { "txtParentSignature", "{{t:s;r:y;o:\"Parent\";}}" },
                { "txtDate1", "{{t:d;r:y;o:\"Parent\";l:\"Date\";dd:\"" + DateTime.Now.ToShortDateString() + "\";}}" },

                { "radReadSOFYes", action.Activity.Workflow.GetAttributeValue("ReadStatementOfFaith").AsBoolean()?"Yes":"No" },
                { "radReadSOFNo", action.Activity.Workflow.GetAttributeValue("ReadStatementOfFaith").AsBoolean()?"No":"Yes" },
                { "radAgreeSOFYes", action.Activity.Workflow.GetAttributeValue("AgreeStatementOfFaith").AsBoolean()?"Yes":"No" },
                { "radAgreeSOFNo", action.Activity.Workflow.GetAttributeValue("AgreeStatementOfFaith").AsBoolean()?"No":"Yes" },
                { "txtSOFCommentsAmendments", String.IsNullOrEmpty(action.Activity.Workflow.GetAttributeValue("CommentsStatementOfFaith"))?" ":action.Activity.Workflow.GetAttributeValue("CommentsStatementOfFaith") },
            };

            BinaryFileService binaryFileService = new BinaryFileService(rockContext);
            BinaryFile        PDF = null;
            var isMinorApplicant  = GetAttributeValue(action, "IsMinorApplication", true).AsBoolean();

            if (isMinorApplicant)
            {
                PDF = binaryFileService.Get(GetActionAttributeValue(action, "MinorVolunteerApplicationPDF").AsGuid());
            }
            else
            {
                PDF = binaryFileService.Get(GetActionAttributeValue(action, "AdultVolunteerApplicationPDF").AsGuid());
            }

            var pdfBytes = PDF.ContentStream.ReadBytesToEnd();

            using (MemoryStream ms = new MemoryStream())
            {
                PdfReader  pdfReader  = new PdfReader(pdfBytes);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, ms);

                AcroFields pdfFormFields = pdfStamper.AcroFields;


                foreach (var field in fields)
                {
                    if (pdfFormFields.Fields.ContainsKey(field.Key))
                    {
                        pdfFormFields.SetField(field.Key, field.Value);
                    }
                }

                // flatten the form to remove editting options, set it to false
                // to leave the form open to subsequent manual edits
                pdfStamper.FormFlattening = true;

                // close the pdf
                pdfStamper.Close();
                //pdfReader.Close();
                pdfStamper.Dispose();
                pdfStamper = null;

                BinaryFile renderedPDF = new BinaryFile();
                renderedPDF.CopyPropertiesFrom(PDF);
                renderedPDF.Guid             = Guid.NewGuid();
                renderedPDF.FileName         = "VolunteerApplication_" + person.FirstName + person.LastName + ".pdf";
                renderedPDF.BinaryFileTypeId = new BinaryFileTypeService(rockContext).Get(new Guid(BACKGROUND_CHECK_BINARY_FILE_TYPE)).Id;

                BinaryFileData pdfData = new BinaryFileData();
                pdfData.Content = ms.ToArray();

                renderedPDF.DatabaseData = pdfData;

                binaryFileService.Add(renderedPDF);
                rockContext.SaveChanges();

                action.Activity.Workflow.SetAttributeValue("PDF", renderedPDF.Guid);
            }


            return(true);
        }
示例#49
0
        /// <summary>
        /// Sets the value on select.
        /// </summary>
        protected override void SetValueOnSelect()
        {
            var item = new LocationService(new RockContext()).Get(int.Parse(ItemId));

            this.SetValue(item);
        }
 public MapPageViewModel()
 {
     locationService = new LocationService();
     Center          = new Geopoint(defaultPosition);
     ZoomLevel       = defaultZoomLevel;
 }
示例#51
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            RockContext rockContext                   = new RockContext();
            var         groupMemberService            = new GroupMemberService(rockContext);
            var         groupService                  = new GroupService(rockContext);
            var         groupTypeService              = new GroupTypeService(rockContext);
            var         attributeService              = new AttributeService(rockContext);
            var         attributeValueService         = new AttributeValueService(rockContext);
            var         personService                 = new PersonService(rockContext);
            var         personAliasService            = new PersonAliasService(rockContext);
            var         entityTypeService             = new EntityTypeService(rockContext);
            var         registrationRegistrantService = new RegistrationRegistrantService(rockContext);
            var         eiogmService                  = new EventItemOccurrenceGroupMapService(rockContext);
            var         groupLocationService          = new GroupLocationService(rockContext);
            var         locationService               = new LocationService(rockContext);
            var         signatureDocumentServce       = new SignatureDocumentService(rockContext);
            var         phoneNumberService            = new PhoneNumberService(rockContext);

            int[] signatureDocumentIds = { };
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates")))
            {
                signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse);
            }
            Guid bbGroup          = GetAttributeValue("Group").AsGuid();
            Guid hsmGroupTypeGuid = GetAttributeValue("HSMGroupType").AsGuid();
            int? hsmGroupTypeId   = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault();

            int entityTypeId            = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id;
            var group                   = new GroupService(rockContext).Get(bbGroup);
            var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList();

            hlGroup.NavigateUrl = "/group/" + group.Id;

            var attributeIds = attributeService.Queryable()
                               .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue)))
                               .Select(a => a.Id).ToList();

            var gmTmpqry = groupMemberService.Queryable()
                           .Where(gm => (gm.GroupId == group.Id));

            var qry = gmTmpqry
                      .Join(registrationRegistrantService.Queryable(),
                            obj => obj.Id,
                            rr => rr.GroupMemberId,
                            (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.GroupMember.Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)) /*, Location = obj.Location */ })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.RegistrationRegistrant.Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)) /*, Location = obj.Location */ });

            var qry2 = gmTmpqry
                       .GroupJoin(
                groupMemberService.Queryable()
                .Join(groupService.Queryable(),
                      gm => new { Id = gm.GroupId, GroupTypeId = 10 },
                      g => new { g.Id, g.GroupTypeId },
                      (gm, g) => new { GroupMember = gm, Group = g })
                .Join(groupLocationService.Queryable(),
                      obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = ( int? )19 },
                      gl => new { gl.GroupId, gl.GroupLocationTypeValueId },
                      (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl })
                .Join(locationService.Queryable(),
                      obj => obj.GroupLocation.LocationId,
                      l => l.Id,
                      (obj, l) => new { GroupMember = obj.GroupMember, Location = l }),
                gm => gm.PersonId,
                glgm => glgm.GroupMember.PersonId,
                (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() }
                )
                       .GroupJoin(signatureDocumentServce.Queryable()
                                  .Join(personAliasService.Queryable(),
                                        sd => sd.AppliesToPersonAliasId,
                                        pa => pa.Id,
                                        (sd, pa) => new { SignatureDocument = sd, Alias = pa }),
                                  obj => obj.GroupMember.PersonId,
                                  sd => sd.Alias.PersonId,
                                  (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds })
                       .GroupJoin(phoneNumberService.Queryable(),
                                  obj => obj.GroupMember.PersonId,
                                  p => p.PersonId,
                                  (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn });


            if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix))))
            {
                string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower();
                qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable();
            }
            decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull();
            decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull();

            if (lowerVal != null && upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal && q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable();
            }
            else if (lowerVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal).AsQueryable();
            }
            else if (upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable();
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var tmp  = qry.ToList();
            var tmp2 = qry2.ToList();

            lStats.Text = "Query Runtime: " + stopwatch.Elapsed;
            stopwatch.Reset();

            stopwatch.Start();

            var newQry = tmp.Select(g => new
            {
                Id                    = g.GroupMember.Id,
                RegisteredBy          = new ModelValue <Person>(g.RegistrationRegistrant.Registration.PersonAlias.Person),
                person                = g.Person,
                Registrant            = new ModelValue <Person>(g.Person),
                Age                   = g.Person.Age,
                GraduationYear        = g.Person.GraduationYear,
                RegistrationId        = g.RegistrationRegistrant.RegistrationId,
                Group                 = new ModelValue <Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group),
                DOB                   = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "",
                Address               = new ModelValue <Location>(tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()),
                Email                 = g.Person.Email,
                Gender                = g.Person.Gender,         // (B & B Registration)
                GraduationYearProfile = g.Person.GraduationYear, // (Person Profile)
                HomePhone             = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(),
                CellPhone             = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(),
                GroupMemberData       = new Func <GroupMemberAttributes>(() =>
                {
                    GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues);
                    return(gma);
                })(),
                RegistrantData = new Func <RegistrantAttributes>(() =>
                {
                    RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant, g.RegistrationAttributeValues);
                    return(row);
                })(),
                LegalRelease = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name.Contains("MINOR") ? "MINOR (" + sd.SignatureDocument.Status.ToString() + ")" : sd.SignatureDocument.SignatureDocumentTemplate.Name.Contains("ADULT") ? "ADULT (" + sd.SignatureDocument.Status.ToString() + ")" : "").FirstOrDefault(), // (highest level form on record, pulled from forms page in Rock)
                Departure    = "TBD",                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              // (hopefully based on bus, otherwise a dropdown with 1-4)
                Campus       = group.Campus,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       //
                Role         = group.ParentGroup.GroupType.Name.Contains("Serving") ? "Leader" : "Student",                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        //
                HSMGroup     = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList())
            }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable();

            lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed;

            stopwatch.Stop();
            gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields;
            var mergeFields = new List <String>();

            mergeFields.Add("Id");
            mergeFields.Add("RegisteredBy");
            mergeFields.Add("Group");
            mergeFields.Add("Registrant");
            mergeFields.Add("Age");
            mergeFields.Add("GraduationYear");
            mergeFields.Add("DOB");
            mergeFields.Add("Address");
            mergeFields.Add("Email");
            mergeFields.Add("Gender");
            mergeFields.Add("GraduationYearProfile");
            mergeFields.Add("HomePhone");
            mergeFields.Add("CellPhone");
            mergeFields.Add("GroupMemberData");
            mergeFields.Add("RegistrantData");
            mergeFields.Add("LegalRelease");
            mergeFields.Add("Departure");
            mergeFields.Add("Campus");
            mergeFields.Add("Role");
            mergeFields.Add("HSMGroup");
            gReport.CommunicateMergeFields = mergeFields;


            if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix))))
            {
                string poa = GetUserPreference(string.Format("{0}POA", keyPrefix));
                if (poa == "[Blank]")
                {
                    poa = "";
                }
                newQry = newQry.Where(q => q.GroupMemberData.POA == poa);
            }

            SortProperty sortProperty = gReport.SortProperty;

            if (sortProperty != null)
            {
                gReport.SetLinqDataSource(newQry.Sort(sortProperty));
            }
            else
            {
                gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName));
            }
            gReport.DataBind();
        }
 public void Update()
 {
     LocationService.Update(this);
 }
示例#53
0
        public void GetLocationsInRadius_ValidZipCodeNegativeRadiusExistingLocationsNearby_ThrowsArgumentOutOfRangeException()
        {
            var locationService = new LocationService(new FakeLocationRepository());

            var ex = Assert.Throws<ArgumentOutOfRangeException>(() => locationService.GetLocationsInRadius("95814", -100.0));
            Assert.True(ex.Message.StartsWith("Radius must be greater than 0"));
        }
 public LocationController(LocationService locationService)
 {
     _locationService = locationService;
 }
示例#55
0
        public void GetLocationsInRadius_ValidZipCodeValidRadiusNoExistingLocationsNearby_ReturnsEmptyList()
        {
            var locationService = new LocationService(new FakeLocationRepository());

            // There should be nothing within one mile of this ZIP code (see FakeLocationRepository's constructor).
            IEnumerable<LocationInRadius> locationsNearby = locationService.GetLocationsInRadius("99950", 1.0);

            // The Location itself is returned.
            Assert.AreEqual(1, locationsNearby.Count());
        }
示例#56
0
        /// <summary>
        /// Handles the Click event of the btnSaveGroup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSaveGroup_Click(object sender, EventArgs e)
        {
            var          rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);

            Group group = groupService.Get(_groupId);

            if (group != null && group.IsAuthorized(Authorization.EDIT, CurrentPerson))
            {
                group.Name        = tbName.Text;
                group.Description = tbDescription.Text;
                group.IsActive    = cbIsActive.Checked;

                if (pnlSchedule.Visible)
                {
                    if (group.Schedule == null)
                    {
                        group.Schedule = new Schedule();
                        group.Schedule.iCalendarContent = null;
                    }

                    group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek;
                    group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime;
                }

                // set attributes
                group.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, group);

                // configure locations
                if (GetAttributeValue("EnableLocationEdit").AsBoolean())
                {
                    // get selected location
                    Location location            = null;
                    int?     memberPersonAliasId = null;

                    if (LocationTypeTab.Equals(MEMBER_LOCATION_TAB_TITLE))
                    {
                        if (ddlMember.SelectedValue != null)
                        {
                            var ids = ddlMember.SelectedValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                            if (ids.Length == 2)
                            {
                                var dbLocation = new LocationService(rockContext).Get(int.Parse(ids[0]));
                                if (dbLocation != null)
                                {
                                    location = dbLocation;
                                }

                                memberPersonAliasId = new PersonAliasService(rockContext).GetPrimaryAliasId(int.Parse(ids[1]));
                            }
                        }
                    }
                    else
                    {
                        if (locpGroupLocation.Location != null)
                        {
                            location = new LocationService(rockContext).Get(locpGroupLocation.Location.Id);
                        }
                    }

                    if (location != null)
                    {
                        GroupLocation groupLocation = group.GroupLocations.FirstOrDefault();

                        if (groupLocation == null)
                        {
                            groupLocation = new GroupLocation();
                            group.GroupLocations.Add(groupLocation);
                        }

                        groupLocation.GroupMemberPersonAliasId = memberPersonAliasId;
                        groupLocation.Location   = location;
                        groupLocation.LocationId = groupLocation.Location.Id;
                        groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();
                    }
                }

                rockContext.SaveChanges();
                group.SaveAttributeValues(rockContext);
            }

            this.IsEditingGroup = false;

            // reload the group info
            pnlGroupEdit.Visible = false;
            pnlGroupView.Visible = true;
            DisplayViewGroup();
        }
        /// <summary>
        /// 保存Json到文件中,同时从告警表分离到图片表或者文件中
        /// </summary>
        /// <param name="callBack"></param>
        public void SeparateImages(Action callBack, int mode, int progressBagCount = 5)
        {
            Log.Info(LogTags.ExtremeVision, "开始 保存Json到文件中,同时从告警表分离到图片表或者文件中");
            Worker.Run(() =>
            {
                //int progressBagCount = 5;

                bool r = true;
                while (r)
                {
                    try
                    {
                        LocationService s = new LocationService();
                        //var list=s.GetAllCameraAlarms(true);
                        var bll   = Bll.NewBllNoRelation();
                        int count = bll.CameraAlarmJsons.DbSet.Count();
                        Log.Info("count:" + count);
                        List <CameraAlarmJson> list2 = bll.CameraAlarmJsons.ToList();
                        Log.Info(LogTags.ExtremeVision, "获取到列表");
                        if (list2 != null)
                        {
                            Log.Info(LogTags.ExtremeVision, "成功");
                            for (int i1 = 0; i1 < list2.Count; i1++)
                            {
                                if (i1 % progressBagCount == 0)
                                {
                                    Log.Info(LogTags.ExtremeVision, string.Format("进度:{0}/{1}", i1, list2.Count));
                                }

                                CameraAlarmJson camera = list2[i1];
                                SavePicture(camera, bll, mode);
                            }
                        }
                        else
                        {
                            Log.Info(LogTags.ExtremeVision, "失败");
                            Log.Info(LogTags.ExtremeVision, "太多了取不出来,一个一个取");
                            for (int i = 0; i < count; i++)
                            {
                                if (i % progressBagCount == 0)
                                {
                                    Log.Info(LogTags.ExtremeVision, string.Format("进度:{0}/{1}", i, count));
                                }
                                CameraAlarmJson camera = bll.CameraAlarmJsons.Find(i + 1);
                                if (camera == null)
                                {
                                    Log.Info("找不到id:" + (i + 1));
                                    continue;
                                }

                                SavePicture(camera, bll, mode);
                            }
                        }
                        Log.Info(LogTags.ExtremeVision, "完成");
                        r = false;//真的完成
                    }
                    catch (Exception exception)
                    {
                        Log.Error(LogTags.ExtremeVision, exception.Message);
                    }
                }
            }, () =>
            {
                if (callBack != null)
                {
                    callBack();
                }
            });
        }
        /// <summary>
        /// Method to save attendance for use in two separate areas.
        /// </summary>
        protected bool SaveAttendance()
        {
            using (var rockContext = new RockContext())
            {
                var occurrenceService  = new AttendanceOccurrenceService(rockContext);
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var locationService    = new LocationService(rockContext);

                AttendanceOccurrence occurrence = null;

                if (_occurrence.Id != 0)
                {
                    occurrence = occurrenceService.Get(_occurrence.Id);
                }

                if (occurrence == null)
                {
                    var existingOccurrence = occurrenceService.Get(_occurrence.OccurrenceDate, _group.Id, _occurrence.LocationId, _occurrence.ScheduleId);
                    if (existingOccurrence != null)
                    {
                        nbNotice.Heading             = "Occurrence Already Exists";
                        nbNotice.Text                = "<p>An occurrence already exists for this group for the selected date, location, and schedule that you've selected. Please return to the list and select that occurrence to update it's attendance.</p>";
                        nbNotice.NotificationBoxType = NotificationBoxType.Danger;
                        nbNotice.Visible             = true;

                        return(false);
                    }
                    else
                    {
                        occurrence                = new AttendanceOccurrence();
                        occurrence.GroupId        = _occurrence.GroupId;
                        occurrence.LocationId     = _occurrence.LocationId;
                        occurrence.ScheduleId     = _occurrence.ScheduleId;
                        occurrence.OccurrenceDate = _occurrence.OccurrenceDate;
                        occurrenceService.Add(occurrence);
                    }
                }

                occurrence.Notes       = GetAttributeValue("ShowNotes").AsBoolean() ? dtNotes.Text : string.Empty;
                occurrence.DidNotOccur = cbDidNotMeet.Checked;

                var existingAttendees = occurrence.Attendees.ToList();

                // If did not meet was selected and this was a manually entered occurrence (not based on a schedule/location)
                // then just delete all the attendance records instead of tracking a 'did not meet' value
                if (cbDidNotMeet.Checked && !_occurrence.ScheduleId.HasValue)
                {
                    foreach (var attendance in existingAttendees)
                    {
                        attendanceService.Delete(attendance);
                    }
                }
                else
                {
                    int?campusId = locationService.GetCampusIdForLocation(_occurrence.LocationId) ?? _group.CampusId;
                    if (!campusId.HasValue && _allowCampusFilter)
                    {
                        var campus = CampusCache.Get(bddlCampus.SelectedValueAsInt() ?? 0);
                        if (campus != null)
                        {
                            campusId = campus.Id;
                        }
                    }

                    if (cbDidNotMeet.Checked)
                    {
                        // If the occurrence is based on a schedule, set the did not meet flags
                        foreach (var attendance in existingAttendees)
                        {
                            attendance.DidAttend = null;
                        }
                    }
                    else
                    {
                        foreach (var attendee in _attendees)
                        {
                            var attendance = existingAttendees
                                             .Where(a => a.PersonAlias.PersonId == attendee.PersonId)
                                             .FirstOrDefault();

                            if (attendance == null)
                            {
                                int?personAliasId = personAliasService.GetPrimaryAliasId(attendee.PersonId);
                                if (personAliasId.HasValue)
                                {
                                    attendance = new Attendance();
                                    attendance.PersonAliasId = personAliasId;
                                    attendance.CampusId      = campusId;
                                    attendance.StartDateTime = _occurrence.OccurrenceDate;

                                    // check that the attendance record is valid
                                    cvAttendance.IsValid = attendance.IsValid;
                                    if (!cvAttendance.IsValid)
                                    {
                                        cvAttendance.ErrorMessage = attendance.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                                        return(false);
                                    }

                                    occurrence.Attendees.Add(attendance);
                                }
                            }

                            if (attendance != null)
                            {
                                attendance.DidAttend = attendee.Attended;
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                if (occurrence.LocationId.HasValue)
                {
                    Rock.CheckIn.KioskLocationAttendance.Remove(occurrence.LocationId.Value);
                }


                Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        try
                        {
                            var workflow = Workflow.Activate(workflowType, _group.Name);

                            workflow.SetAttributeValue("StartDateTime", _occurrence.OccurrenceDate.ToString("o"));
                            workflow.SetAttributeValue("Schedule", _group.Schedule.Guid.ToString());

                            List <string> workflowErrors;
                            new WorkflowService(rockContext).Process(workflow, _group, out workflowErrors);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }
            }

            return(true);
        }
示例#59
0
        public void GetByCityState_ValidCityValidState_ReturnsNonEmptyList()
        {
            // Arrange
            var locationService = new LocationService(new FakeLocationRepository());

            // Act
            IEnumerable<Location> sactoLocations = locationService.GetByCityState("Sacramento", "CA");

            // Assert
            Assert.True(sactoLocations.Count() > 0);
        }
        /// <summary>
        /// 从图片表分离到文件中
        /// </summary>
        /// <param name="callBack"></param>
        public void SeparateImages_PicToFile(Action callBack)
        {
            Log.Info(LogTags.ExtremeVision, "开始 从图片表分离到文件中");

            Worker.Run(() =>
            {
                try
                {
                    //var bll = Bll.NewBllNoRelation();
                    int picCount = GetPictureCount();
                    if (picCount == 0)
                    {
                        Log.Info(LogTags.ExtremeVision, "Picture表中没有告警图片");
                        return;
                    }

                    int count = db.Pictures.DbSet.Count();
                    Log.Info(LogTags.ExtremeVision, "pic count:" + count);

                    LocationService s = new LocationService();
                    var list          = s.GetAllCameraAlarms(false);

                    Log.Info(LogTags.ExtremeVision, "alarm count:" + list.Count);

                    List <string> picNameList = new List <string>();
                    foreach (var item in list)
                    {
                        if (!picNameList.Contains(item.pic_name))
                        {
                            picNameList.Add(item.pic_name);
                        }
                    }

                    Log.Info(LogTags.ExtremeVision, "pic count 2:" + picNameList.Count);

                    //return;
                    //for (int i1 = 0; i1 < picNameList.Count; i1++)
                    //{
                    //    Log.Info(string.Format("进度:{0}/{1}", i1, picNameList.Count));
                    //    //CameraAlarmInfo camera = picNameList[i1];
                    //    //SavePicture(camera, bll);
                    //    //Picture pic = s.GetCameraAlarmPicture(picNameList[i1]);
                    //    string picName = picNameList[i1];
                    //    Picture pic = db.Pictures.Find(i => i.Name == picName);
                    //    if (pic == null) continue;//已经提取出来的
                    //    SaveFile(pic);
                    //    var r = db.Pictures.DeleteById(pic.Id);
                    //}

                    List <Picture> upViewList = new List <Picture>();

                    var picList = db.Pictures.ToList();

                    for (int i = 0; i < count; i++)
                    {
                        try
                        {
                            Log.Info(LogTags.ExtremeVision, string.Format("进度:{0}/{1}", i, count));
                            Picture pic = picList[i];
                            if (pic == null)
                            {
                                continue;
                            }
                            if (pic.Name != "顶视图")
                            {
                                PictureSaveFile(pic);
                                var r = db.Pictures.DeleteById(pic.Id);
                            }
                            else
                            {
                                upViewList.Add(pic);//定视图
                            }
                        }
                        catch (Exception ex1)
                        {
                            Log.Error(LogTags.ExtremeVision, ex1.Message);
                        }
                    }

                    if (upViewList.Count > 1)
                    {
                        for (int i = 1; i < upViewList.Count; i++)
                        {
                            var r = db.Pictures.DeleteById(upViewList[i].Id);//重复的顶视图图片
                        }
                    }

                    Log.Info(LogTags.ExtremeVision, "完成");
                }
                catch (Exception ex2)
                {
                    Log.Error(LogTags.ExtremeVision, ex2.Message);
                }
            }, () =>
            {
                if (callBack != null)
                {
                    callBack();
                }
            });
        }