/// <summary> /// Returns a kiosk based on finding a geo location match for the given latitude and longitude. /// </summary> /// <param name="sLatitude">latitude as string</param> /// <param name="sLongitude">longitude as string</param> /// <returns></returns> public static Device GetCurrentKioskByGeoFencing( string sLatitude, string sLongitude ) { double latitude = double.Parse( sLatitude ); double longitude = double.Parse( sLongitude ); var checkInDeviceTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.DEVICE_TYPE_CHECKIN_KIOSK ).Id; // We need to use the DeviceService until we can get the GeoFence to JSON Serialize/Deserialize. Device kiosk = new DeviceService( new RockContext() ).GetByGeocode( latitude, longitude, checkInDeviceTypeId ); return kiosk; }
/// <summary> /// Displays the text of the current filters /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> protected void fDevice_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e ) { switch ( e.Key ) { case "Printer": int deviceId = 0; if ( int.TryParse( e.Value, out deviceId ) ) { var service = new DeviceService( new RockContext() ); var device = service.Get( deviceId ); if ( device != null ) { e.Value = device.Name; } } break; case "Device Type": int definedValueId = 0; if ( int.TryParse( e.Value, out definedValueId ) ) { var definedValue = DefinedValueCache.Read( definedValueId ); if ( definedValue != null ) { e.Value = definedValue.Value; } } break; case "Print To": e.Value = ( (PrintTo)System.Enum.Parse( typeof( PrintTo ), e.Value ) ).ToString(); break; case "Print From": e.Value = ( (PrintFrom)System.Enum.Parse( typeof( PrintFrom ), e.Value ) ).ToString(); break; } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var deviceService = new DeviceService( new RockContext() ); var sortProperty = gDevice.SortProperty; gDevice.EntityTypeId = EntityTypeCache.Read<Device>().Id; var queryable = deviceService.Queryable().Select( a => new { a.Id, a.Name, DeviceTypeName = a.DeviceType.Value, a.IPAddress, a.PrintToOverride, a.PrintFrom, PrinterDeviceName = a.PrinterDevice.Name, a.PrinterDeviceId, a.DeviceTypeValueId } ); string name = fDevice.GetUserPreference( "Name" ); if ( !string.IsNullOrWhiteSpace( name ) ) { queryable = queryable.Where( d => d.Name.Contains( name ) ); } int? deviceTypeId = fDevice.GetUserPreference( "Device Type" ).AsIntegerOrNull(); if ( deviceTypeId.HasValue ) { queryable = queryable.Where( d => d.DeviceTypeValueId == deviceTypeId.Value ); } string ipAddress = fDevice.GetUserPreference( "IP Address" ); if ( !string.IsNullOrWhiteSpace( ipAddress ) ) { queryable = queryable.Where( d => d.IPAddress.Contains( ipAddress ) ); } if ( !string.IsNullOrWhiteSpace( fDevice.GetUserPreference( "Print To" ) ) ) { PrintTo printTo = (PrintTo)System.Enum.Parse( typeof( PrintTo ), fDevice.GetUserPreference( "Print To" ) ); ; queryable = queryable.Where( d => d.PrintToOverride == printTo ); } int? printerId = fDevice.GetUserPreference( "Printer" ).AsIntegerOrNull(); if ( printerId.HasValue ) { queryable = queryable.Where( d => d.PrinterDeviceId == printerId ); } if ( !string.IsNullOrWhiteSpace( fDevice.GetUserPreference( "Print From" ) ) ) { PrintFrom printFrom = (PrintFrom)System.Enum.Parse( typeof( PrintFrom ), fDevice.GetUserPreference( "Print From" ) ); ; queryable = queryable.Where( d => d.PrintFrom == printFrom ); } if ( sortProperty != null ) { gDevice.DataSource = queryable.Sort( sortProperty ).ToList(); } else { gDevice.DataSource = queryable.OrderBy( d => d.Name ).ToList(); } gDevice.EntityTypeId = EntityTypeCache.Read<Rock.Model.Device>().Id; gDevice.DataBind(); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { if ( !Page.IsPostBack ) { RockPage.AddScriptLink( "~/Blocks/CheckIn/Scripts/geo-min.js" ); bool enableLocationSharing = bool.Parse( GetAttributeValue( "EnableLocationSharing" ) ?? "false" ); if ( enableLocationSharing ) { lbRetry.Visible = true; AddGeoLocationScript(); } else { AttemptKioskMatchByIpOrName(); } string script = string.Format( @" <script> $(document).ready( function (e) {{ if (localStorage) {{ if (localStorage.checkInKiosk) {{ $('[id$=""hfKiosk""]').val(localStorage.checkInKiosk); if (localStorage.checkInGroupTypes) {{ $('[id$=""hfGroupTypes""]').val(localStorage.checkInGroupTypes); }} {0}; }} }} }}); </script> ", this.Page.ClientScript.GetPostBackEventReference( lbRefresh, "" ) ); phScript.Controls.Add( new LiteralControl( script ) ); if ( !CurrentKioskId.HasValue || UserBackedUp || CurrentGroupTypeIds == null ) { // #DEBUG, may be the local machine var kiosk = new DeviceService( new RockContext() ).Queryable().Where( d => d.Name == Environment.MachineName ).FirstOrDefault(); if ( kiosk != null ) { CurrentKioskId = kiosk.Id; BindGroupTypes(); } else { maWarning.Show( "This device has not been set up for check-in.", ModalAlertType.Warning ); lbOk.Visible = false; return; } } else { NavigateToNextPage(); } lbOk.Focus(); SaveState(); } else { phScript.Controls.Clear(); } }
/// <summary> /// Verifies the ip address is unique. /// </summary> private bool VerifyUniqueIpAddress() { bool isValid = true; int currentDeviceId = int.Parse( hfDeviceId.Value ); int? deviceTypeId = ddlDeviceType.SelectedValueAsInt().Value; if ( !string.IsNullOrWhiteSpace( tbIpAddress.Text ) && deviceTypeId != null ) { var rockContext = new RockContext(); bool ipExists = new DeviceService( rockContext ).Queryable() .Any( d => d.IPAddress.Equals( tbIpAddress.Text ) && d.DeviceTypeValueId == deviceTypeId && d.Id != currentDeviceId ); isValid = !ipExists; } return isValid; }
private void SetCampus() { RockContext rockContext = new RockContext(); Campus campus = null; // get device string deviceIp = GetIPAddress(); DeviceService deviceService = new DeviceService(rockContext); var deviceQry = deviceService.Queryable( "Location" ) .Where( d => d.IPAddress == deviceIp ); // add device type filter if (!string.IsNullOrWhiteSpace(GetAttributeValue("DeviceType"))) { Guid givingKioskGuid = new Guid( GetAttributeValue("DeviceType")); deviceQry = deviceQry.Where( d => d.DeviceType.Guid == givingKioskGuid); } var device = deviceQry.FirstOrDefault(); if ( device != null ) { if ( device.Locations.Count > 0 ) { campus = new CampusService( new RockContext() ).Get( device.Locations.First().CampusId.Value ); // set the context if ( campus != null ) { var campusEntityType = EntityTypeCache.Read( "Rock.Model.Campus" ); var currentCampus = RockPage.GetCurrentContext( campusEntityType ) as Campus; if ( currentCampus == null || currentCampus.Id != campus.Id ) { bool pageScope = GetAttributeValue( "ContextScope" ) == "Page"; RockPage.SetContextCookie( campus, pageScope, true ); } } } } // set display output var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson ); mergeFields.Add( "ClientIp", deviceIp ); mergeFields.Add( "Device", device ); mergeFields.Add( "Campus", campus ); lOutput.Text = GetAttributeValue( "DisplayLava" ).ResolveMergeFields( mergeFields ); // show debug info if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) ) { lDebug.Visible = true; lDebug.Text = mergeFields.lavaDebugInfo(); } }
private void BindGroupTypes( string selectedValues ) { var selectedItems = selectedValues.Split( ',' ); cblGroupTypes.Items.Clear(); if ( ddlKiosk.SelectedValue != None.IdValue ) { var kiosk = new DeviceService( new RockContext() ).Get( Int32.Parse( ddlKiosk.SelectedValue ) ); if ( kiosk != null ) { cblGroupTypes.DataSource = GetDeviceGroupTypes( kiosk.Id ); cblGroupTypes.DataBind(); } if ( selectedValues != string.Empty ) { foreach ( string id in selectedValues.Split(',') ) { ListItem item = cblGroupTypes.Items.FindByValue( id ); if ( item != null ) { item.Selected = true; } } } else { if ( CurrentGroupTypeIds != null ) { foreach ( int id in CurrentGroupTypeIds ) { ListItem item = cblGroupTypes.Items.FindByValue( id.ToString() ); if ( item != null ) { item.Selected = true; } } } } } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="action">The workflow action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override bool Execute( Model.WorkflowAction action, Object entity, out List<string> errorMessages ) { var checkInState = GetCheckInState( entity, out errorMessages ); var labels = new List<CheckInLabel>(); if ( checkInState != null ) { int labelFileTypeId = new BinaryFileTypeService() .Queryable() .Where( f => f.Guid == new Guid(SystemGuid.BinaryFiletype.CHECKIN_LABEL)) .Select( f => f.Id) .FirstOrDefault(); if (labelFileTypeId != 0) { using ( var uow = new Rock.Data.UnitOfWorkScope() ) { foreach ( var family in checkInState.CheckIn.Families.Where( f => f.Selected ) ) { foreach ( var person in family.People.Where( p => p.Selected ) ) { foreach ( var groupType in person.GroupTypes.Where( g => g.Selected ) ) { var mergeObjects = new Dictionary<string, object>(); mergeObjects.Add( "person", person ); mergeObjects.Add( "groupType", groupType ); groupType.Labels = new List<CheckInLabel>(); GetGroupTypeLabels( groupType.GroupType, groupType.Labels, labelFileTypeId, mergeObjects ); var PrinterIPs = new Dictionary<int, string>(); foreach ( var label in groupType.Labels ) { label.PrintFrom = checkInState.Kiosk.Device.PrintFrom; label.PrintTo = checkInState.Kiosk.Device.PrintToOverride; if ( label.PrintTo == PrintTo.Default ) { label.PrintTo = groupType.GroupType.AttendancePrintTo; } if ( label.PrintTo == PrintTo.Kiosk ) { var device = checkInState.Kiosk.Device; if ( device != null ) { label.PrinterDeviceId = device.PrinterDeviceId; } } else if ( label.PrintTo == PrintTo.Location ) { // Should only be one var group = groupType.Groups.Where( g => g.Selected ).FirstOrDefault(); if ( group != null ) { var location = group.Locations.Where( l => l.Selected ).FirstOrDefault(); if ( location != null ) { var device = location.Location.PrinterDevice; if ( device != null ) { label.PrinterDeviceId = device.PrinterDeviceId; } } } } if ( label.PrinterDeviceId.HasValue ) { if ( PrinterIPs.ContainsKey( label.PrinterDeviceId.Value ) ) { label.PrinterAddress = PrinterIPs[label.PrinterDeviceId.Value]; } else { var printerDevice = new DeviceService().Get( label.PrinterDeviceId.Value ); if ( printerDevice != null ) { PrinterIPs.Add( printerDevice.Id, printerDevice.IPAddress ); label.PrinterAddress = printerDevice.IPAddress; } } } } } } } } } return true; } return false; }
/// <summary> /// Reads the device by id. /// </summary> /// <param name="id">The id.</param> /// <param name="configuredGroupTypes">The configured group types.</param> /// <returns></returns> public static KioskDevice Read( int id, List<int> configuredGroupTypes ) { string cacheKey = KioskDevice.CacheKey( id ); ObjectCache cache = MemoryCache.Default; KioskDevice device = cache[cacheKey] as KioskDevice; // If the kioskdevice is currently inactive, but has a next active time prior to now, force a refresh if ( device != null && device.FilteredGroupTypes(configuredGroupTypes).Count > 0 && !device.HasLocations( configuredGroupTypes ) ) { if ( device.KioskGroupTypes.Select( g => g.NextActiveTime ).Min().CompareTo( DateTimeOffset.Now ) < 0 ) { device = null; } } if (device != null) { return device; } else { var rockContext = new RockContext(); var deviceModel = new DeviceService( rockContext ) .Queryable( "Locations" ) .Where( d => d.Id == id ) .FirstOrDefault(); if ( deviceModel != null ) { device = new KioskDevice( deviceModel ); foreach ( Location location in deviceModel.Locations ) { LoadKioskLocations( device, location, rockContext ); } var cachePolicy = new CacheItemPolicy(); cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds( 60 ); cache.Set( cacheKey, device, cachePolicy ); return device; } } return null; }
/// <summary> /// Attempts to match a known kiosk based on the IP address of the client. /// </summary> private void AttemptKioskMatchByIpOrName() { // match kiosk by ip/name. string ipAddress = RockPage.GetClientIpAddress(); bool lookupKioskName = GetAttributeValue( "EnableReverseLookup" ).AsBoolean( false ); var rockContext = new RockContext(); var checkInDeviceTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.DEVICE_TYPE_CHECKIN_KIOSK ).Id; var device = new DeviceService( rockContext ).GetByIPAddress( ipAddress, checkInDeviceTypeId, lookupKioskName ); string hostName = string.Empty; string deviceLocation = string.Empty; try { hostName = Dns.GetHostEntry( ipAddress ).HostName; } catch ( System.Net.Sockets.SocketException ) { hostName = "Unknown"; } if ( device != null ) { var location = device.Locations.FirstOrDefault(); if ( location != null ) { deviceLocation = location.Name; } ClearMobileCookie(); CurrentKioskId = device.Id; } else { maAlert.Show( "This device has not been set up for check-in.", ModalAlertType.Alert ); lbOk.Text = @"<span class='fa fa-refresh' />"; lbOk.Enabled = false; } lblInfo.Text = string.Format( "Device IP: {0} Name: {1} Location: {2}", ipAddress, hostName, deviceLocation ); pnlContent.Update(); pnlHeader.Update(); }
/// <summary> /// Prints a test label. /// </summary> protected void SendTestPrint() { if ( CurrentKioskId != null ) { // get the current kiosk print options Device device = null; if ( CurrentCheckInState != null ) { device = CurrentCheckInState.Kiosk.Device; } // get the current device and printer if ( device == null || device.PrinterDevice == null ) { using ( var rockContext = new RockContext() ) { var deviceService = new DeviceService( rockContext ); device = device ?? deviceService.Get( (int)CurrentKioskId ); device.PrinterDevice = device.PrinterDevice ?? deviceService.Get( (int)device.PrinterDeviceId ); } } var printerAddress = string.Empty; if ( device != null && device.PrinterDevice != null ) { printerAddress = device.PrinterDevice.IPAddress; } // set the label content var labelContent = GetAttributeValue( "TestLabelContent" ); labelContent = Regex.Replace( labelContent, string.Format( @"(?<=\^FD){0}(?=\^FS)", "DeviceName" ), device.Name ); labelContent = Regex.Replace( labelContent, string.Format( @"(?<=\^FD){0}(?=\^FS)", "PrinterIP" ), printerAddress ); // try printing the label if ( !string.IsNullOrWhiteSpace( labelContent ) && !string.IsNullOrWhiteSpace( printerAddress ) ) { var socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); var printerIpEndPoint = new IPEndPoint( IPAddress.Parse( printerAddress ), 9100 ); var result = socket.BeginConnect( printerIpEndPoint, null, null ); bool success = result.AsyncWaitHandle.WaitOne( 5000, true ); if ( socket.Connected ) { var ns = new NetworkStream( socket ); byte[] toSend = System.Text.Encoding.ASCII.GetBytes( labelContent.ToString() ); ns.Write( toSend, 0, toSend.Length ); } else { maAlert.Show( string.Format( "Can't connect to printer {0} from {1}", printerAddress, device.Name ), ModalAlertType.Alert ); pnlContent.Update(); } if ( socket != null && socket.Connected ) { socket.Shutdown( SocketShutdown.Both ); socket.Close(); } maAlert.Show( string.Format( "Sent a test print job to {0} from {1}", printerAddress, device.Name ), ModalAlertType.Information ); pnlContent.Update(); } else { maAlert.Show( "The test label or the device printer isn't configured with an IP address.", ModalAlertType.Alert ); pnlContent.Update(); } } else { maAlert.Show( "Current check-in state is not instantiated.", ModalAlertType.Alert ); pnlContent.Update(); } }
/// <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; } }
/// <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; DeviceService DeviceService = new DeviceService(); AttributeService attributeService = new AttributeService(); int DeviceId = int.Parse( hfDeviceId.Value ); if ( DeviceId == 0 ) { Device = new Device(); DeviceService.Add( Device, CurrentPersonId ); } else { Device = DeviceService.Get( DeviceId ); } 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 = gpGeoPoint.SelectedValue; Device.Location.GeoFence = gpGeoFence.SelectedValue; if ( !Device.IsValid ) { // Controls will render the error messages return; } DeviceService.Save( Device, CurrentPersonId ); NavigateToParentPage(); }
/// <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 btnPrint_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var device = new DeviceService( rockContext ).Get( ddlDevice.SelectedValueAsInt() ?? 0 ); if ( device != null ) { string currentIp = device.IPAddress; var printerIp = new IPEndPoint( IPAddress.Parse( currentIp ), 9100 ); var socket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); IAsyncResult result = socket.BeginConnect( printerIp, null, null ); bool success = result.AsyncWaitHandle.WaitOne( 5000, true ); if ( socket.Connected ) { var ns = new NetworkStream( socket ); byte[] toSend = System.Text.Encoding.ASCII.GetBytes( ceLabel.Text ); ns.Write( toSend, 0, toSend.Length ); socket.Shutdown( SocketShutdown.Both ); socket.Close(); } } } }
/// <summary> /// Binds the group types. /// </summary> /// <param name="selectedValues">The selected values.</param> private void BindGroupTypes( string selectedGroupTypes ) { if ( CurrentKioskId > 0 ) { var kiosk = new DeviceService( new RockContext() ).Get( (int)CurrentKioskId ); if ( kiosk != null ) { var groupTypes = kiosk.Locations.SelectMany( l => l.GroupLocations .Select( gl => gl.Group.GroupType ) ).Distinct().ToList(); hfGroupTypes.Value = selectedGroupTypes; repMinistry.DataSource = groupTypes; repMinistry.DataBind(); } } }
/// <summary> /// Attempts to match a known kiosk based on the IP address of the client. /// </summary> private void AttemptKioskMatchByIpOrName() { // match kiosk by REMOTE_ADDR (ip/name). var checkInDeviceTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.DEVICE_TYPE_CHECKIN_KIOSK ).Id; var device = new DeviceService( new RockContext() ).GetByIPAddress( Request.ServerVariables["REMOTE_ADDR"], checkInDeviceTypeId, false ); if ( device != null ) { ClearMobileCookie(); CurrentKioskId = device.Id; BindGroupTypes( hfGroupTypes.Value ); } }
/// <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; var rockContext = new RockContext(); var deviceService = new DeviceService( rockContext ); var attributeService = new AttributeService( rockContext ); var locationService = new LocationService( rockContext ); int DeviceId = int.Parse( hfDeviceId.Value ); if ( DeviceId == 0 ) { Device = new Device(); deviceService.Add( Device ); } else { Device = deviceService.Get( DeviceId ); } 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; 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.SaveChanges(); NavigateToParentPage(); }
/// <summary> /// Reads the device by id. /// </summary> /// <param name="id">The id.</param> /// <param name="configuredGroupTypes">The configured group types.</param> /// <returns></returns> public static KioskDevice Read( int id, List<int> configuredGroupTypes ) { object obj = new object(); obj =_locks.GetOrAdd( id, obj ); lock ( obj ) { string cacheKey = KioskDevice.CacheKey( id ); ObjectCache cache = Rock.Web.Cache.RockMemoryCache.Default; KioskDevice device = cache[cacheKey] as KioskDevice; if ( device != null ) { return device; } else { using ( var rockContext = new RockContext() ) { var campusLocations = new Dictionary<int, int>(); Rock.Web.Cache.CampusCache.All() .Where( c => c.LocationId.HasValue ) .Select( c => new { CampusId = c.Id, LocationId = c.LocationId.Value } ) .ToList() .ForEach( c => campusLocations.Add( c.CampusId, c.LocationId ) ); var deviceModel = new DeviceService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.Id == id ) .FirstOrDefault(); if ( deviceModel != null ) { device = new KioskDevice( deviceModel ); foreach ( Location location in deviceModel.Locations ) { LoadKioskLocations( device, location, campusLocations, rockContext ); } cache.Set( cacheKey, device, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.Date.AddDays( 1 ) } ); return device; } } } } return null; }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The workflow action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override bool Execute( RockContext rockContext, Model.WorkflowAction action, Object entity, out List<string> errorMessages ) { var checkInState = GetCheckInState( entity, out errorMessages ); if ( checkInState != null ) { var family = checkInState.CheckIn.CurrentFamily; if ( family != null ) { var commonMergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null ); var groupMemberService = new GroupMemberService( rockContext ); var familyLabels = new List<Guid>(); var people = family.GetPeople( true ); foreach ( var person in people ) { var personGroupTypes = person.GetGroupTypes( true ); var groupTypes = new List<CheckInGroupType>(); // Get Primary area group types first personGroupTypes.Where( t => checkInState.ConfiguredGroupTypes.Contains( t.GroupType.Id ) ).ToList().ForEach( t => groupTypes.Add( t ) ); // Then get additional areas personGroupTypes.Where( t => !checkInState.ConfiguredGroupTypes.Contains( t.GroupType.Id ) ).ToList().ForEach( t => groupTypes.Add( t ) ); var personLabels = new List<Guid>(); foreach ( var groupType in groupTypes ) { groupType.Labels = new List<CheckInLabel>(); var groupTypeLabels = GetGroupTypeLabels( groupType.GroupType ); var PrinterIPs = new Dictionary<int, string>(); foreach ( var labelCache in groupTypeLabels ) { foreach ( var group in groupType.GetGroups( true ) ) { foreach ( var location in group.GetLocations( true ) ) { if ( labelCache.LabelType == KioskLabelType.Family ) { if ( familyLabels.Contains( labelCache.Guid ) || personLabels.Contains( labelCache.Guid ) ) { break; } else { familyLabels.Add( labelCache.Guid ); } } else if ( labelCache.LabelType == KioskLabelType.Person ) { if ( personLabels.Contains( labelCache.Guid ) ) { break; } else { personLabels.Add( labelCache.Guid ); } } var mergeObjects = new Dictionary<string, object>(); foreach ( var keyValue in commonMergeFields ) { mergeObjects.Add( keyValue.Key, keyValue.Value ); } mergeObjects.Add( "Location", location ); mergeObjects.Add( "Group", group ); mergeObjects.Add( "Person", person ); mergeObjects.Add( "People", people ); mergeObjects.Add( "GroupType", groupType ); var groupMembers = groupMemberService.Queryable().AsNoTracking() .Where( m => m.PersonId == person.Person.Id && m.GroupId == group.Group.Id ) .ToList(); mergeObjects.Add( "GroupMembers", groupMembers ); var label = new CheckInLabel( labelCache, mergeObjects ); label.FileGuid = labelCache.Guid; label.PrintFrom = checkInState.Kiosk.Device.PrintFrom; label.PrintTo = checkInState.Kiosk.Device.PrintToOverride; if ( label.PrintTo == PrintTo.Default ) { label.PrintTo = groupType.GroupType.AttendancePrintTo; } if ( label.PrintTo == PrintTo.Kiosk ) { var device = checkInState.Kiosk.Device; if ( device != null ) { label.PrinterDeviceId = device.PrinterDeviceId; } } else if ( label.PrintTo == PrintTo.Location ) { var deviceId = location.Location.PrinterDeviceId; if ( deviceId != null ) { label.PrinterDeviceId = deviceId; } } if ( label.PrinterDeviceId.HasValue ) { if ( PrinterIPs.ContainsKey( label.PrinterDeviceId.Value ) ) { label.PrinterAddress = PrinterIPs[label.PrinterDeviceId.Value]; } else { var printerDevice = new DeviceService( rockContext ).Get( label.PrinterDeviceId.Value ); if ( printerDevice != null ) { PrinterIPs.Add( printerDevice.Id, printerDevice.IPAddress ); label.PrinterAddress = printerDevice.IPAddress; } } } groupType.Labels.Add( label ); } } } } } } return true; } return false; }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The workflow action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override bool Execute( RockContext rockContext, Model.WorkflowAction action, Object entity, out List<string> errorMessages ) { var checkInState = GetCheckInState( entity, out errorMessages ); var labels = new List<CheckInLabel>(); if ( checkInState != null ) { var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ); var globalMergeValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( null ); foreach ( var family in checkInState.CheckIn.Families.Where( f => f.Selected ) ) { foreach ( var person in family.People.Where( p => p.Selected ) ) { foreach ( var groupType in person.GroupTypes.Where( g => g.Selected ) ) { var mergeObjects = new Dictionary<string, object>(); foreach ( var keyValue in globalMergeValues ) { mergeObjects.Add( keyValue.Key, keyValue.Value ); } mergeObjects.Add( "Person", person ); mergeObjects.Add( "GroupType", groupType ); groupType.Labels = new List<CheckInLabel>(); GetGroupTypeLabels( groupType.GroupType, groupType.Labels, mergeObjects ); var PrinterIPs = new Dictionary<int, string>(); foreach ( var label in groupType.Labels ) { label.PrintFrom = checkInState.Kiosk.Device.PrintFrom; label.PrintTo = checkInState.Kiosk.Device.PrintToOverride; if ( label.PrintTo == PrintTo.Default ) { label.PrintTo = groupType.GroupType.AttendancePrintTo; } if ( label.PrintTo == PrintTo.Kiosk ) { var device = checkInState.Kiosk.Device; if ( device != null ) { label.PrinterDeviceId = device.PrinterDeviceId; } } else if ( label.PrintTo == PrintTo.Location ) { // Should only be one var group = groupType.Groups.Where( g => g.Selected ).FirstOrDefault(); if ( group != null ) { var location = group.Locations.Where( l => l.Selected ).FirstOrDefault(); if ( location != null ) { var device = location.Location.PrinterDevice; if ( device != null ) { label.PrinterDeviceId = device.PrinterDeviceId; } } } } if ( label.PrinterDeviceId.HasValue ) { if ( PrinterIPs.ContainsKey( label.PrinterDeviceId.Value ) ) { label.PrinterAddress = PrinterIPs[label.PrinterDeviceId.Value]; } else { var printerDevice = new DeviceService( rockContext ).Get( label.PrinterDeviceId.Value ); if ( printerDevice != null ) { PrinterIPs.Add( printerDevice.Id, printerDevice.IPAddress ); label.PrinterAddress = printerDevice.IPAddress; } } } } } } } return true; } return false; }
/// <summary> /// Attempts to match a known kiosk based on the IP address of the client. /// </summary> private void AttemptKioskMatchByIpOrName() { // try to find matching kiosk by REMOTE_ADDR (ip/name). var checkInDeviceTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.DEVICE_TYPE_CHECKIN_KIOSK ).Id; var device = new DeviceService( new RockContext() ).GetByIPAddress( Request.ServerVariables["REMOTE_ADDR"], checkInDeviceTypeId, false ); if ( device != null ) { ClearMobileCookie(); CurrentKioskId = device.Id; CurrentGroupTypeIds = GetAllKiosksGroupTypes( device ); ; CurrentCheckInState = null; CurrentWorkflow = null; SaveState(); NavigateToNextPage(); } }
/// <summary> /// Reads the device by id. /// </summary> /// <param name="id">The id.</param> /// <param name="configuredGroupTypes">The configured group types.</param> /// <returns></returns> public static KioskDevice Read( int id, List<int> configuredGroupTypes ) { object obj = new object(); obj =_locks.GetOrAdd( id, obj ); lock ( obj ) { string cacheKey = KioskDevice.CacheKey( id ); ObjectCache cache = Rock.Web.Cache.RockMemoryCache.Default; KioskDevice device = cache[cacheKey] as KioskDevice; // If the kioskdevice is currently inactive, but has a next active time prior to now, force a refresh if ( device != null && device.FilteredGroupTypes(configuredGroupTypes).Count > 0 && !device.HasLocations( configuredGroupTypes ) ) { if ( device.KioskGroupTypes.Select( g => g.NextActiveTime ).Min().CompareTo( RockDateTime.Now ) < 0 ) { device = null; } } if ( device != null ) { return device; } else { using ( var rockContext = new RockContext() ) { var campusLocations = new Dictionary<int, int>(); Rock.Web.Cache.CampusCache.All() .Where( c => c.LocationId.HasValue ) .Select( c => new { CampusId = c.Id, LocationId = c.LocationId.Value } ) .ToList() .ForEach( c => campusLocations.Add( c.CampusId, c.LocationId ) ); var deviceModel = new DeviceService( rockContext ) .Queryable( "Locations" ).AsNoTracking() .Where( d => d.Id == id ) .FirstOrDefault(); if ( deviceModel != null ) { device = new KioskDevice( deviceModel ); foreach ( Location location in deviceModel.Locations ) { LoadKioskLocations( device, location, campusLocations, rockContext ); } var cachePolicy = new CacheItemPolicy(); cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds( 60 ); cache.Set( cacheKey, device, cachePolicy ); return device; } } } } return null; }
/// <summary> /// returns the locations for this Kiosk for the configured group types /// </summary> /// <param name="configuredGroupTypes">The configured group types.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public IEnumerable<Location> Locations( List<int> configuredGroupTypes, RockContext rockContext ) { var result = new List<Rock.Model.Location>(); Rock.Model.Device currentDevice = new DeviceService( rockContext ).Get(this.Device.Id); // first, get all the possible locations for this device including child locations var allLocations = new List<int>(); foreach ( Rock.Model.Location location in currentDevice.Locations ) { // add the location to the locations for this device allLocations.Add( location.Id ); // Get all the child locations also new LocationService( rockContext ) .GetAllDescendents( location.Id ) .Select( l => l.Id ) .ToList() .ForEach( l => allLocations.Add( l ) ); } // now, narrow it down to only locations that are active group locations for the configured group types foreach ( var groupLocation in new GroupLocationService( rockContext ).GetActiveByLocations( allLocations ) ) { if ( configuredGroupTypes.Contains( groupLocation.Group.GroupTypeId ) ) { if ( !result.Any( a => a.Id == groupLocation.LocationId ) ) { result.Add( groupLocation.Location ); } } } return result; }
/// <summary> /// Attempts to match a known kiosk based on the IP address of the client. /// </summary> private void AttemptKioskMatchByIpOrName() { // try to find matching kiosk by REMOTE_ADDR (ip/name). var checkInDeviceTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.DEVICE_TYPE_CHECKIN_KIOSK ).Id; using ( var rockContext = new RockContext() ) { bool enableReverseLookup = GetAttributeValue( "EnableReverseLookup" ).AsBoolean( false ); var device = new DeviceService( rockContext ).GetByIPAddress( Rock.Web.UI.RockPage.GetClientIpAddress(), checkInDeviceTypeId, !enableReverseLookup ); if ( device != null ) { ClearMobileCookie(); CurrentKioskId = device.Id; CurrentGroupTypeIds = GetAllKiosksGroupTypes( device, rockContext ); ; if ( !CurrentCheckinTypeId.HasValue ) { foreach ( int groupTypeId in CurrentGroupTypeIds ) { var checkinType = GetCheckinType( groupTypeId ); if ( checkinType != null ) { CurrentCheckinTypeId = checkinType.Id; break; } } } CurrentCheckInState = null; CurrentWorkflow = null; SaveState(); NavigateToNextPage(); } } }
/// <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 = int.Parse( hfDeviceId.Value ); 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; 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.SaveChanges(); Rock.CheckIn.KioskDevice.Flush( Device.Id ); NavigateToParentPage(); } }
/// <summary> /// Handles the Delete event of the gDevice control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gDevice_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); DeviceService DeviceService = new DeviceService( rockContext ); Device Device = DeviceService.Get( e.RowKeyId ); if ( Device != null ) { int deviceId = Device.Id; string errorMessage; if ( !DeviceService.CanDelete( Device, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } DeviceService.Delete( Device ); rockContext.SaveChanges(); Rock.CheckIn.KioskDevice.Flush( deviceId ); } BindGrid(); }
/// <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(); string orgLocGuid = GlobalAttributesCache.Read().GetValue( "OrganizationAddress" ); if ( !string.IsNullOrWhiteSpace( orgLocGuid ) ) { Guid locGuid = Guid.Empty; if ( Guid.TryParse( orgLocGuid, out locGuid ) ) { var location = new LocationService( rockContext ).Get( locGuid ); if ( location != null ) { geopPoint.CenterPoint = location.GeoPoint; geopFence.CenterPoint = location.GeoPoint; } } } 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; // 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; }
/// <summary> /// Handles the Delete event of the gDevice control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gDevice_Delete( object sender, RowEventArgs e ) { RockTransactionScope.WrapTransaction( () => { DeviceService DeviceService = new DeviceService(); Device Device = DeviceService.Get( (int)e.RowKeyValue ); if ( Device != null ) { string errorMessage; if ( !DeviceService.CanDelete( Device, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } DeviceService.Delete( Device, CurrentPersonId ); DeviceService.Save( Device, CurrentPersonId ); } } ); BindGrid(); }