public void SetLocationTest()
        {
            Setup();

            // Set up a device
            PairableDevice device = new PairableDevice
            {
                Identifier = "myPad",
                Location   = new Point(1, 1)
            };

            Server.Locator.Devices.Add(device);

            Server.Start();
            Client.Start();
            WaitForConnections();

            // Build a request to set the device's orientation
            IARequest request = new IARequest(Routes.SetOrientationRoute);

            request.Parameters["identifier"] = "myPad";
            Point newLocation = new Point(2, 2);

            request.SetBodyWith(new IntermediatePoint(newLocation));

            // Send the request, and test
            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception exception)
            {
                Assert.AreEqual(newLocation, device.Location.Value);
            });

            Teardown();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

             if (Session["IARequestID"] != null)
             {
            m_oIARequest = DataAccess.IARequests.SingleOrDefault(row => row.IARequestID == (int) Session["IARequestID"]);
             }
             else
             {
            Response.Redirect("~/user-dashboard.aspx");
             }

             if (Session["errorMessage"] != null && !string.IsNullOrEmpty(Session["errorMessage"].ToString()))
             {
            m_divMessageNegative.Visible = true;
            m_litError.Text = string.Format("Issue: There was a {0}", Session["errorMessage"].ToString());
             }
             else
             {
            m_divMessagePositive.Visible = true;
             }

             if (m_oIARequest.IACustomerCreditCardID > 0)
             {
            paymentPreAuthorized.Visible = true;
             }
             else if (IARequest.IARequestStatusID == ApplicationContext.GetRequestStatusID(RequestStatus.NeedsEstimate))
             {
            estimateMessage.Visible = true;
             }
        }
Ejemplo n.º 3
0
        private void FindDeviceWidthAndHeight(IADevice iaDevice)
        {
            //Does the device contain and width and height route
            if (iaDevice.SupportedRoutes.Contains(Routes.GetWidthAndHeightRoute))
            {
                IARequest request = new IARequest(Routes.GetWidthAndHeightRoute);
                IntAirAct.SendRequest(request, iaDevice, delegate(IAResponse response, Exception error)
                {
                    if (response == null || response.StatusCode == 404)
                    {
                        logger.TraceEvent(TraceEventType.Error, 100, "All devices should provide a width and height");
                    }
                    else if (response.StatusCode == 200)
                    {
                        Dictionary <String, double> dictionary = response.BodyAs <Dictionary <String, double> >();

                        Device localDevice = locator.Devices.Find(d => d.Identifier.Equals(iaDevice.Name));

                        //Device still exists, set width and height for device
                        if (localDevice != null)
                        {
                            localDevice.Height = dictionary["height"];
                            localDevice.Width  = dictionary["width"];
                        }
                        //Otherwise, device has disappeared, no action required
                        else
                        {
                        }
                    }
                });
            }
        }
Ejemplo n.º 4
0
        void GetDevicesInView(IARequest request, IAResponse response)
        {
            String deviceIdentifier = request.Parameters["identifier"];

            // Find the associated device in the Current Devices
            Device observer = locator.Devices.Find(d => d.Identifier.Equals(deviceIdentifier));

            if (observer == null)
            {
                response.StatusCode = 404;
                return;
            }

            // Get the devices in view, and convert them for serialization
            List <Device>             devicesInView = locator.GetDevicesInView(observer);
            List <IntermediateDevice> intDevices    = PairableDevice.GetCompleteIntermediateDevicesList(devicesInView);

            if (intDevices.Count == 0)
            {
                response.StatusCode = 404;
                return;
            }

            response.SetBodyWith(intDevices);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Handle a request for information about a device
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        void GetDevice(IARequest request, IAResponse response)
        {
            String deviceIdentifier = request.Parameters["identifier"];

            // Find the associated device in the Current Devices
            Device device = locator.Devices.Find(d => d.Identifier.Equals(deviceIdentifier));

            if (device == null)
            {
                response.StatusCode = 404;
                return;
            }

            // Get the intermediateDevice for serialization
            IntermediateDevice intermediateDevice = PairableDevice.GetCompleteIntermediateDevice(device);

            if (intermediateDevice == null)
            {
                //TODO: Should this status code be different, to reflect that the device exists but couldn't be returned due to incompleteness?
                response.StatusCode = 404;
                return;
            }

            // Respond with the device
            response.SetBodyWith(intermediateDevice);
        }
Ejemplo n.º 6
0
        void GetNearestDeviceInView(IARequest request, IAResponse response)
        {
            String deviceIdentifier = request.Parameters["identifier"];

            // Find the associated device in the Current Devices
            Device observer = locator.Devices.Find(d => d.Identifier.Equals(deviceIdentifier));

            if (observer == null)
            {
                //TODO: Should we use distinct status codes for distinct failure types here?
                response.StatusCode = 404;
                return;
            }

            // Find the nearest device that we observe
            Device nearestDevice = locator.GetNearestDeviceInView(observer);

            if (nearestDevice == null)
            {
                response.StatusCode = 404;
                return;
            }

            // Prepare the device for serialization
            IntermediateDevice intermediateDevice = PairableDevice.GetCompleteIntermediateDevice(nearestDevice);

            if (intermediateDevice == null)
            {
                response.StatusCode = 404;
                return;
            }

            response.SetBodyWith(intermediateDevice);
        }
Ejemplo n.º 7
0
        void GetNearestDeviceInRange(IARequest request, IAResponse response)
        {
            String deviceIdentifier = request.Parameters["identifier"];
            double range            = Double.Parse(request.Parameters["range"]);

            // Find the associated device in the Current Devices
            Device observer = locator.Devices.Find(d => d.Identifier.Equals(deviceIdentifier));

            if (observer == null)
            {
                response.StatusCode = 404;
                return;
            }

            Device nearestDevice = locator.GetNearestDeviceWithinRange(observer, range);

            if (nearestDevice == null)
            {
                response.StatusCode = 404;
                return;
            }

            IntermediateDevice intermediateDevice = PairableDevice.GetCompleteIntermediateDevice(nearestDevice);

            if (intermediateDevice == null)
            {
                response.StatusCode = 404;
                return;
            }

            // Respond with the device
            response.SetBodyWith(intermediateDevice);
        }
Ejemplo n.º 8
0
        void GetDevicesInRange(IARequest request, IAResponse response)
        {
            String deviceIdentifier = request.Parameters["identifier"];
            double range            = Double.Parse(request.Parameters["range"]);

            // Find the associated device in the Current Devices
            Device device = locator.Devices.Find(d => d.Identifier.Equals(deviceIdentifier));

            if (device == null)
            {
                response.StatusCode = 404;
                return;
            }

            List <Device>             devicesInView       = locator.GetDevicesWithinRange(device, range);
            List <IntermediateDevice> intermediateDevices = PairableDevice.GetCompleteIntermediateDevicesList(devicesInView);

            if (intermediateDevices.Count == 0)
            {
                response.StatusCode = 404;
                return;
            }

            // Respond with the device
            response.SetBodyWith(intermediateDevices);
        }
Ejemplo n.º 9
0
        void GetOffsetAngle(IARequest request, IAResponse response)
        {
            // Find the device
            String deviceIdentifier = request.Parameters["identifier"];
            Device requestingDevice = locator.Devices.Find(d => d.Identifier == deviceIdentifier);

            // Device Does Not Exist
            if (requestingDevice == null)
            {
                response.StatusCode = 404; // not found
                return;
            }

            if (requestingDevice.Location.HasValue && locator.Trackers[0].Location.HasValue)
            {
                Point requestingDeviceLocation = requestingDevice.Location.Value;
                Point offsetLocation           = locator.Trackers[0].Location.Value;

                double angle = Util.AngleBetweenPoints(requestingDeviceLocation, offsetLocation);
                response.SetBodyWith(angle);

                //response.SetBodyWith(90);
            }
            else
            {
                // Device doesn't have location
                response.StatusCode = 400;
            }
        }
        public void SetOrientationTest()
        {
            Setup();

            // Set up a device
            PairableDevice device = new PairableDevice
            {
                Identifier  = "myPad",
                Orientation = 20.0
            };

            Server.Locator.Devices.Add(device);

            Server.Start();
            Client.Start();
            WaitForConnections();

            // Build a request to set the device's orientation
            IARequest request = new IARequest(Routes.SetOrientationRoute);

            request.Parameters["identifier"] = "myPad";
            double newOrientation = 240.0;

            request.SetBodyWithString(newOrientation.ToString());

            // Send the request, and test
            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception exception)
            {
                Assert.AreEqual(240.0, device.Orientation.Value, 0.01);
            });


            Teardown();
        }
        public void GetDeviceInfoTest()
        {
            Setup();

            PairableDevice deviceOne = new PairableDevice
            {
                Location    = new Point(1, 0),
                Orientation = 90,
                Identifier  = "deviceOne",
            };

            PairableDevice deviceTwo = new PairableDevice
            {
                Location   = new Point(-1, 0),
                Identifier = "deviceTwo",
            };

            Server.Locator.Devices.Add(deviceOne);
            Server.Locator.Devices.Add(deviceTwo);


            Server.Start();
            Client.Start();
            WaitForConnections();

            // Successful get device info test
            IARequest request = new IARequest(Routes.GetDeviceInfoRoute);

            request.Parameters["identifier"] = deviceOne.Identifier;

            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception e)
            {
                IntermediateDevice id = response.BodyAs <IntermediateDevice>();

                Assert.AreEqual("deviceOne", id.identifier);
                Assert.AreEqual(new Point(1, 0), id.location.Value);
                Assert.AreEqual(90.0, id.orientation.Value, 0.01);

                doneWaitingForResponse = true;
            });

            WaitForResponse();
            doneWaitingForResponse = false;

            // Unsuccessful get device info test
            // Device two is incomplete, missing orientation, the correct server behaviour is to return http status 404
            request = new IARequest(Routes.GetDeviceInfoRoute);
            request.Parameters["identifier"] = deviceTwo.Identifier;

            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception e)
            {
                Assert.AreEqual(404, response.StatusCode);
                doneWaitingForResponse = true;
            });

            WaitForResponse();

            Teardown();
        }
        public void AllDevicesInViewTest()
        {
            Setup();
            PairableDevice observer = new PairableDevice
            {
                Location    = new Point(0, 0),
                Orientation = 225,
                Identifier  = "observer",
            };

            PairableDevice nearest = new PairableDevice
            {
                Location    = new Point(-1, -1),
                Identifier  = "nearest",
                Orientation = 20,
            };

            PairableDevice furthest = new PairableDevice
            {
                Location    = new Point(-2, -2),
                Identifier  = "furthest",
                Orientation = 20,
            };

            Server.Locator.Devices.Add(observer);
            Server.Locator.Devices.Add(furthest);
            Server.Locator.Devices.Add(nearest);

            Server.Start();
            Client.Start();
            WaitForConnections();

            IARequest request = new IARequest(Routes.GetAllDevicesInViewRoute);

            request.Parameters["identifier"] = observer.Identifier;

            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception e)
            {
                List <IntermediateDevice> intDevices = response.BodyAs <IntermediateDevice>();

                IntermediateDevice intDevice = intDevices.Find(x => x.identifier == nearest.Identifier);
                Assert.AreEqual(nearest.Location, intDevice.location);
                Assert.AreEqual(nearest.Orientation, intDevice.orientation);

                intDevice = intDevices.Find(x => x.identifier == furthest.Identifier);
                Assert.AreEqual(furthest.Location, intDevice.location);
                Assert.AreEqual(furthest.Orientation, intDevice.orientation);

                doneWaitingForResponse = true;
            });

            WaitForResponse();
            Teardown();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Return All Devices known to the Locator
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        void GetDevices(IARequest request, IAResponse response)
        {
            List <IntermediateDevice> intermediateDevices = PairableDevice.GetCompleteIntermediateDevicesList(locator.Devices);

            if (intermediateDevices.Count == 0)
            {
                response.StatusCode = 404;
            }
            else
            {
                response.SetBodyWith(intermediateDevices);
            }
        }
        public void NearestDeviceInRangeTest()
        {
            Setup();

            PairableDevice observer = new PairableDevice
            {
                Location    = new Point(10, 10),
                Orientation = 0,
                Identifier  = "observer",
            };

            PairableDevice nearest = new PairableDevice
            {
                Location    = new Point(0, 5),
                Identifier  = "nearest",
                Orientation = 0,
            };

            PairableDevice furthest = new PairableDevice
            {
                Location    = new Point(-5, 0),
                Identifier  = "furthest",
                Orientation = 0,
            };

            Server.Locator.Devices.Add(observer);
            Server.Locator.Devices.Add(furthest);
            Server.Locator.Devices.Add(nearest);

            Server.Start();
            Client.Start();
            WaitForConnections();

            IARequest request = new IARequest(Routes.GetNearestDeviceInRangeRoute);

            request.Parameters["identifier"] = observer.Identifier;
            request.Parameters["range"]      = "100.0";

            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception e)
            {
                IntermediateDevice intDevice = response.BodyAs <IntermediateDevice>();
                Assert.AreEqual(nearest.Identifier, intDevice.identifier);
                Assert.AreEqual(nearest.Location, intDevice.location);
                Assert.AreEqual(nearest.Orientation, intDevice.orientation);

                doneWaitingForResponse = true;
            });

            WaitForResponse();
            Teardown();
        }
        public void GetAllDeviceInfoTest()
        {
            Setup();

            PairableDevice deviceOne = new PairableDevice
            {
                Location    = new Point(1, 0),
                Orientation = 90,
                Identifier  = "deviceOne",
            };

            PairableDevice deviceTwo = new PairableDevice
            {
                Location    = new Point(-1, 0),
                Identifier  = "deviceTwo",
                Orientation = 20,
            };

            Server.Locator.Devices.Add(deviceOne);
            Server.Locator.Devices.Add(deviceTwo);

            Server.Start();
            Client.Start();
            WaitForConnections();

            IARequest request = new IARequest(Routes.GetAllDeviceInfoRoute);

            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception e)
            {
                List <IntermediateDevice> ids = response.BodyAs <IntermediateDevice>();


                IntermediateDevice intDevice = ids.Find(x => x.identifier.Equals("deviceOne"));
                Assert.AreEqual(deviceOne.Location, intDevice.location);
                Assert.AreEqual(deviceOne.Orientation, intDevice.orientation.Value);
                intDevice = ids.Find(x => x.identifier.Equals("deviceTwo"));
                Assert.AreEqual(deviceTwo.Location, intDevice.location);
                Assert.AreEqual(deviceTwo.Orientation, intDevice.orientation.Value);


                doneWaitingForResponse = true;
            });

            WaitForResponse();

            Teardown();
        }
Ejemplo n.º 16
0
        public void DeviceFound(IADevice iaDevice, bool ownDevice)
        {
            PairableDevice pairableDevice = new PairableDevice
            {
                Identifier   = iaDevice.Name,
                PairingState = PairingState.NotPaired
            };

            FindDeviceWidthAndHeight(iaDevice);


            if (iaDevice.SupportedRoutes.Contains(Routes.GetLocationRoute))
            {
                IARequest request = new IARequest(Routes.GetLocationRoute);
                IntAirAct.SendRequest(request, iaDevice, delegate(IAResponse response, Exception error)
                {
                    if (response == null || response.StatusCode == 404)
                    {
                        // Device has no location
                    }
                    else if (response.StatusCode == 200)
                    {
                        IntermediatePoint intermediatePoint = response.BodyAs <IntermediatePoint>();
                        Point result = intermediatePoint.ToPoint();

                        Device localDevice = locator.Devices.Find(d => d.Identifier.Equals(iaDevice.Name));

                        if (localDevice != null)
                        {
                            localDevice.Location = result;
                            response.StatusCode  = 201; // created
                        }
                        else
                        {
                            response.StatusCode = 404; // not found
                        }
                    }
                });
            }

            locator.Devices.Add(pairableDevice);

            if (DeviceAdded != null)
            {
                DeviceAdded(this, pairableDevice);
            }
        }
        public void GetOffsetAngleTest()
        {
            Setup();

            // Create a person and device, paired and positioned
            PairablePerson person = new PairablePerson
            {
                PairingState         = PairingState.Paired,
                Identifier           = "Bob",
                Location             = new Point(1, 1),
                HeldDeviceIdentifier = "myPad"
            };

            PairableDevice device = new PairableDevice
            {
                HeldByPersonIdentifier = "Bob",
                Identifier             = "myPad",
                Location     = new Point(1, 1),
                PairingState = PairingState.Paired
            };

            // Position the tracker
            //Server.PersonManager.Tracker.Location = new Point(0, 2);
            //Server.PersonManager.Tracker.Orientation = 270;
            Server.Locator.Devices.Add(device);
            Server.Locator.Persons.Add(person);

            Server.Start();
            Client.Start();
            WaitForConnections();

            IARequest request = new IARequest(Routes.GetOffsetAngleRoute);

            request.Parameters["identifier"] = "myPad";

            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception exception)
            {
                double offsetOrientation = double.Parse(response.BodyAsString());
                // The angle between the device and the tracker should be 135 degrees
                Assert.AreEqual(135, offsetOrientation, 0.01);
            });


            Teardown();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Handle a request with updated location for a device.
        /// </summary>
        /// <param name="request">IntAirAct Request</param>
        /// <param name="response">IntAirAct Response</param>
        public void UpdateDeviceLocation(IARequest request, IAResponse response)
        {
            IntermediatePoint intermediatePoint = request.BodyAs <IntermediatePoint>();
            Point             result            = intermediatePoint.ToPoint();

            String name        = request.Parameters["identifier"];
            Device localDevice = locator.Devices.Find(d => d.Identifier.Equals(name));

            if (localDevice != null)
            {
                localDevice.Location = result;
                response.StatusCode  = 201; // created
            }
            else
            {
                response.StatusCode = 404; // not found
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Handle a request with updated information for a device.
        /// Presently, only used to update device location
        /// </summary>
        /// <param name="request">IntAirAct Request</param>
        /// <param name="response">IntAirAct Response</param>
        void UpdateDeviceOrientation(IARequest request, IAResponse response)
        {
            string result = request.BodyAsString();
            //TODO: Handle parse failure gracefully
            float newOrientation = float.Parse(result);

            String name        = request.Parameters["identifier"];
            Device localDevice = locator.Devices.Find(d => d.Identifier.Equals(name));

            if (localDevice != null)
            {
                localDevice.Orientation = newOrientation;
                response.StatusCode     = 201; // created
            }
            else
            {
                response.StatusCode = 404; // not found
            }
        }
Ejemplo n.º 20
0
        public void UnpairDevice(PairableDevice pairingDevice)
        {
            if (pairingDevice.PairingState != PairingState.NotPaired)
            {
                List <PairablePerson> pPersons      = locator.Persons.OfType <PairablePerson>().ToList <PairablePerson>();
                PairablePerson        pairingPerson = pPersons.Find(p => p.HeldDeviceIdentifier == pairingDevice.Identifier);

                pairingDevice.HeldByPersonIdentifier = null;
                pairingDevice.PairingState           = PairingState.NotPaired;

                pairingPerson.PairingState         = PairingState.NotPaired;
                pairingPerson.HeldDeviceIdentifier = null;

                // Dispatch a message to the device
                IARequest request = new IARequest(Routes.BecomeUnpairedRoute);
                // Find the IntAirAct device matching the current device.
                IADevice iaDevice = intAirAct.Devices.Find(d => d.Name == pairingDevice.Identifier);
                intAirAct.SendRequest(request, iaDevice);
                System.Diagnostics.Debug.WriteLine(iaDevice.Name + " " + iaDevice.Host);
            }
        }
Ejemplo n.º 21
0
        public void Pair(PairableDevice pairingDevice, PairablePerson pairingPerson)
        {
            //Change the Pairing State
            pairingDevice.PairingState = PairingState.Paired;
            pairingPerson.PairingState = PairingState.Paired;

            //Create a Holds-Device and Held-By-Person Relationship
            pairingPerson.HeldDeviceIdentifier   = pairingDevice.Identifier;
            pairingDevice.HeldByPersonIdentifier = pairingPerson.Identifier;

            List <IADevice> devices = intAirAct.Devices;
            IADevice        device  = devices.Find(d => d.Name == pairingDevice.Identifier);

            if (device != null)
            {
                IARequest request = new IARequest(Routes.BecomePairedRoute);
                intAirAct.SendRequest(request, device, delegate(IAResponse response, Exception exception)
                {
                    logger.TraceEvent(TraceEventType.Information, 0, "Error notifying Device {0} that it became paired.", pairingDevice.Identifier, pairingPerson.Identifier);
                });
            }

            logger.TraceEvent(TraceEventType.Information, 0, "Pairing Succeeded with Device {0} and Person {1}", pairingDevice.Identifier, pairingPerson.Identifier);
        }
Ejemplo n.º 22
0
 void UpdateDevicePairingState(IARequest request, IAResponse response)
 {
     Console.WriteLine(request.Parameters["identifier"]);
     pairingRecognizer.DevicePairAttempt(request.Parameters["identifier"]);
 }
Ejemplo n.º 23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (RequestId > 0)
             {
            _workRequest = DataAccess.IARequests.SingleOrDefault(row => row.IARequestID == RequestId);
             }

             if (_workRequest != null)
             {
            // Validate the request can be viewed by the current user
            if (!ApplicationContext.CanCurrentUserViewOrder(_workRequest))
            {
               Response.Redirect("~/Default.aspx");
            }

            if (!_workRequest.IsLocked)
            {
               var clickSource = "m";
               if (Request.QueryString["s"] != null && Request.QueryString["s"].ToLower() == "a")
               {
                  clickSource = "a";
               }
               var redirectURL = string.Format("~/edit-request.aspx?s={0}&id={1}", clickSource, _workRequest.IARequestID);
               Response.Redirect(redirectURL);
            }

            if (string.Compare(PaymentSourceCombo.SelectedValue, TransientCardEntryKey, true) == 0)
               _transientCardEntry = true;

            if (!IsPostBack)
            {
               Page.Title = string.Format("Speedy Spots :: Request Details :: Request #{0}", IARequest.RequestIdForDisplay);
               SetBreadCrumb();

               m_divButtons.Visible = false;
               m_btnCancel.Visible = false;
               m_btnCancelRequest.Visible = false;
               if (ApplicationContext.CanRequestBeCanceled(_workRequest))
               {
                  m_divButtons.Visible = true;
                  m_btnCancel.Visible = true;
                  m_btnCancelRequest.Visible = true;
               }

               m_oRepeaterProduction.ItemCreated += OnRepeaterProductionItemCreated;
               m_oRepeaterProduction.DataSource = _workRequest.IARequestProductions;
               m_oRepeaterProduction.DataBind();

               m_btnPayment.Visible = false;
               m_btnApproveEstimate.Visible = false;

               if (IARequestEstimate != null)
               {
                  if (IARequestEstimate.IsPaymentRequired && !IARequestEstimate.IsApproved)
                  {
                     m_divPayment.Visible = true;
                     m_btnPayment.Visible = true;

                     if (IARequest.IAJobs.Any())
                     {
                        m_btnCancel.Visible = false;
                        m_btnCancelRequest.Visible = false;
                     }

                     LoadPaymentSources();

                     m_txtEmailReceipt.Text = MemberProtect.Organization.GetDataItem(ApplicationContext.GetOrgID(), "EmailInvoice");

                     ApplicationContext.LoadCreditCardTypes(ref m_cboCreditCardType);
                     ApplicationContext.LoadCreditCardExpirationMonths(ref m_cboCreditCardExpireMonth);
                     ApplicationContext.LoadCreditCardExpirationYears(ref m_cboCreditCardExpireYear);
                  }
                  else
                  {
                     m_divPayment.Visible = false;
                     m_btnPayment.Visible = false;

                     if (!IARequestEstimate.IsApproved)
                     {
                        m_btnApproveEstimate.Visible = true;
                     }
                  }
               }
               else
               {
                  m_divPayment.Visible = false;
               }

               if (!m_btnApproveEstimate.Visible && !m_btnCancelRequest.Visible && !m_btnPayment.Visible)
               {
                  m_divLowerButtons.Visible = false;
               }

               if (DataAccess.fn_Customer_GetInvoices(IARequest.IARequestID).Any())
               {
                  m_repeaterInvoices.DataSource = DataAccess.fn_Customer_GetInvoices(IARequest.IARequestID);
                  m_repeaterInvoices.DataBind();
               }
               else
               {
                  m_divInvoices.Visible = false;
               }
            }
             }
             else
             {
            Response.Redirect("~/Default.aspx");
             }
        }
Ejemplo n.º 24
0
        protected void OnSubmit(object sender, EventArgs e)
        {
            // Validation
             if (m_radContactPhone.SelectedValue == "other")
             {
            if (m_txtContactPhone.Text == string.Empty)
            {
               SetMessage("Please select or enter a contact phone number for this request.", MessageTone.Negative);
               return;
            }
             }

             if (ApplicationContext.IsStaff)
             {
            if (string.IsNullOrEmpty(Request.Form["ffb2"]))
            {
               SetMessage("Please select the customer you are submitting a request on behalf of.", MessageTone.Negative);
               return;
            }
             }

             var currentUserId = MemberProtect.CurrentUser.UserID;
             if (ApplicationContext.IsStaff)
             {
            // Grab the customer ID for whom the producer is requesting on behalf of
            currentUserId = MemberProtect.Utility.ValidateGuid(Request.Form["ffb2"]);
            if (currentUserId == Guid.Empty)
            {
               SetMessage("Please select a valid customer.", MessageTone.Negative);
               return;
            }
             }

             if (!Page.IsValid) return;

             m_txtNotificationEmails.Text = ApplicationContext.CleanAddressList(m_txtNotificationEmails.Text);
             MemberProtect.User.SetDataItem(currentUserId, "NotificationEmails", m_txtNotificationEmails.Text);

             var iaRequest = new IARequest
             {
            MPUserID = currentUserId,
            PageLoadDateTime = DateTime.Parse(m_hdnPageLoadTime.Value),
            MPUserIDOwnedByStaff = Guid.Empty,
            MPUserIDLockedByStaff = Guid.Empty
             };

             switch (m_radContactPhone.SelectedValue)
             {
            case "user":
               iaRequest.ContactPhone = MemberProtect.User.GetDataItem(currentUserId, "Phone");
               iaRequest.ContactPhoneExtension = MemberProtect.User.GetDataItem(currentUserId, "PhoneExtension");
               break;
            case "userMobile":
               iaRequest.ContactPhone = MemberProtect.User.GetDataItem(currentUserId, "MobilePhone");
               iaRequest.ContactPhoneExtension = string.Empty;
               break;
            case "other":
               iaRequest.ContactPhone = m_txtContactPhone.Text.Trim();
               iaRequest.ContactPhoneExtension = m_txtContactPhoneExtension.Text.Trim();
               break;
             }

             iaRequest.NotificationEmails = m_txtNotificationEmails.Text.Trim();
             iaRequest.IsRushOrder = m_radSameDay.Checked;
             iaRequest.IsLocked = true;
             iaRequest.HasBeenViewedByProducer = false;
             iaRequest.EstimateRequested = "No";
             iaRequest.CreatedDateTime = DateTime.Now;

             iaRequest.ProductionNotes = string.Empty;
             iaRequest.Script = string.Empty;

             var sEstimateNote = string.Empty;
             if (m_radBeginProduction.SelectedValue == "estimate" || !m_radBeginProduction.Visible)
             {
            iaRequest.IARequestStatusID = ApplicationContext.GetRequestStatusID(RequestStatus.NeedsEstimate);

            if (!m_radBeginProduction.Visible)
            {
               iaRequest.EstimateRequested = "Auto";
               sEstimateNote = "Auto requested estimate";
            }
            else
            {
               iaRequest.EstimateRequested = "Customer";
               sEstimateNote = "Requested estimate";
            }
             }
             else
             {
            iaRequest.IARequestStatusID = ApplicationContext.GetRequestStatusID(RequestStatus.Submitted);
            iaRequest.EstimateRequested = "No";
             }

             if (PaymentPreApprovalEstimateButton.Checked)
             {
            var id = MemberProtect.Utility.ValidateInteger(PaymentSourceCombo.SelectedValue);
            if (id > 0)
            {
               iaRequest.IACustomerCreditCardID = id;
               sEstimateNote = "Pre-authorized Payment";
            }
             }

             DataAccess.IARequests.InsertOnSubmit(iaRequest);
             DataAccess.SubmitChanges();

             var hadError = false;
             var errorMessage = string.Empty;
             // Add in the production notes
             try
             {
            iaRequest.ProductionNotes = Regex.Replace(ProductionNotes, @"[^\u0000-\u007F]", "");
            DataAccess.SubmitChanges();
             }
             catch (Exception ex)
             {
            ErrorSignal.FromCurrentContext().Raise(ex);
            hadError = true;
            errorMessage = "problem saving production notes";
             }

             // Add in the script
             try
             {
            // what is this?
            iaRequest.Script = Regex.Replace(Script, @"[^\u0000-\u007F]", "");
            DataAccess.SubmitChanges();
             }
             catch (Exception ex)
             {
            ErrorSignal.FromCurrentContext().Raise(ex);
            errorMessage = (hadError) ? "problem saving production notes and script" : "problem saving script";
            hadError = true;
             }

             if (sEstimateNote != string.Empty)
             {
            iaRequest.CreateNote(MemberProtect.CurrentUser.UserID, sEstimateNote);
             }
             DataAccess.SubmitChanges();

             if (ApplicationContext.IsStaff)
             {
            iaRequest.CreateNote(MemberProtect.CurrentUser.UserID, "Request created on behalf of the customer");
            DataAccess.SubmitChanges();
             }

             try
             {
            ProcessUploadedFiles(iaRequest.IARequestID);
             }
             catch (Exception ex)
             {
            ErrorSignal.FromCurrentContext().Raise(ex);
            errorMessage = (hadError) ? errorMessage + " and uploading files" : "problem uploading files.";
             }

             Session["IARequestID"] = iaRequest.IARequestID;
             Session["errorMessage"] = errorMessage;
             Response.Redirect("~/create-request-confirm.aspx");
        }
Ejemplo n.º 25
0
        public CreditCardServiceResponse PayEstimate(CreditCardViewModel cardProfile, Func<string, string> urlBuilder, IARequest request, IARequestEstimate estimate)
        {
            var response = new CreditCardServiceResponse {SuccessfulCharge = true};

             var transaction = new AuthorizeNETTransactionInformation(cardProfile.CreditCardNumber, estimate.Charge, cardProfile.ExpirationDate)
             {
            FirstName = cardProfile.FirstName,
            LastName = cardProfile.LastName,
            CreditCardCode = cardProfile.CardVerificationCode,
            Email = cardProfile.ReceiptEmailAddressCsv,
            InvoiceNumber = string.Format("Est-{0}", request.RequestIdForDisplay),
            Description = "Request Estimate",
            Company = cardProfile.CompanyName.PadRight(50).Substring(0, 50).Trim(),
            Zip = ""
             };

             var paymentGatewayResponse = new PaymentGatewayResponse(string.Empty);

             if (cardProfile.CreditCardId == 0)
             {
            var authorizeNetDirect = new AuthorizeNET(_enableDebug, _loginId, _transactionKey);

            if (!authorizeNetDirect.ProcessAuthorizationAndCapture(transaction))
            {
               response.SuccessfulCharge = false;
               response.ErrorMessage = authorizeNetDirect.Error;
            }

            response.PaymentGatewayResponse = authorizeNetDirect.PaymentGatewayResponse;
             }
             else
             {
            // go through CIM to process transaction
            paymentGatewayResponse = CIMAuthorizationAndCapture(transaction,
                                                                cardProfile.CIMProfileId,
                                                                cardProfile.CIMPaymentProfileId);
            if (paymentGatewayResponse.Errors.Any() || paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseCode) != "1")
            {
               var message = paymentGatewayResponse.Errors.Any()
                                ? paymentGatewayResponse.Errors.Aggregate((messages, error) => messages + ", " + error)
                                : paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseReasonText);

               response.SuccessfulCharge = false;
               response.ErrorMessage = message;
            }
             }

             if (!response.SuccessfulCharge) return response;

             RecordOrder(cardProfile, paymentGatewayResponse, estimate);

             var requestStatusLookup = new RequestStatusLookup(_dataContext);
             request.IARequestStatusID = requestStatusLookup.GetRequestStatus(RequestStatus.Processing).IARequestStatusID;
             _dataContext.SubmitChanges();

             var approved = DateTime.Now;
             MarkEstimateAsPaid(request, estimate, approved);

             SendCustomerReceipt(cardProfile, request, estimate);

             InformBillingThatCustomerPaid(cardProfile, paymentGatewayResponse, urlBuilder, request, approved, estimate.Charge);

             return response;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Cancel buttons should be shown when:
        /// 1. (Request status is 'Submitted' OR 'Needs Estimate' OR 'WaitingEstimateApproval') AND there are no jobs on the request
        /// 
        /// Cancel button should NOT be shown when:
        /// 2. Has an Estimate that requires payment and there are already jobs on the request
        /// </summary>
        /// <param name="oIARequest"></param>
        /// <returns></returns>
        public bool CanRequestBeCanceled(IARequest oIARequest)
        {
            var bReturn = (oIARequest.IARequestStatusID == GetRequestStatusID(RequestStatus.Submitted) ||
                         oIARequest.IARequestStatusID == GetRequestStatusID(RequestStatus.NeedsEstimate) ||
                         oIARequest.IARequestStatusID == GetRequestStatusID(RequestStatus.WaitingEstimateApproval)) && oIARequest.IAJobs.Count == 0;

             // 1. (Request status is 'Submitted' OR 'Needs Estimate' OR 'WaitingEstimateApproval') AND there are no jobs on the request

             // 2. Has an Estimate that requires payment and there are already jobs on the request
             if (oIARequest.IARequestEstimates.Any())
             {
            if (oIARequest.IARequestEstimates[0].IsPaymentRequired && oIARequest.IAJobs.Any())
            {
               bReturn = false;
            }
             }

             return bReturn;
        }
Ejemplo n.º 27
0
 private void MarkEstimateAsPaid(IARequest request, IARequestEstimate estimate, DateTime approved)
 {
     estimate.IsApproved = true;
      estimate.ApprovedDateTime = approved;
      request.CreateNote(_customerMemberProtectUserId, estimate.PreAuthorizedPaymentCharged
                                                      ? string.Format("Estimate payment pre-approved and paid: {0:c}", estimate.Charge)
                                                      : string.Format("Estimate approved and paid: {0:c}", estimate.Charge));
      _dataContext.SubmitChanges();
 }
        public void SuccessfulPairingTest()
        {
            Setup();

            // We would like to be able to test the round trip communication, sending 'request pairing' on the client to the server, to sending
            // 'become paired' from server to client.
            // But internally, tinyIOC registers things by type, so only the first instance of intairact's server adapter gets retrieved.
            // All routes are handled by the same IAA instance, which is obviously a problem when we have two in the system that we would like to have talk to each other.

            // So, at present this part of the test cannot work
            //Client.Route(Routes.BecomePairedRoute, delegate(IARequest request, IAResponse response)
            //{
            //    doneWaitingForResponse = true;
            //});

            Server.Start();
            Client.Start();
            WaitForConnections();

            // Create a person on the server, who is attempting to pair their device
            // NB: Setting PairingAttempt on a Person begins a 3 second timer, after which their pairing state resets to NotPaired
            // The test should always complete before then, but if mysterious failures start appearing, it could be time related
            Server.Locator.Persons.Add(new PairablePerson()
            {
                Identifier   = "Bob",
                Location     = new System.Windows.Point(1, 1),
                PairingState = PairingState.PairingAttempt
            });

            // Notify the server that the client wants to be paired
            IARequest pairingRequest = new IARequest(Routes.RequestPairingRoute);

            pairingRequest.Origin = Client.OwnDevice;
            pairingRequest.Parameters["identifier"] = Client.OwnDevice.Name;
            Client.SendRequest(pairingRequest, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception exception)
            {
                if (exception != null)
                {
                    System.Diagnostics.Debug.WriteLine(exception.Message);
                    Assert.Fail();
                }

                // In response to the return of the request, we test some properties on the server

                // Find the mock pairable person we created, test their pairing state
                PairablePerson person = (PairablePerson)Server.Locator.Persons.Find(x => x.Identifier.Equals("Bob"));
                Assert.AreEqual(PairingState.Paired, person.PairingState);

                // Find the Client's IADevice on the server, test its pariing state
                PairableDevice device = (PairableDevice)Server.Locator.Devices.Find(x => x.Identifier.Equals(Client.OwnDevice.Name));
                Assert.AreEqual(PairingState.Paired, device.PairingState);

                // Test that the two were paired with each other
                Assert.AreEqual(person.HeldDeviceIdentifier, device.Identifier);
                Assert.AreEqual(device.HeldByPersonIdentifier, person.Identifier);

                doneWaitingForResponse = true;
            });

            WaitForResponse();
            Teardown();
        }
Ejemplo n.º 29
0
        public void RequestAssignStaff(IARequest oIARequest, Guid oMPUserID)
        {
            // Only update the staff owner if there is currently no owner
             if (oIARequest.MPUserIDOwnedByStaff == Guid.Empty)
             {
            oIARequest.MPUserIDOwnedByStaff = oMPUserID;

            oIARequest.CreateNote(oMPUserID, "Production Owner");
             }
        }
Ejemplo n.º 30
0
        private void SendCustomerReceipt(CreditCardViewModel cardProfile, IARequest request, IARequestEstimate estimate)
        {
            var thankYouEmail = new StringBuilder();
             thankYouEmail.AppendLine(string.Format("Thank you for making your estimate payment for request # {0} requested by {1} {2}.<br/>",
                                                request.RequestIdForDisplay, _memberProtect.User.GetDataItem(request.MPUserID, "FirstName"),
                                                _memberProtect.User.GetDataItem(request.MPUserID, "LastName")));
             thankYouEmail.AppendLine("<br/>");
             thankYouEmail.AppendLine("Payment Details<br/>");
             foreach (var job in request.IAJobs)
             {
            thankYouEmail.AppendLine(string.Format("Job: {0}<br />", job.Name));
             }
             thankYouEmail.AppendLine(string.Format("Amount: {0:c}<br/>", estimate.Charge));
             thankYouEmail.AppendLine(string.Format("When: {0:g}<br/>", DateTime.Now));
             thankYouEmail.AppendLine(string.Format("Card: {0} ending in {1}<br/>", cardProfile.CardType,
                                                _memberProtect.Utility.Right(cardProfile.CreditCardNumber, 4)));
             thankYouEmail.AppendLine("<br/>");
             thankYouEmail.AppendLine("Thank you,<br/>");
             thankYouEmail.AppendLine("<a href='http://www.speedyspots.com'>SpeedySpots.com</a><br/>");
             thankYouEmail.AppendLine("<a href='mailto:[email protected]'>[email protected]</a><br/>");
             thankYouEmail.AppendLine("(734) 475-9327<br/>");
             thankYouEmail.AppendLine("Customer Email: " + cardProfile.ReceiptEmailAddressCsv); //ADDED THIS LINE FOR EMAIL FIx

             var subject = string.Format("Estimate payment received for request {0}.", request.RequestIdForDisplay);
             EmailCommunicationService.EstimatePaymentCustomerReceiptSend(subject, thankYouEmail, cardProfile.ReceiptEmailAddressCsv);
        }
        public void AllDevicesWithinRangeTest()
        {
            Setup();

            PairableDevice observer = new PairableDevice
            {
                Location    = new Point(10, 10),
                Orientation = 0,
                Identifier  = "observer",
            };

            PairableDevice nearest = new PairableDevice
            {
                Location    = new Point(0, 5),
                Identifier  = "nearest",
                Orientation = 0,
            };

            PairableDevice furthest = new PairableDevice
            {
                Location    = new Point(-5, 0),
                Identifier  = "furthest",
                Orientation = 0,
            };

            PairableDevice tooFar = new PairableDevice
            {
                Location    = new Point(100, 100),
                Identifier  = "tooFar",
                Orientation = 50,
            };

            Server.Locator.Devices.Add(observer);
            Server.Locator.Devices.Add(furthest);
            Server.Locator.Devices.Add(nearest);
            Server.Locator.Devices.Add(tooFar);

            Server.Start();
            Client.Start();
            WaitForConnections();

            IARequest request = new IARequest(Routes.GetAllDevicesInRangeRoute);

            request.Parameters["identifier"] = observer.Identifier;
            request.Parameters["range"]      = "50.0";


            Client.SendRequest(request, Server.IntAirAct.OwnDevice, delegate(IAResponse response, Exception e)
            {
                List <IntermediateDevice> intDevices = response.BodyAs <IntermediateDevice>();

                IntermediateDevice intDevice = intDevices.Find(x => x.identifier == nearest.Identifier);
                Assert.AreEqual(nearest.Location, intDevice.location);
                Assert.AreEqual(nearest.Orientation, intDevice.orientation);

                intDevice = intDevices.Find(x => x.identifier == furthest.Identifier);
                Assert.AreEqual(furthest.Location, intDevice.location);
                Assert.AreEqual(furthest.Orientation, intDevice.orientation);

                // The 'tooFar' device should not be returned
                Assert.AreEqual(2, intDevices.Count);

                doneWaitingForResponse = true;
            });

            WaitForResponse();
            Teardown();
        }
Ejemplo n.º 32
0
        public bool CanCurrentUserViewOrder(IARequest m_oIARequest)
        {
            // Customer must be the originator of the request to view it
             if (IsCustomer && m_oIARequest.MPUserID == MemberProtect.CurrentUser.UserID)
             {
            return true;
             }
             if (IsCustomer && m_oIARequest.MPUserID != MemberProtect.CurrentUser.UserID)
             {
            // See if this is a request from an assigned coworker
            var query = from c in DataAccess.IACustomerCoworkers
                        where c.MPUserID == MemberProtect.CurrentUser.UserID && c.MPUserIDCoworker == m_oIARequest.MPUserID
                        select c;

            return (query.Any());
             }

             return false;
        }
Ejemplo n.º 33
0
        private void SetCurrentRequest()
        {
            var requestId = 0;

             if (Request.QueryString["rid"] != null)
             {
            requestId = MemberProtect.Utility.ValidateInteger(Request.QueryString["rid"].ToString());
             }

             if (requestId == 0 && Request.QueryString["jid"] != null)
             {
            var jobId = MemberProtect.Utility.ValidateInteger(Request.QueryString["jid"].ToString());
            var oIAJob = DataAccess.IAJobs.SingleOrDefault(row => row.IAJobID == jobId);
            if (oIAJob != null)
            {
               requestId = oIAJob.IARequestID;
            }
             }

             if (requestId <= 0 && Session["IARequestID"] != null)
             {
            requestId = int.Parse(Session["IARequestID"].ToString());
             }

             if (requestId > 0)
             {
            Session["IARequestID"] = requestId;
            currentRequest = DataAccess.IARequests.SingleOrDefault(row => row.IARequestID == requestId);
             }
             else
             {
            throw new ApplicationException("Request cannot be found.");
             }
        }
Ejemplo n.º 34
0
        private void InformBillingThatCustomerPaid(CreditCardViewModel paymentDetails, PaymentGatewayResponse paymentGatewayResponse,
                                                 Func<string, string> urlBuilder,
                                                 IARequest request, DateTime approved, decimal chargeAmount)
        {
            string subject;
             string customerType;

             var mpOrg = _dataContext.MPOrgUsers.FirstOrDefault(row => row.MPUserID == _customerMemberProtectUserId);
             var mpOrgId = mpOrg == null ? Guid.Empty : mpOrg.MPOrgID;

             if (_memberProtect.Utility.YesNoToBool(_memberProtect.Organization.GetDataItem(mpOrgId, "IsVerified")))
             {
            subject = "Estimate Payment made (verified)";
            customerType = "a verified";
             }
             else
             {
            subject = "Estimate Payment made (unverified)";
            customerType = "an unverified";
             }

             var paidEmail = new StringBuilder();
             paidEmail.AppendFormat("An estimate payment was made by {0} customer:<br/>", customerType);
             paidEmail.Append("<br/>");
             paidEmail.AppendFormat("Company: <a href='{0}?id={1}'>{2}</a><br/>", urlBuilder("company-modify.aspx"),
                                mpOrgId.ToString().Replace("-", string.Empty), _memberProtect.Organization.GetName(mpOrgId));
             paidEmail.AppendFormat("Customer: <a href='{0}?id={1}'>{2} {3}</a><br/>", urlBuilder("user-account.aspx"),
                                _customerMemberProtectUserId.ToString().Replace("-", string.Empty),
                                _memberProtect.User.GetDataItem(_customerMemberProtectUserId, "FirstName"),
                                _memberProtect.User.GetDataItem(_customerMemberProtectUserId, "LastName"));
             paidEmail.AppendFormat("Email Receipt: {0}<br/>", paymentDetails.ReceiptEmailAddressCsv);
             paidEmail.AppendFormat("Request: <a href='{0}?rid={1}'>{2}</a><br/>", urlBuilder("create-job.aspx"), request.IARequestID, request.RequestIdForDisplay);
             paidEmail.AppendFormat("Amount: {0:c}<br/>", chargeAmount);
             paidEmail.AppendFormat("Card: {0} ending in {1}<br/>", paymentDetails.CardType, _memberProtect.Utility.Right(paymentDetails.CreditCardNumber, 4));
             paidEmail.AppendFormat("Name on Card: {0} {1}<br/>", paymentDetails.FirstName, paymentDetails.LastName);
             paidEmail.AppendFormat("When: {0:g}<br/>", approved);
             paidEmail.AppendFormat("Authorize Receipt: {0}<br/>", paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.TransactionId));

             EmailCommunicationService.EstimatePaymentBillingNoticeSend(paidEmail, subject);
        }
Ejemplo n.º 35
0
        private void LoadRequest()
        {
            if (RequestId > 0)
             {
            _iaRequest = DataAccess.IARequests.SingleOrDefault(row => row.IARequestID == RequestId);
             }

             if (_iaRequest == null)
             {
            RedirectMessage("~/staff-dashboard.aspx", "Unable to find request.");
             }
        }
Ejemplo n.º 36
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // User must be a producer in order to visit this page
             if (!ApplicationContext.IsStaff)
             {
            Response.Redirect("~/Default.aspx");
             }

             m_oIARequest = DataAccess.IARequests.SingleOrDefault(row => row.IARequestID == RequestID);

             if (m_oIARequest == null)
             {
            Response.Redirect("~/staff-dashboard.aspx");
             }

             UpdateLabels();

             if (IsPostBack) return;

             SetBreadcrumbs();
             MarkRequestAsViewed();
             CheckRequestStatusAgainstJobs();

             m_grdList.PageSize = ApplicationContext.GetGridPageSize();

             ApplicationContext.LoadLanguages(ref m_cboLanguage);

             // Load status filter options
             m_cboLabels.DataSource = LabelsService.GetLabels();
             m_cboLabels.DataValueField = "IALabelID";
             m_cboLabels.DataTextField = "Text";
             m_cboLabels.DataBind();

             m_cboLabels.Text = "Apply Labels";

             ConfigureEstimateButton();

             // Auto-select any labels already associated with this request
             foreach (var chkLabel in from oRequestLabel in m_oIARequest.IARequestLabels
                                  select m_cboLabels.FindItemByValue(oRequestLabel.IALabelID.ToString(), true)
                                  into oItem
                                  where oItem != null
                                  select oItem.FindControl("m_chkLabel") as CheckBox)
             {
            chkLabel.Checked = true;
             }

             m_lblJob.Text = "Create Job:";
             m_btnUpdate.Visible = false;
             m_txtJobName.Focus();
        }
Ejemplo n.º 37
0
        protected override void OnDrop(DragEventArgs e)
        {
            string DataType = e.Data.GetFormats(true)[0];

            //if the object dropped is a tracker
            if (DataType == "trackerControl")
            {
                base.OnDrop(e);
                Point mouseLocation = e.GetPosition(sharedCanvas);

                // Grab the data we packed into the DataObject
                TrackerControl trackerControl = (TrackerControl)e.Data.GetData("trackerControl");

                // Hide the Ghost and Text since a Drop has been made
                MainWindow.GhostBorder.Visibility = System.Windows.Visibility.Hidden;
                ghostTextBlock.Visibility         = System.Windows.Visibility.Hidden;

                // Return the Opacity of the TrackerControl
                trackerControl.Opacity = 1;

                trackerControl.Tracker.Location = DrawingResources.ConvertFromDisplayCoordinatesToMeters(mouseLocation, sharedCanvas);


                // Check if the TrackerControl is already a child of Shared Canvas
                Point canvasBounds = new Point(DrawingResources.ConvertFromMetersToPixelsX(DrawingResources.ROOM_WIDTH, sharedCanvas), DrawingResources.ConvertFromMetersToPixelsY(DrawingResources.ROOM_HEIGHT, sharedCanvas));

                if (!trackerControl.IsDescendantOf(SharedCanvas))
                {
                    trackerControl.formatForCanvas();
                    kinectWrapPanel.Children.Remove(trackerControl);
                    SharedCanvas.Children.Add(trackerControl);

                    if (trackerControl.Tracker.Orientation == null)
                    {
                        trackerControl.Tracker.Orientation = 270;
                    }
                }

                // if the cursor is outside the canvas, put the tracker back in stackpanel.
                else if (!(mouseLocation.X < canvasBounds.X && mouseLocation.Y < canvasBounds.Y))
                {
                    trackerControl.Tracker.StopStreaming();
                    cleanUpKinectPersons(trackerControl.Tracker.Identifier);
                    trackerControl.formatForStackPanel();
                    SharedCanvas.Children.Remove(trackerControl);
                    kinectWrapPanel.Children.Add(trackerControl);
                }
            }

            //if the objet dropped is a device.
            else if (DataType == "deviceControl")
            {
                base.OnDrop(e);
                Point mouseLocation = e.GetPosition(sharedCanvas);

                // Grab the data we packed into the DataObject
                DeviceControl deviceControl = (DeviceControl)e.Data.GetData("deviceControl");

                // Hide the Ghost and Text since a Drop has been made
                MainWindow.GhostBorder.Visibility = System.Windows.Visibility.Hidden;
                ghostTextBlock.Visibility         = System.Windows.Visibility.Hidden;

                // Return the Opacity of the DeviceControl
                deviceControl.Opacity = 1;

                PairableDevice device   = deviceControl.PairableDevice;
                IADevice       iaDevice = deviceControl.IADevice;

                IARequest request = new IARequest(Routes.SetLocationRoute);
                request.Parameters["identifier"] = iaDevice.Name;

                Point canvasBounds = new Point(DrawingResources.ConvertFromMetersToPixelsX(DrawingResources.ROOM_WIDTH, sharedCanvas), DrawingResources.ConvertFromMetersToPixelsY(DrawingResources.ROOM_HEIGHT, sharedCanvas));

                //if the dragged device is a pairable device (i.e iPad)
                if (!iaDevice.SupportedRoutes.Contains(Routes.GetLocationRoute))
                {
                    Point mouseLocationOnCanvas = mouseLocation = DrawingResources.ConvertFromDisplayCoordinatesToMeters(mouseLocation, sharedCanvas);
                    bool  pairedToNewDevice     = false;

                    foreach (KeyValuePair <PairablePerson, PersonControl> keyPair in PersonControlDictionary)
                    {
                        Point  personLocation = keyPair.Key.Location.Value;
                        double distance       = Math.Sqrt(Math.Pow(mouseLocationOnCanvas.X - personLocation.X, 2) + Math.Pow(mouseLocationOnCanvas.Y - personLocation.Y, 2));

                        //if the mouse drop is close to a person, pair the device with that person.
                        if (distance < 0.3 && (device.HeldByPersonIdentifier == keyPair.Key.Identifier || keyPair.Key.PairingState != PairingState.Paired))
                        {
                            if (device.PairingState == PairingState.Paired || device.PairingState == PairingState.PairedButOccluded)
                            {
                                kinectManager.PairingRecognizer.UnpairDevice(device);
                            }

                            kinectManager.PairingRecognizer.Pair(device, keyPair.Key);
                            pairedToNewDevice = true;
                            break;
                        }
                    }

                    //if the mouse drop is not close to a person then unpair the device.
                    if (!pairedToNewDevice)
                    {
                        kinectManager.PairingRecognizer.UnpairDevice(device);
                    }
                }

                //if the dragged device is not a pairable device (i.e table-top)
                else if (iaDevice.SupportedRoutes.Contains(Routes.GetLocationRoute))
                {
                    if (mouseLocation.X < canvasBounds.X && mouseLocation.Y < canvasBounds.Y)
                    {
                        // Dropped within Canvas, so we want to place it on the canvas
                        device.Location = DrawingResources.ConvertFromDisplayCoordinatesToMeters(mouseLocation, sharedCanvas);
                        request.SetBodyWith(new IntermediatePoint(device.Location.Value));
                    }
                    else
                    {
                        // Not dropped within Canvas, so we want to put it back on the stack panel
                        device.Location = null;
                        request.SetBodyWith(null);
                    }

                    // Send a request to the Device that their location has changed
                    kinectManager.IntAirAct.SendRequest(request, iaDevice);
                }
            }
        }
Ejemplo n.º 38
0
        private void RemoveOldPeople(List <Skeleton> skeletons, List <PairablePerson> pairablePersons, List <PairableDevice> pairableDevices, String kinectID)
        {
            // If a person has dissappeared, remove the kinect ID from they TrackIDwithSkeletonID dictionary
            List <PairablePerson> vanishedPersons = new List <PairablePerson>();

            foreach (PairablePerson person in pairablePersons)
            {
                foreach (KeyValuePair <string, string> entry in person.TrackerIDwithSkeletonID.ToList())
                {
                    if (entry.Key != null && entry.Key.Equals(kinectID))
                    {
                        bool found = false;
                        foreach (Skeleton skeleton in skeletons)
                        {
                            if (entry.Value.Equals(skeleton.TrackingId.ToString()))
                            {
                                found = true;
                            }
                        }
                        if (!found)
                        {
                            // Remove from the dictionary
                            person.TrackerIDwithSkeletonID.Remove(kinectID);
                        }
                    }
                }


                //If that person is not tracked by anyone then make them an occluded person.
                if (person.TrackerIDwithSkeletonID.Count == 0)
                {
                    //Remove Held-By-Person Identifier
                    PairableDevice device = pairableDevices.Find(x => x.Identifier.Equals(person.HeldDeviceIdentifier));

                    // If the person was not paired to a device, we can remove them immediately
                    if (device == null)
                    {
                        RemovePerson(vanishedPersons, person);
                    }
                    // If the person was paired, then we allow a grace period for them to reappear, to avoid immediately unpairing them
                    else
                    {
                        if (person.PairingState == PairingState.Paired)
                        {
                            person.PairingState = PairingState.PairedButOccluded;
                            person.Identifier   = null;
                        }
                        // The person will remain with PairingState == PairedButOccluded for a few seconds, after which it will mark itself NotPaired
                        // If this happens, we remove the person for good, and unpair their device
                        else if (person.PairingState == PairingState.NotPaired)
                        {
                            device.HeldByPersonIdentifier = null;
                            device.PairingState           = PairingState.NotPaired;

                            // Dispatch a message to the device
                            IARequest request = new IARequest(Routes.BecomeUnpairedRoute);
                            // Find the IntAirAct device matching the current device.
                            IADevice iaDevice = intAirAct.Devices.Find(d => d.Name == device.Identifier);
                            intAirAct.SendRequest(request, iaDevice);
                            System.Diagnostics.Debug.WriteLine(iaDevice.Name + " " + iaDevice.Host);

                            RemovePerson(vanishedPersons, person);
                        }
                    }
                }
            }
            foreach (PairablePerson person in vanishedPersons)
            {
                pairablePersons.Remove(person);
            }
        }