public string DualRegionQueryCircle(DateTime startDate, DateTime endDate, LatLong pointOne, double radiusOne, LatLong pointTwo, double radiusTwo)
        {
            using (TaxiDataEntities context = new TaxiDataEntities())
            {
                SqlGeography centroidOne = CreatePoint(pointOne);
                SqlGeography centroidTwo = CreatePoint(pointTwo);

                List<QueryDto> returnVal = context.TwoRegionQueryCircle(startDate, endDate, radiusOne, centroidOne.ToString(), radiusTwo, centroidTwo.ToString())
                    .Select(x => new QueryDto
                    {
                        Pickup = new LatLong
                        {
                            Latitude = (double)x.pickup_latitude,
                            Longitude = (double)x.pickup_longitude
                        },
                        Dropoff = new LatLong
                        {
                            Latitude = (double)x.dropoff_latitude,
                            Longitude = (double)x.dropoff_longitude
                        },
                        FareTotal = x.total_amount,
                        TravelTime = x.trip_time_in_secs,
                        NumOfPassenger = x.passenger_count,
                        TripDistance = x.trip_distance
                    }).ToList();

                return JsonConvert.SerializeObject(returnVal);
            }
        }
예제 #2
0
파일: Zone.cs 프로젝트: cjg/petroula
 public Zone(string name, LatLong center, int zoomlevel, List<LatLong> points)
 {
     this.name = name;
     this.center = center;
     this.zoomlevel = zoomlevel;
     this.points = points;
 }
        public static List<FortData> Optimize(FortData[] pokeStops, LatLong latlng, GMapOverlay routeOverlay)
        {
            List<FortData> optimizedRoute = new List<FortData>(pokeStops);

            // NN
            FortData NN = FindNN(optimizedRoute, latlng.Latitude, latlng.Longitude);
            optimizedRoute.Remove(NN);
            optimizedRoute.Insert(0, NN);
            for (int i = 1; i < pokeStops.Length; i++)
            {
                NN = FindNN(optimizedRoute.Skip(i), NN.Latitude, NN.Longitude);
                optimizedRoute.Remove(NN);
                optimizedRoute.Insert(i, NN);
                Visualize(optimizedRoute, routeOverlay);
            }

            // 2-Opt
            bool isOptimized;
            do
            {
                optimizedRoute = Optimize2Opt(optimizedRoute, out isOptimized);
                Visualize(optimizedRoute, routeOverlay);
            }
            while (isOptimized);

            return optimizedRoute;
        }
 /// <summary>Returns the distance using Haversine formula in miles or kilometers of any two latitude and longitude points.</summary>
 /// <param name="p1">Location 1</param>
 /// <param name="p2">Location 2</param>
 /// <param name="unit">Miles or Kilometers</param>
 /// <returns>Distance in the requested unit.</returns>
 public static double GetDistance(LatLong p1, LatLong p2, DistanceUnit unit)
 {
     double r = (unit == DistanceUnit.Miles) ? 3960 : 6371;
     var lat = (p2.Latitude - p1.Latitude).ToRadians();
     var lng = (p2.Longitude - p1.Longitude).ToRadians();
     var h1 = Math.Sin(lat / 2) * Math.Sin(lat / 2) + Math.Cos(p1.Latitude.ToRadians()) * Math.Cos(p2.Latitude.ToRadians()) * Math.Sin(lng / 2) * Math.Sin(lng / 2);
     var h2 = 2 * Math.Asin(Math.Min(1, Math.Sqrt(h1)));
     return r * h2;
 }
예제 #5
0
        /// <summary>
        /// Positions current location indicator on map
        /// </summary>
        /// <param name="pin">Current location pin object</param>
        /// <param name="position">Latitude/longitude at which to place pin</param>
        public static void SetCurrentLocationPin(this Map m, CurrentLocationPin pin, LatLong position)
        {
            MapLayer.SetPositionAnchor(pin, pin.AnchorPoint);
            MapLayer.SetPosition(pin, new Location(position.Latitude, position.Longitude));

            if (!m.Children.Contains(pin))
            {
                m.Children.Add(pin);
            }

            pin.Visibility = Visibility.Visible;
        }
        public void AssignmentTest()
        {
            LatLong assignment = new LatLong();

            Assert.AreEqual(0, assignment.Latitude);
            Assert.AreEqual(0, assignment.Longitude);

            assignment.Latitude  = 52.986375;
            assignment.Longitude = -10.27699;
            Assert.AreEqual(52.986375, assignment.Latitude);
            Assert.AreEqual(-10.27699, assignment.Longitude);
        }
        public void SubtractionTest()
        {
            LatLong e1 = new LatLong(53.3393, -6.2576841),
                    e2 = new LatLong(52.986375, -6.043701);

            LatLong expected = new LatLong(0.352925, -0.213983);

            Assert.AreEqual(expected, e1 - e2);

            expected = new LatLong(-0.352925, 0.213983);
            Assert.AreEqual(expected, e2 - e1);
        }
        public static void ConvertNationalGridToLongLat(SqlString xCoord, SqlString yCoord, out SqlDecimal SqlLongitude, out SqlDecimal SqlLatitude)
        {
            double LatidudeOut  = 0;
            double LongitudeOut = 0;

            ConvertNationalGridToLongLat_internal(Convert.ToDouble(xCoord.Value), Convert.ToDouble(yCoord.Value), out LongitudeOut, out LatidudeOut);
            LatLong OSGB36 = new LatLong(LatidudeOut, LongitudeOut);

            LatLong WGS84LatLong = convertOSGB36toWGS84(OSGB36);

            SqlLatitude  = (SqlDecimal)WGS84LatLong.Lat;
            SqlLongitude = (SqlDecimal)WGS84LatLong.Lon;
        }
예제 #9
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            LatLong valueAsLatLong = (LatLong)value;

            if (valueAsLatLong != null && valueAsLatLong.Latitude != null && valueAsLatLong.Longitude != null)
            {
                return(new Location(valueAsLatLong.Latitude, valueAsLatLong.Longitude));
            }
            else
            {
                return(null);
            }
        }
예제 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="latlong"></param>
        /// <returns></returns>
        private static Point3D LatLongToPoint(LatLong latlong)
        {
            double  latitude = latlong.Latitude;
            double  degrees  = latlong.Longitude - 90.0;
            Point3D pointd   = new Point3D();

            latitude = GISHelper.DegToRad(latitude);
            degrees  = GISHelper.DegToRad(degrees);
            pointd.Y = Math.Sin(latitude);
            pointd.X = -Math.Cos(degrees) * Math.Cos(latitude);
            pointd.Z = Math.Sin(degrees) * Math.Cos(latitude);
            return(pointd);
        }
        /// <summary>
        /// Calculate the geographical distance between point a and point b
        /// </summary>
        /// <param name="a"></param>geopoint a
        /// <param name="b"></param>geopoint b
        /// <returns></returns>
        public static double GeoDistance(LatLong x1, LatLong x2)
        {
            double radLat1 = rad(x1.Latitude);
            double radLat2 = rad(x2.Latitude);
            double a       = radLat1 - radLat2;
            double b       = rad(x1.Longitude) - rad(x2.Longitude);
            double s       = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
                                                     Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));

            s = s * EARTH_RADIUS;
            s = Math.Round(s * 10000) / 10000;
            return(s);
        }
예제 #12
0
 public GoogleMap()
 {
     MapType      = GMap_MapType.G_HYBRID_MAP;
     MapMode      = GMap_Mode.Dynamic;
     ShowMarkers  = true;
     ShowRoute    = true;
     MapVisible   = true;
     Path         = new LatLong[0];
     ZoomFactor   = GMap_ZoomLevels.US;
     MapCenter    = new LatLong(35.224762, -86.156354); // approximate center of US
     ClickHandler = string.Empty;
     PathVarName  = "rgPath";
 }
예제 #13
0
    public LatLong GetLatLong(string StateOrCity)
    {
        string  output;
        LatLong lst = new LatLong();

        using (WebClient client = new WebClient())
        {
            string input = "http://autocomplete.wunderground.com/aq?query=" + StateOrCity;
            output = client.DownloadString(input);
            lst    = JsonConvert.DeserializeObject <LatLong>(output);
            return(lst);
        }
    }
    void OnBuildingSelected(bool success, Building building)
    {
        if (success)
        {
            var boxLocation = LatLong.FromDegrees(building.Centroid.GetLatitude(), building.Centroid.GetLongitude());
            var boxAnchor   = Instantiate(boxPrefab) as GameObject;
            boxAnchor.GetComponent <GeographicTransform>().SetPosition(boxLocation);

            var box = boxAnchor.transform.GetChild(0);
            box.localPosition = new Vector3(0.0f, (float)building.TopAltitude, 0.0f);
            Destroy(boxAnchor, 2.0f);
        }
    }
예제 #15
0
        public void ParseTest()
        {
            var      target = new LatLong();           // TODO: Initialize to an appropriate value
            int      LatitudePostionFieldNumber   = 0; // TODO: Initialize to an appropriate value
            int      NorthingFieldNumber          = 0; // TODO: Initialize to an appropriate value
            int      LongitudePositionFieldNumber = 0; // TODO: Initialize to an appropriate value
            int      EastingFieldNumber           = 0; // TODO: Initialize to an appropriate value
            Sentence LineToParse = null;               // TODO: Initialize to an appropriate value
            bool     expected    = false;              // TODO: Initialize to an appropriate value
            bool     actual      = target.Parse(LatitudePostionFieldNumber, NorthingFieldNumber, LongitudePositionFieldNumber, EastingFieldNumber, LineToParse);

            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
예제 #16
0
        /// <param name="latLong">
        ///            the point </param>
        /// <param name="tile">
        ///            the tile </param>
        /// <returns> true if the point is located in the given tile </returns>
        public static bool pointInTile(LatLong latLong, TileCoordinate tile)
        {
            if (latLong == null || tile == null)
            {
                return(false);
            }

            double lon1 = MercatorProjection.tileXToLongitude(tile.X, tile.Zoomlevel);
            double lon2 = MercatorProjection.tileXToLongitude(tile.X + 1, tile.Zoomlevel);
            double lat1 = MercatorProjection.tileYToLatitude(tile.Y, tile.Zoomlevel);
            double lat2 = MercatorProjection.tileYToLatitude(tile.Y + 1, tile.Zoomlevel);

            return(latLong.latitude <= lat1 && latLong.latitude >= lat2 && latLong.longitude >= lon1 && latLong.longitude <= lon2);
        }
예제 #17
0
        /// <summary>
        /// Begin an operation to precache a spherical area of the map. This allows that area to load faster in future.
        /// </summary>
        /// <param name="center">the center of the area to precache</param>
        /// <param name="radius">the radius (in meters) of the area to precache</param>
        /// <param name="completionCallback">the callback to call whenever the precache operation completes</param>
        /// <returns>an object with a Cancel() method to allow cancellation of the precache operation</returns>
        public PrecacheOperation Precache(LatLong center, double radius, PrecacheOperationCompletedCallback completionCallback)
        {
            if (radius < 0.0 || radius > MaximumPrecacheRadius)
            {
                throw new ArgumentOutOfRangeException("radius", string.Format("radius outside of valid (0, {0}] range.", MaximumPrecacheRadius));
            }

            int operationId = m_precacheApiInternal.BeginPrecacheOperation(center, radius);
            var operation   = new PrecacheOperation(m_precacheApiInternal, operationId, completionCallback);

            m_precacheOperations.Add(operationId, operation);

            return(operation);
        }
    IEnumerator Example()
    {
        //var startLocation = LatLong.FromDegrees(37.7858, -122.401);
        var startLocation = LatLong.FromDegrees(53.495, -113.5210);

        Api.Instance.CameraApi.MoveTo(startLocation, distanceFromInterest: 1890);

        yield return(new WaitForSeconds(4.0f));

        //var destLocation = LatLong.FromDegrees(37.802, -122.4058);
        var destLocation = LatLong.FromDegrees(53.515, -113.5276);

        Api.Instance.CameraApi.AnimateTo(destLocation, distanceFromInterest: 500, headingDegrees: 270, tiltDegrees: 30, transitionDuration: 5, jumpIfFarAway: false);
    }
예제 #19
0
    private void OnEnable()
    {
        // Start precaching resources in a 2000 meter radius around this point
        PrecacheOperation precacheOperation = Api.Instance.PrecacheApi.Precache(
            LatLong.FromDegrees(37.7952, -122.4028),
            2000.0,
            (_result) =>
        {
            Debug.LogFormat("Precaching {0}", _result.Succeeded ? "complete" : "cancelled");
        });

        // cancel the precache operation
        precacheOperation.Cancel();
    }
예제 #20
0
        private void ShowDepartures(string to, bool actSilently)
        {
            var currentPosition = LocationService.CurrentPosition;

            if (currentPosition != null && !currentPosition.IsUnknown)
            {
                var from = Stations.GetNearest(LatLong.Create(currentPosition.Latitude, currentPosition.Longitude), 1)[0];
                ShowDepartures(Stations.GetAll(), from.Item2, null, to, actSilently);
            }
            else
            {
                OnError();
            }
        }
예제 #21
0
        /// <summary>
        /// Smoothly animates the camera to view the supplied interest point. Requires that a camera has been set using SetControlledCamera.
        /// </summary>
        /// <param name="interestPoint">The latitude and longitude of the point on the ground which the camera should be looking at once the transition is complete.</param>
        /// <param name="cameraPosition">The latitude, longitude and altitude from which the camera will look at the interest point when the transition is complete.</param>
        /// <param name="transitionDuration">Optional. The total duration of the transition, in seconds. If not specified the duration will be calculated from the distance to be travelled and the camera&apos;s maximum speed.</param>
        /// <param name="jumpIfFarAway">Optional. By default AnimateTo will provide a smooth transition for short distances, but an instantaneous transition if there is a large distance to be covered (rather than waiting for a lengthy animation to play). If you want to override this behaviour and force an animation (even over large distances), you can set this to false.</param>
        /// <returns>Whether the camera successfully animated or not.</returns>
        public bool AnimateTo(
            LatLong interestPoint,
            LatLongAltitude cameraPosition,
            double?transitionDuration = null,
            bool jumpIfFarAway        = true)
        {
            double distance;
            double headingDegrees;
            double tiltDegrees;

            GetTiltHeadingAndDistanceFromCameraAndTargetPosition(interestPoint, cameraPosition, out tiltDegrees, out headingDegrees, out distance);

            return(AnimateTo(interestPoint, distance, headingDegrees, tiltDegrees, transitionDuration, jumpIfFarAway));
        }
    IEnumerator Example()
    {
        Api.Instance.CameraApi.RegisterShouldConsumeInputDelegate(ShouldConsumeCameraInput);

        var startLocation = LatLong.FromDegrees(37.7858, -122.401);

        Api.Instance.CameraApi.MoveTo(startLocation, distanceFromInterest: 800, headingDegrees: 0, tiltDegrees: 50);

        yield return(new WaitForSeconds(4.0f));

        var destLocation = LatLong.FromDegrees(37.7952, -122.4028);

        Api.Instance.CameraApi.MoveTo(destLocation, distanceFromInterest: 500);
    }
        public ActionResult Create([Bind(Include = "teamPracticeId,practiceLocation,practicePrice,indoor,outdoor,practiceTime")] TeamPractice teamPractice)
        {
            if (ModelState.IsValid)
            {
                LatLong latlong = APIController.GoogleCall(teamPractice.practiceLocation);
                teamPractice.lat = latlong.lat;
                teamPractice.lng = latlong.lng;
                db.TeamPractices.Add(teamPractice);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(teamPractice));
        }
예제 #24
0
        /// <summary>
        /// Convert a locator to latitude and longitude in degrees
        /// </summary>
        /// <param name="locator">Locator string to convert</param>
        /// <returns>LatLong structure</returns>
        public static LatLong LocatorToLatLong(string locator)
        {
            locator = locator.Trim().ToUpper().ToString();
            if (!Regex.IsMatch(locator, "^[A-R]{2}[0-9]{2}[A-X]{2}$"))
            {
                throw new FormatException("Invalid locator format");
            }

            LatLong ll = new LatLong();

            ll.Long = (locator[0] - 'A') * 20 + (locator[2] - '0') * 2 + (locator[4] - 'A' + 0.5) / 12 - 180;
            ll.Lat  = (locator[1] - 'A') * 10 + (locator[3] - '0') + (locator[5] - 'A' + 0.5) / 24 - 90;
            return(ll);
        }
예제 #25
0
        public ActionResult Create([Bind(Include = "tournamentId,tournamentLocation,tournamentTime,tournamentPrice,tournamentHotel")] Tournament tournament)
        {
            if (ModelState.IsValid)
            {
                LatLong latlong = APIController.GoogleCall(tournament.tournamentLocation);
                tournament.lat = latlong.lat;
                tournament.lng = latlong.lng;
                db.Tournaments.Add(tournament);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(tournament));
        }
예제 #26
0
        public IEnumerable <JsonDinner> SearchByPlaceNameOrZip(string location)
        {
            if (String.IsNullOrEmpty(location))
            {
                return(null);
            }
            LatLong foundlocation = GeolocationService.PlaceOrZipToLatLong(location);

            if (foundlocation != null)
            {
                return(FindByLocation(foundlocation.Lat, foundlocation.Long).
                       OrderByDescending(p => p.EventDate));
            }
            return(null);
        }
예제 #27
0
        private static IList <int?> toCoordinateList(Geometry jtsGeometry)
        {
            Coordinate[] jtsCoords = jtsGeometry.Coordinates;

            List <int?> result = new List <int?>();

            for (int j = 0; j < jtsCoords.Length; j++)
            {
                LatLong geoCoord = new LatLong(jtsCoords[j].y, jtsCoords[j].x, true);
                result.Add(Convert.ToInt32(LatLongUtils.degreesToMicrodegrees(geoCoord.latitude)));
                result.Add(Convert.ToInt32(LatLongUtils.degreesToMicrodegrees(geoCoord.longitude)));
            }

            return(result);
        }
예제 #28
0
        /// <summary>
        /// Adds point-of-interest pin to designated location
        /// </summary>
        /// <param name="pin">Point-of-interest pin instance</param>
        /// <param name="position">Latitude/longitude for pin placement</param>
        public static void AddPointOfInterestPin(this Map m, PointOfInterestPin pin, LatLong position)
        {
            MapLayer poiLayer = PoiLayer(m);

            if (poiLayer == null)
            {
                poiLayer = new MapLayer();
                m.Children.Add(poiLayer);
            }

            MapLayer.SetPositionAnchor(pin, pin.AnchorPoint);

            MapLayer.SetPosition(pin, new Location(position.Latitude, position.Longitude));
            poiLayer.Children.Add(pin);
        }
        public void DistanceBetweenTest()
        {
            // Used http://www.movable-type.co.uk/scripts/latlong.html to
            // determine expected distances.

            LatLong DublinOffice  = new LatLong(53.3393, -6.2576841),
                    DavidBehan    = new LatLong(52.833502, -8.522366),
                    MichaelAhearn = new LatLong(52.966, -6.463),
                    OliveAhearn   = new LatLong(53, -7);

            Assert.AreEqual(0, Earth.DistanceBetween(DublinOffice, DublinOffice), "DublinOffice");
            Assert.AreEqual(161.4, Earth.DistanceBetween(DublinOffice, DavidBehan), "DavidBehan");
            Assert.AreEqual(43.7, Earth.DistanceBetween(DublinOffice, MichaelAhearn), "MichaelAhearn");
            Assert.AreEqual(62.2, Earth.DistanceBetween(DublinOffice, OliveAhearn), "OliveAhearn");
        }
예제 #30
0
    public static Vector3 GetVector3FromLatLon(LatLong latlong, float sphereRadius)
    {
        var latitude  = Mathf.PI * latlong.Lat / 180f;
        var longitude = Mathf.PI * latlong.Long / 180f;

        // adjust position by radians
        latitude -= 1.570795765134f; // subtract 90 degrees (in radians)

        // and switch z and y (since z is forward)
        float xPos = (sphereRadius) * Mathf.Sin(latitude) * Mathf.Cos(longitude);
        float zPos = (sphereRadius) * Mathf.Sin(latitude) * Mathf.Sin(longitude);
        float yPos = (sphereRadius) * Mathf.Cos(latitude);

        return(new Vector3(xPos, yPos, zPos));
    }
예제 #31
0
        internal static void OnBuildingReceived(bool buildingReceived, BuildingInterop building, int buildingRequestId)
        {
            var request = BuildingRequests[buildingRequestId];

            Building result;

            result.BuildingId   = Marshal.PtrToStringAnsi(building.StringIdPtr);
            result.BaseAltitude = building.BaseAltitude;
            result.TopAltitude  = building.TopAltitude;
            result.Centroid     = LatLong.FromDegrees(building.CentroidLatitude, building.CentroidLongitude);

            BuildingRequests.Remove(buildingRequestId);

            request.callback(buildingReceived, result);
        }
예제 #32
0
        public void Spawn(Texture texture, double latitude, double longitude)
        {
            targetPosition = new LatLong(latitude, longitude);
            Api.Instance.CameraApi.MoveTo(targetPosition, distanceFromInterest: 1200, headingDegrees: 0, tiltDegrees: 45);

            sphereParent = new GameObject("sphereParent");

            gt = sphereParent.AddComponent(typeof(GeographicTransform)) as GeographicTransform;
            gt.SetPosition(targetPosition);

            ReversedSphere = Instantiate(ReversedSphere, new Vector3(0, 60, 0), Quaternion.identity);
            ReversedSphere.transform.SetParent(sphereParent.transform);
            //var texture = Resources.Load<Texture2D>("Textures/01-7745");
            SetTexture(texture);
        }
예제 #33
0
        public ActionResult SearchByPlaceNameOrZip(string placeOrZip)
        {
            if (String.IsNullOrEmpty(placeOrZip))
            {
                return(null);
            }
            ;
            LatLong location = GeolocationService.PlaceOrZipToLatLong(placeOrZip);

            var dinners = dinnerRepository.
                          FindByLocation(location.Lat, location.Long).
                          OrderByDescending(p => p.EventDate);

            return(View("Results", dinners.ToPagedList(1, 20)));
        }
예제 #34
0
        public SessionDisplayablePoint(
            TimeSpan timeSpan,
            int?distance,
            int?altitude,
            double?speed,
            LatLong position)
        {
            Time     = timeSpan;
            Altitude = altitude;
            Speed    = speed;
            Position = position;
            Distance = distance;

            MapPointColor = Color.Default;
        }
예제 #35
0
 //clone
 public LatLong(LatLong p)
 {
     this.Latitude = p.Latitude;
     this.Longitude = p.Longitude;
     this.Size = p.Size;
     this.Numerator = p.Numerator;
     this.Denominator = p.Denominator;
 }
        public ActionResult EditJobDetails(JobViewModel _jobdetails)
        {
            Logger.Debug("Inside People Controller- Create");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    List<JobProgressViewModel> pJobProgressViewModel = new List<JobProgressViewModel>();

                    TempData["TabName"] = "Details";
                    DropdownValues();
                    JobViewModel _job = _jobdetails;
                    if (ModelState.IsValid)
                    {
                        Job job = new Job();
                        job.JobGUID = new Guid(_job.JobModel.JobIndexGUID.ToString());
                        Int16 jobclass;

                        if (_job.JobModel.JobClass != null && !string.IsNullOrEmpty(_job.JobModel.JobClass))
                        {
                            string[] pjobclass = _job.JobModel.JobClass.Split(',');
                            if (pjobclass.Count() > 1)
                            {
                                if (short.TryParse(pjobclass[0], out jobclass))
                                {
                                    job.JobClass = jobclass;
                                }
                                job.JobForm = _IJobSchemaRepository.GetJobSchemabyJobFormID(new Guid(pjobclass[1])).JobForm1;
                            }
                        }
                        //job.JobFormGUID = _job.JobModel.JobLogicalID;
                        //  job.JobID = 0;
                        job.JobReferenceNo = _job.JobModel.JobReferenceNo;
                        job.IsDeleted = false;
                        job.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                        if (_job.JobModel.RegionCode != Guid.Empty)
                        {
                            job.RegionGUID = _job.JobModel.RegionCode;
                        }
                        else
                        {
                            job.RegionGUID = null;
                        }
                        if (_job.JobModel.TerritoryCode != Guid.Empty)
                        {
                            job.TerritoryGUID = _job.JobModel.TerritoryCode;
                        }
                        else
                        {
                            job.TerritoryGUID = null;
                        }
                        job.LocationType = 1;
                        if (_job.JobModel.CustGUID != Guid.Empty)
                        {
                            job.CustomerGUID = _job.JobModel.CustGUID;
                        }
                        else
                        {
                            job.CustomerGUID = null;
                        }
                        if (_job.JobModel.StopsGUID != Guid.Empty)
                        {
                            job.CustomerStopGUID = _job.JobModel.StopsGUID;
                        }
                        else
                        {
                            job.CustomerStopGUID = null;
                        }
                        if (job.CustomerStopGUID != null)
                        {
                            Market Market = _IMarketRepository.GetMarketByID(new Guid(job.CustomerStopGUID.ToString()));
                            LatLong latLong = new LatLong();
                            latLong = GetLatLngCode(Market.AddressLine1, Market.AddressLine2, Market.City, Market.State, Market.Country, Market.ZipCode);
                            job.ServiceAddress = Market.AddressLine1 + "," + Market.AddressLine2 + "," + Market.City + "," + Market.State + "," + Market.Country + "," + Market.ZipCode;
                            job.Latitude = latLong.Latitude;
                            job.Longitude = latLong.Longitude;
                        }
                        else
                        {
                            job.ServiceAddress = "";
                            job.Latitude = null;
                            job.Longitude = null;
                        }
                        job.StatusCode = 1;
                        job.JobName = _job.JobModel.JobName;
                        job.IsSecheduled = _job.JobModel.IsScheduled == "true" ? true : false;
                        job.ManagerUserGUID = new Guid(Session["UserGUID"].ToString());

                        double duration;
                        if (double.TryParse(_job.JobModel.EstimatedDuration.ToString(), out duration))
                            job.EstimatedDuration = duration * 3600;
                        else
                            job.EstimatedDuration = 0;

                        job.ScheduledStartTime = Convert.ToDateTime(_job.JobModel.PreferredStartTime);
                        job.PreferedStartTime = Convert.ToDateTime(_job.JobModel.PreferredStartTime);
                        job.PreferedEndTime = Convert.ToDateTime(_job.JobModel.PreferredEndTime);
                        job.ActualStartTime = Convert.ToDateTime(_job.JobModel.ActualStartTime);
                        job.ActualEndTime = Convert.ToDateTime(_job.JobModel.ActualEndTime);


                        //  job.JobForm = _IJobSchemaRepository.GetJobSchemabyJobFormID(_job.JobModel.JobLogicalID).JobForm1;
                        job.CreateDate = DateTime.UtcNow;
                        job.CreateBy = new Guid(Session["UserGUID"].ToString());
                        job.LastModifiedDate = DateTime.UtcNow;
                        job.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                        int result = _IJobRepository.UpdateJob(job);
                        //int result = _IJobRepository.Save();
                        if (result > 0)
                        {
                            // return RedirectToAction("Index", "JobDetails", new { jobindexguid = _job.JobModel.JobIndexGUID.ToString() });
                            return RedirectToAction("Index", "JobStatus");
                        }
                        else
                        {
                            if (Session["OrganizationGUID"] != null)
                            {
                                Job _job1 = _IJobRepository.GetJobByID(new Guid(_job.JobModel.JobIndexGUID.ToString()));
                                JobModel job1 = new JobModel();
                                job1.JobIndexGUID = _job1.JobGUID;
                                //     job1.JobLogicalID = _IJobSchemaRepository.GetJobFormIDfromJobForm(_job1.JobForm);
                                job1.JobReferenceNo = _job1.JobReferenceNo;
                                job1.JobName = _job1.JobName;
                                job1.CustGUID = _job1.CustomerGUID != null ? new Guid(_job1.CustomerGUID.ToString()) : Guid.Empty;
                                job1.IsScheduled = _job1.IsSecheduled == true ? "true" : "false";
                                job1.EstimatedDuration = _job1.EstimatedDuration;
                                job1.ActualStartTime = Convert.ToDateTime(_job1.ActualStartTime).ToString("MM/dd/yy HH:mm");
                                job1.ActualEndTime = Convert.ToDateTime(_job1.ActualEndTime).ToString("MM/dd/yy HH:mm");
                                job1.PreferredStartTime = Convert.ToDateTime(_job1.PreferedStartTime).ToString("MM/dd/yy HH:mm");
                                job1.PreferredEndTime = Convert.ToDateTime(_job1.PreferedEndTime).ToString("MM/dd/yy HH:mm");
                                job1.RegionCode = _job1.RegionGUID != null ? new Guid(_job1.RegionGUID.ToString()) : Guid.Empty;
                                job1.TerritoryCode = _job1.TerritoryGUID != null ? new Guid(_job1.TerritoryGUID.ToString()) : Guid.Empty;
                                job1.StopsGUID = _job1.CustomerStopGUID != null ? new Guid(_job1.CustomerStopGUID.ToString()) : Guid.Empty;
                                job1.CustomerName = _job1.CustomerGUID != null ? _IJobRepository.GetCustomerName(new Guid(_job1.CustomerGUID.ToString())) : "";
                                job1.CreateDate = _job1.CreateDate;
                                int StatusCode; ;
                                if (int.TryParse(_job1.StatusCode.ToString(), out StatusCode))
                                {
                                    job1.Status = StatusCode;
                                }
                                else
                                {
                                    job1.Status = 0;
                                }

                                var placeList = new PlaceViewModel();
                                placeList.PlaceList = new List<PlaceModel>();
                                var appPlace = new List<Place>();
                                DropdownValues();
                                appPlace = _IPlaceRepository.GetPlaceByOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).ToList();

                                placeList.PlaceList.Add(new PlaceModel
                                {
                                    PlaceGUID = Guid.Empty.ToString(),
                                    PlaceName = "All",
                                    UserGUID = "",
                                    OrganizationGUID = "",
                                });

                                foreach (var place in appPlace.ToList())
                                {
                                    placeList.PlaceList.Add(new PlaceModel
                                    {
                                        PlaceGUID = place.PlaceGUID.ToString(),
                                        PlaceID = place.PlaceID,
                                        PlaceName = place.PlaceName,
                                        UserGUID = place.UserGUID.ToString(),
                                        OrganizationGUID = place.OrganizationGUID != null ? place.OrganizationGUID.ToString() : Guid.Empty.ToString(),
                                    });
                                }

                                var marketList = new MarketViewModel();
                                marketList.MarketList = new List<MarketModel>();
                                var appMarket = new List<Market>();
                                // if (Session["UserType"].ToString() == "ENT_A")
                                {
                                    appMarket = _IMarketRepository.GetMarketByOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString()), 1).ToList();
                                }
                                //else
                                //{
                                //    appMarket = _IMarketRepository.GetMarketByUserGUID(new Guid(Session["UserGUID"].ToString()), 1).ToList();
                                //}

                                foreach (var market in appMarket.ToList())
                                {
                                    marketList.MarketList.Add(new MarketModel
                                    {
                                        MarketGUID = market.MarketGUID.ToString(),
                                        UserGUID = market.UserGUID != null ? market.UserGUID.ToString() : Guid.Empty.ToString(),
                                        OrganizationGUID = market.OrganizationGUID != null ? market.OrganizationGUID.ToString() : Guid.Empty.ToString(),
                                        OwnerGUID = market.OwnerGUID != null ? market.OwnerGUID.ToString() : Guid.Empty.ToString(),
                                        MarketName = market.MarketName,
                                        MarketPhone = market.MarketPhone,
                                        PrimaryContactGUID = market.PrimaryContactGUID != null ? market.PrimaryContactGUID.ToString() : Guid.Empty.ToString(),
                                        FirstName = market.FirstName,
                                        LastName = market.LastName,
                                        MobilePhone = market.MobilePhone,
                                        HomePhone = market.HomePhone,
                                        Emails = market.Emails,
                                        AddressLine1 = market.AddressLine1,
                                        AddressLine2 = market.AddressLine2,
                                        City = market.City,
                                        State = market.State,
                                        Country = market.Country,
                                        ZipCode = market.ZipCode,
                                        RegionGUID = market.RegionGUID != null ? market.RegionGUID.ToString() : Guid.Empty.ToString(),
                                        TerritoryGUID = market.TerritoryGUID != null ? market.TerritoryGUID.ToString() : Guid.Empty.ToString(),
                                        RegionName = market.RegionGUID != null ? _IRegionRepository.GetRegionNameByRegionGUID(new Guid(market.RegionGUID.ToString())) : "",
                                        TerritoryName = market.TerritoryGUID != null ? _ITerritoryRepository.GetTerritoryNameByTerritoryGUID(new Guid(market.TerritoryGUID.ToString())) : "",
                                    });
                                }
                                pJobProgressViewModel = getJobProgress(_job.JobModel.JobIndexGUID.ToString());
                                var viewModel = new JobViewModel();
                                viewModel.Place = placeList.PlaceList;
                                viewModel.Market = marketList.MarketList;
                                viewModel.JobProgressList = pJobProgressViewModel;
                                viewModel.JobModel = job1;
                                return View("Index", viewModel);
                                //return RedirectToAction("Index", "JobDetails", new { jobindexguid = _job.JobModel.JobIndexGUID.ToString() });
                            }
                            else
                            {
                                return RedirectToAction("../User/Login");
                            }

                        }
                    }
                    else
                    {
                        if (Session["OrganizationGUID"] != null)
                        {
                            Job _job1 = _IJobRepository.GetJobByID(new Guid(_job.JobModel.JobIndexGUID.ToString()));
                            JobModel job1 = new JobModel();
                            job1.JobIndexGUID = _job1.JobGUID;
                            //  job1.JobLogicalID = _IJobSchemaRepository.GetJobFormIDfromJobForm(_job1.JobForm);

                            job1.JobReferenceNo = _job1.JobReferenceNo;
                            job1.JobName = _job1.JobName;
                            job1.CustGUID = _job1.CustomerGUID != null ? new Guid(_job1.CustomerGUID.ToString()) : Guid.Empty;
                            job1.IsScheduled = _job1.IsSecheduled == true ? "true" : "false";
                            job1.EstimatedDuration = _job1.EstimatedDuration;
                            job1.ActualStartTime = Convert.ToDateTime(_job1.ActualStartTime).ToString("MM/dd/yy HH:mm");
                            job1.ActualEndTime = Convert.ToDateTime(_job1.ActualEndTime).ToString("MM/dd/yy HH:mm");
                            job1.PreferredStartTime = Convert.ToDateTime(_job1.PreferedStartTime).ToString("MM/dd/yy HH:mm");
                            job1.PreferredEndTime = Convert.ToDateTime(_job1.PreferedEndTime).ToString("MM/dd/yy HH:mm");
                            job1.RegionCode = _job1.RegionGUID != null ? new Guid(_job1.RegionGUID.ToString()) : Guid.Empty;
                            job1.TerritoryCode = _job1.TerritoryGUID != null ? new Guid(_job1.TerritoryGUID.ToString()) : Guid.Empty;
                            job1.StopsGUID = _job1.CustomerStopGUID != null ? new Guid(_job1.CustomerStopGUID.ToString()) : Guid.Empty;
                            job1.CustomerName = _job1.CustomerGUID != null ? _IJobRepository.GetCustomerName(new Guid(_job1.CustomerGUID.ToString())) : "";
                            job1.CreateDate = _job1.CreateDate;

                            int StatusCode; ;
                            if (int.TryParse(_job1.StatusCode.ToString(), out StatusCode))
                            {
                                job1.Status = StatusCode;
                            }
                            else
                            {
                                job1.Status = 0;
                            }
                            var placeList = new PlaceViewModel();
                            placeList.PlaceList = new List<PlaceModel>();
                            var appPlace = new List<Place>();
                            DropdownValues();
                            appPlace = _IPlaceRepository.GetPlaceByOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString())).ToList();

                            placeList.PlaceList.Add(new PlaceModel
                            {
                                PlaceGUID = Guid.Empty.ToString(),
                                PlaceName = "All",
                                UserGUID = "",
                                OrganizationGUID = "",
                            });

                            foreach (var place in appPlace.ToList())
                            {
                                placeList.PlaceList.Add(new PlaceModel
                                {
                                    PlaceGUID = place.PlaceGUID.ToString(),
                                    PlaceID = place.PlaceID,
                                    PlaceName = place.PlaceName,
                                    UserGUID = place.UserGUID.ToString(),
                                    OrganizationGUID = place.OrganizationGUID != null ? place.OrganizationGUID.ToString() : Guid.Empty.ToString(),
                                });
                            }

                            var marketList = new MarketViewModel();
                            marketList.MarketList = new List<MarketModel>();
                            var appMarket = new List<Market>();
                            //if (Session["UserType"].ToString() == "ENT_A")
                            {
                                appMarket = _IMarketRepository.GetMarketByOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString()), 1).ToList();
                            }
                            //else
                            //{
                            //    appMarket = _IMarketRepository.GetMarketByUserGUID(new Guid(Session["UserGUID"].ToString()), 1).ToList();
                            //}

                            foreach (var market in appMarket.ToList())
                            {
                                marketList.MarketList.Add(new MarketModel
                                {
                                    MarketGUID = market.MarketGUID.ToString(),
                                    UserGUID = market.UserGUID != null ? market.UserGUID.ToString() : Guid.Empty.ToString(),
                                    OrganizationGUID = market.OrganizationGUID != null ? market.OrganizationGUID.ToString() : Guid.Empty.ToString(),
                                    OwnerGUID = market.OwnerGUID != null ? market.OwnerGUID.ToString() : Guid.Empty.ToString(),
                                    MarketName = market.MarketName,
                                    MarketPhone = market.MarketPhone,
                                    PrimaryContactGUID = market.PrimaryContactGUID != null ? market.PrimaryContactGUID.ToString() : Guid.Empty.ToString(),
                                    FirstName = market.FirstName,
                                    LastName = market.LastName,
                                    MobilePhone = market.MobilePhone,
                                    HomePhone = market.HomePhone,
                                    Emails = market.Emails,
                                    AddressLine1 = market.AddressLine1,
                                    AddressLine2 = market.AddressLine2,
                                    City = market.City,
                                    State = market.State,
                                    Country = market.Country,
                                    ZipCode = market.ZipCode,
                                    RegionGUID = market.RegionGUID != null ? market.RegionGUID.ToString() : Guid.Empty.ToString(),
                                    TerritoryGUID = market.TerritoryGUID != null ? market.TerritoryGUID.ToString() : Guid.Empty.ToString(),
                                    RegionName = market.RegionGUID != null ? _IRegionRepository.GetRegionNameByRegionGUID(new Guid(market.RegionGUID.ToString())) : "",
                                    TerritoryName = market.TerritoryGUID != null ? _ITerritoryRepository.GetTerritoryNameByTerritoryGUID(new Guid(market.TerritoryGUID.ToString())) : "",
                                });
                            }
                            pJobProgressViewModel = getJobProgress(_job.JobModel.JobIndexGUID.ToString());
                            var viewModel = new JobViewModel();
                            viewModel.Place = placeList.PlaceList;
                            viewModel.Market = marketList.MarketList;
                            viewModel.JobProgressList = pJobProgressViewModel;
                            viewModel.JobModel = job1;

                            return View("Index", viewModel);
                        }
                        else
                        {
                            return RedirectToAction("../User/Login");
                        }

                    }
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return RedirectToAction("Login", "User");
            }
        }
예제 #37
0
            private const double Exp = 2; // 2=euclid, 1=manhatten

            #endregion Fields

            #region Methods

            public static bool BoxWithin(LatLong a, LatLong b, double boxsize)
            {
                var d = boxsize / 2;
                var withinX = a.Latitude - d <= b.Latitude && a.Latitude + d >= b.Latitude;
                var withinY = a.Longitude - d <= b.Longitude && a.Longitude + d >= b.Longitude;
                return withinX && withinY;
            }
예제 #38
0
 public static double Distance(LatLong a, LatLong b)
 {
     return StraightLineDistance(a.Latitude, a.Longitude, b.Latitude, b.Longitude);
     //return Math.Pow(Math.Pow(Math.Abs(a.X - b.X), Exp) +
     //    Math.Pow(Math.Abs(a.Y - b.Y), Exp), 1.0 / Exp);
 }
        private int InsertOrUpdateStore(DataRow dr)
        {
            int result = 0;
            try
            {
                Place _place = _IPlaceRepository.GetPlaceByID(dr["parentid"].ToString(), new Guid(Session["OrganizationGUID"].ToString()));
                Territory _territory = _ITerritoryRepository.GetTerritoryByTerritoryID(dr["marketid"].ToString(), new Guid(Session["OrganizationGUID"].ToString()));
                Market _market = _IMarketRepository.GetMarketByCustomerID(new Guid(Session["OrganizationGUID"].ToString()), dr["parentid"].ToString(), dr["storenum"].ToString());
                //Market _market = _IMarketRepository.GetMarketByCustomerID(new Guid(Session["OrganizationGUID"].ToString()), dr["parentid"].ToString(), dr["storenum"].ToString().PadLeft(4, '0'));

                Regex objphonePattern = new Regex(@"(1?)(-| ?)(\()?([0-9]{3})(\)|-| |\)-|\) )?([0-9]{3})(-| )?([0-9]{3,14}|[0-9]{3,14})");
                Regex objEmailPattern = new Regex(@"[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?");

                //if (_place != null && _territory != null && _market == null && objphonePattern.IsMatch(dr["phone"].ToString()) && objEmailPattern.IsMatch(dr["email"].ToString()))
                //var result = input.ToString().PadLeft(length, '0');leading zero
                if (_place != null)
                {
                    Market Market = new Market();

                    Market.MarketID = dr["storenum"].ToString();
                    //Market.MarketID = Market.MarketID.PadLeft(4, '0');
                    Market.IsDefault = true;
                    if (!string.IsNullOrEmpty(Session["UserGUID"].ToString()) && Session["UserGUID"].ToString() != Guid.Empty.ToString())
                    {
                        Market.UserGUID = new Guid(Session["UserGUID"].ToString());
                    }
                    else
                    {
                        Market.UserGUID = null;
                    }
                    Market.EntityType = 1;
                    if (!string.IsNullOrEmpty(Session["OrganizationGUID"].ToString()) && Session["OrganizationGUID"].ToString() != Guid.Empty.ToString())
                    {
                        Market.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                    }
                    else
                    {
                        Market.OrganizationGUID = null;
                    }
                    if (_place.PlaceGUID != Guid.Empty)
                    {
                        Market.OwnerGUID = _place.PlaceGUID;
                    }
                    else
                    {
                        Market.OwnerGUID = null;
                    }
                    Market.MarketName = dr["name"].ToString();

                    List<Person> _people = _IPeopleRepository.GetPeopleByPlaceGUID(_place.PlaceGUID).ToList();
                    if (_people.Count > 0)
                    {
                        _people = _people.OrderByDescending(x => x.CreatedDate).ToList();
                        if (_people[0].PeopleGUID != Guid.Empty)
                        {
                            Market.PrimaryContactGUID = _people[0].PeopleGUID;
                        }
                        else
                        {
                            Market.PrimaryContactGUID = null;
                        }
                    }
                    else
                    {
                        Market.PrimaryContactGUID = null;
                    }
                    if (_territory != null && _territory.RegionGUID != null && _territory.RegionGUID != Guid.Empty)
                    {
                        Market.RegionGUID = _territory.RegionGUID;
                    }
                    else
                    {
                        Market.RegionGUID = null;
                    }
                    if (_territory != null && _territory.TerritoryGUID != Guid.Empty)
                    {
                        Market.TerritoryGUID = _territory.TerritoryGUID;
                    }
                    else
                    {
                        Market.TerritoryGUID = null;
                    }
                    Market.ParentID = dr["parentid"].ToString();
                    Market.TeritoryID = dr["marketid"].ToString();
                    Market.RMUserID = dr["regionalmanager_userid"].ToString();
                    Market.FMUserID = dr["fieldmanager_userid"].ToString();
                    Market.RegionName = dr["region"].ToString();
                    if (!string.IsNullOrEmpty(dr["regionalmanager_name"].ToString()))
                    {
                        string[] names = dr["regionalmanager_name"].ToString().Split(' ');
                        if (names.Length > 1)
                        {
                            Market.FirstName = names[0].ToString();
                            Market.LastName = names[1].ToString();
                        }
                        else
                        {
                            Market.FirstName = "";
                            Market.LastName = "";
                        }
                    }
                    else
                    {
                        Market.FirstName = "";
                        Market.LastName = "";
                    }
                    Market.MobilePhone = "";
                    Market.MarketPhone = dr["phone"].ToString();
                    Market.HomePhone = dr["phone"].ToString();
                    Market.Emails = dr["email"].ToString();
                    Market.AddressLine1 = dr["addr1"].ToString();
                    Market.AddressLine2 = dr["addr2"].ToString();
                    Market.City = dr["city"].ToString();
                    Market.State = dr["state"].ToString();
                    Market.Country = dr["country"].ToString();
                    Market.ZipCode = dr["postalcode"].ToString();
                    Market.IsDeleted = false;

                    Market.UpdatedDate = DateTime.UtcNow;

                    LatLong latLong = new LatLong();
                    latLong = GetLatLngCode(Market.AddressLine1, Market.AddressLine2, Market.City, Market.State, Market.Country, Market.ZipCode);
                    Market.TimeZone = getTimeZone(latLong.Latitude, latLong.Longitude).ToString();
                    Market.Latitude = latLong.Latitude;
                    Market.Longitude = latLong.Longitude;

                    //As per disscussion with kousik
                    var lWebClient = new WebClient();
                    string lTempData = String.Format(ConfigurationManager.AppSettings.Get("ClientStoreURL"), Market.MarketID);
                    lTempData = lWebClient.DownloadString(lTempData);
                    S_POSStoreResponse lObjPOSResp = new JavaScriptSerializer().Deserialize<S_POSStoreResponse>(lTempData);
                    bool UserCreated = false;
                    if (null == lObjPOSResp || !lObjPOSResp.store.apistatus.Equals("OK"))
                    {
                        //If this returns null, return not found error to the mobile
                    }
                    else
                    {
                        Market.StoreJSON = new JavaScriptSerializer().Serialize(lObjPOSResp);
                        Market.StoreJSON = Convert.ToBase64String(Encoding.UTF8.GetBytes(Market.StoreJSON));

                    }

                    if (_market == null)
                    {
                        Market.MarketGUID = Guid.NewGuid();
                        Market.CreateDate = DateTime.UtcNow;
                        result = _IMarketRepository.InsertMarket(Market);
                        // result = _IMarketRepository.Save();
                    }
                    else
                    {
                        Market.MarketGUID = _market.MarketGUID;
                        Market.CreateDate = _market.CreateDate;
                        result = _IMarketRepository.UpdateMarket(Market);
                        // result = _IMarketRepository.Save();
                    }
                    //no need to create user now, when userid is not available in the global user table
                    //if (result > 0)
                    //{
                    //    UserCreated = CreateUserByStoreJson(lObjPOSResp, Market.RegionGUID, Market.TerritoryGUID);
                    //}
                    return result;
                }
                else
                {
                    return result;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.InnerException.ToString());
                return result;
            }
        }
        public ActionResult Edit(ServicePointModel market)
        {
            Logger.Debug("Inside ServicePoint Controller- Create Http Post");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    DropdownValues();
                    if (ModelState.IsValid)
                    {
                        Market Market = new Market();
                        Market.MarketGUID = new Guid(market.MarketGUID);
                        Market.IsDefault = true;
                        Market.UserGUID = new Guid(market.UserGUID);
                        Market.EntityType = 0;
                        if (!string.IsNullOrEmpty(market.OrganizationGUID) && market.OrganizationGUID != Guid.Empty.ToString())
                        {
                            Market.OrganizationGUID = new Guid(market.OrganizationGUID);
                        }
                        else
                        {
                            Market.OrganizationGUID = null;
                        }
                        if (!string.IsNullOrEmpty(market.UserGUID) && market.UserGUID != Guid.Empty.ToString())
                        {
                            Market.OwnerGUID = new Guid(market.UserGUID);
                        }
                        else
                        {
                            Market.OwnerGUID = null;
                        }

                        Market.MarketName = market.MarketName;
                        if (!string.IsNullOrEmpty(market.UserGUID) && market.UserGUID != Guid.Empty.ToString())
                        {
                            Market.PrimaryContactGUID = new Guid(market.UserGUID);
                        }
                        else
                        {
                            Market.PrimaryContactGUID = null;
                        }

                        if (!string.IsNullOrEmpty(market.RegionGUID) && market.RegionGUID != Guid.Empty.ToString())
                        {
                            Market.RegionGUID = new Guid(market.RegionGUID);
                        }
                        else
                        {
                            Market.RegionGUID = null;
                        }

                        if (!string.IsNullOrEmpty(market.TerritoryGUID) && market.TerritoryGUID != Guid.Empty.ToString())
                        {
                            Market.TerritoryGUID = new Guid(market.TerritoryGUID);
                        }
                        else
                        {
                            Market.TerritoryGUID = null;
                        }

                        Market.FirstName = market.FirstName;
                        Market.LastName = market.LastName;
                        Market.MobilePhone = market.MobilePhone;
                        Market.MarketPhone = market.MarketPhone;
                        Market.HomePhone = market.HomePhone;
                        Market.Emails = market.Emails;
                        Market.AddressLine1 = market.AddressLine1;
                        Market.AddressLine2 = market.AddressLine2;
                        Market.City = market.City;
                        Market.State = market.State;
                        Market.Country = market.Country;
                        Market.ZipCode = market.ZipCode;
                        Market.IsDeleted = false;
                        Market.CreateDate = market.CreateDate;
                        Market.UpdatedDate = DateTime.UtcNow;

                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(Market.AddressLine1, Market.AddressLine2, Market.City, Market.State, Market.Country, Market.ZipCode);
                        Market.TimeZone = getTimeZone(latLong.Latitude, latLong.Longitude).ToString();
                        Market.Latitude = latLong.Latitude;
                        Market.Longitude = latLong.Longitude;
                        int marketUpdateResult = _IMarketRepository.UpdateMarket(Market);
                        //int marketUpdateResult = _IMarketRepository.Save();
                        if (marketUpdateResult > 0)
                        {
                            return RedirectToAction("Index");
                        }

                    }
                    return View(market);
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(market);
            }
        }
        public ActionResult Edit(MarketViewForCreate marketcreate)
        {
            Logger.Debug("Inside Place Controller- Edit Http Post");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    TempData["TabName"] = "Stores";
                    ViewBag.MarketName = !string.IsNullOrEmpty(marketcreate.MarketModel.MarketName) ? marketcreate.MarketModel.MarketName.ToString() : _IMarketRepository.GetMarketByID(new Guid(marketcreate.MarketModel.MarketGUID)).MarketName;
                    DropdownValues();
                    if (ModelState.IsValid)
                    {
                        MarketModel market = new MarketModel();
                        market = marketcreate.MarketModel;
                        Market Market = new Market();
                        Market.MarketGUID = new Guid(market.MarketGUID);
                        Market.MarketID = market.MarketID;
                        Market.IsDefault = true;
                        if (!string.IsNullOrEmpty(market.UserGUID) && market.UserGUID != Guid.Empty.ToString())
                        {
                            Market.UserGUID = new Guid(market.UserGUID);
                        }
                        else
                        {
                            Market.UserGUID = null;
                        }
                        Market.EntityType = market.EntityType;
                        if (!string.IsNullOrEmpty(market.OrganizationGUID) && market.OrganizationGUID != Guid.Empty.ToString())
                        {
                            Market.OrganizationGUID = new Guid(market.OrganizationGUID);
                        }
                        else
                        {
                            Market.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                        }
                        if (!string.IsNullOrEmpty(market.OwnerGUID) && market.OwnerGUID != Guid.Empty.ToString())
                        {
                            Market.OwnerGUID = new Guid(market.OwnerGUID);
                        }
                        else
                        {
                            Market.OwnerGUID = null;
                        }
                        Market.MarketName = market.MarketName;
                        if (!string.IsNullOrEmpty(market.PrimaryContactGUID) && market.PrimaryContactGUID != Guid.Empty.ToString())
                        {
                            Market.PrimaryContactGUID = new Guid(market.PrimaryContactGUID);
                        }
                        else
                        {
                            Market.PrimaryContactGUID = null;
                        }
                        if (!string.IsNullOrEmpty(market.RegionGUID) && market.RegionGUID != Guid.Empty.ToString())
                        {
                            Market.RegionGUID = new Guid(market.RegionGUID);
                            Region _region = _IRegionRepository.GetRegionByID(new Guid(market.RegionGUID));
                            if (_region != null)
                            {
                                Market.RegionName = _region.Name;
                            }
                        }
                        else
                        {
                            Market.RegionGUID = null;
                        }
                        if (!string.IsNullOrEmpty(market.TerritoryGUID) && market.TerritoryGUID != Guid.Empty.ToString())
                        {
                            Market.TerritoryGUID = new Guid(market.TerritoryGUID);
                            Territory _territory = _ITerritoryRepository.GetTerritoryByID(new Guid(market.TerritoryGUID));
                            if (_territory != null)
                            {
                                Market.TeritoryID = _territory.TerritoryID;
                            }
                        }
                        else
                        {
                            Market.TerritoryGUID = null;
                        }
                        if (!string.IsNullOrEmpty(market.RMUserGUID) && market.RMUserGUID != Guid.Empty.ToString())
                        {
                            GlobalUser _globalUser = _IGlobalUserRepository.GetGlobalUserByID(new Guid(market.RMUserGUID));
                            if (_globalUser != null)
                            {
                                Market.RMUserID = _globalUser.USERID;
                            }
                        }
                        if (!string.IsNullOrEmpty(market.FMUserGUID) && market.FMUserGUID != Guid.Empty.ToString())
                        {
                            GlobalUser _globalUser = _IGlobalUserRepository.GetGlobalUserByID(new Guid(market.FMUserGUID));
                            if (_globalUser != null)
                            {
                                Market.FMUserID = _globalUser.USERID;
                            }
                        }


                        Market.FirstName = market.FirstName;
                        Market.LastName = market.LastName;
                        Market.MobilePhone = market.MobilePhone;
                        Market.MarketPhone = market.MarketPhone;
                        Market.HomePhone = market.HomePhone;
                        Market.Emails = market.Emails;
                        Market.AddressLine1 = market.AddressLine1;
                        Market.AddressLine2 = market.AddressLine2;
                        Market.City = market.City;
                        Market.State = market.State;
                        Market.Country = market.Country;
                        Market.ZipCode = market.ZipCode;
                        Market.CreateDate = Convert.ToDateTime(market.CreateDate);
                        Market.UpdatedDate = DateTime.UtcNow;
                        Market.IsDeleted = false;

                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(Market.AddressLine1, Market.AddressLine2, Market.City, Market.State, Market.Country, Market.ZipCode);
                        Market.TimeZone = getTimeZone(latLong.Latitude, latLong.Longitude).ToString();
                        Market.Latitude = latLong.Latitude;
                        Market.Longitude = latLong.Longitude;


                        //As per disscussion with kousik
                        var lWebClient = new WebClient();
                        string lTempData = String.Format(ConfigurationManager.AppSettings.Get("ClientStoreURL"), Market.MarketID);
                        lTempData = lWebClient.DownloadString(lTempData);
                        S_POSStoreResponse lObjPOSResp = new JavaScriptSerializer().Deserialize<S_POSStoreResponse>(lTempData);
                        if (null == lObjPOSResp || !lObjPOSResp.store.apistatus.Equals("OK"))
                        {
                            //If this returns null, return not found error to the mobile
                        }
                        else
                        {
                            Market.StoreJSON = new JavaScriptSerializer().Serialize(lObjPOSResp);
                            Market.StoreJSON = Convert.ToBase64String(Encoding.UTF8.GetBytes(Market.StoreJSON));
                        }


                        int marketUpdateResult = _IMarketRepository.UpdateMarket(Market);
                        //int marketUpdateResult = _IMarketRepository.Save();
                        if (marketUpdateResult > 0)
                        {
                            return RedirectToAction("Index", "CustomerView", new { id = "Stores", customerid = Market.OwnerGUID.ToString() });
                        }
                        else
                        {
                            List<AspUser> RMUserList = new List<AspUser>();
                            var appUser = _IUserProfileRepository.GetUserProfilesbyOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString()), "ENT_U_RM").OrderBy(sort => sort.FirstName).ToList();
                            //if (string.IsNullOrEmpty(id))
                            {
                                RMUserList.Add(new AspUser { FirstName = "None", LastName = "", UserGUID = Guid.Empty.ToString(), OrganizationGUID = "" });
                                foreach (var user in appUser.ToList())
                                {
                                    RMUserList.Add(new AspUser { FirstName = user.FirstName, LastName = user.LastName, UserGUID = user.UserGUID.ToString() });
                                }
                            }
                            List<AspUser> FMUserList = new List<AspUser>();
                            var appUserFM = _IUserProfileRepository.GetUserProfilesbyOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString()), "ENT_U").OrderBy(sort => sort.FirstName).ToList();
                            //if (string.IsNullOrEmpty(id))
                            {
                                FMUserList.Add(new AspUser { FirstName = "None", LastName = "", UserGUID = Guid.Empty.ToString(), OrganizationGUID = "" });
                                foreach (var user in appUserFM.ToList())
                                {
                                    FMUserList.Add(new AspUser { FirstName = user.FirstName, LastName = user.LastName, UserGUID = user.UserGUID.ToString() });
                                }
                            }

                            marketcreate.RMUser = RMUserList.AsEnumerable();
                            marketcreate.FMUser = FMUserList.AsEnumerable();

                            return View(marketcreate);
                        }

                    }
                    else
                    {
                        List<AspUser> RMUserList = new List<AspUser>();
                        var appUser = _IUserProfileRepository.GetUserProfilesbyOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString()), "ENT_U_RM").OrderBy(sort => sort.FirstName).ToList();
                        //if (string.IsNullOrEmpty(id))
                        {
                            RMUserList.Add(new AspUser { FirstName = "None", LastName = "", UserGUID = Guid.Empty.ToString(), OrganizationGUID = "" });
                            foreach (var user in appUser.ToList())
                            {
                                RMUserList.Add(new AspUser { FirstName = user.FirstName, LastName = user.LastName, UserGUID = user.UserGUID.ToString() });
                            }
                        }
                        List<AspUser> FMUserList = new List<AspUser>();
                        var appUserFM = _IUserProfileRepository.GetUserProfilesbyOrganizationGUID(new Guid(Session["OrganizationGUID"].ToString()), "ENT_U").OrderBy(sort => sort.FirstName).ToList();
                        //if (string.IsNullOrEmpty(id))
                        {
                            FMUserList.Add(new AspUser { FirstName = "None", LastName = "", UserGUID = Guid.Empty.ToString(), OrganizationGUID = "" });
                            foreach (var user in appUserFM.ToList())
                            {
                                FMUserList.Add(new AspUser { FirstName = user.FirstName, LastName = user.LastName, UserGUID = user.UserGUID.ToString() });
                            }
                        }
                        marketcreate.RMUser = RMUserList.AsEnumerable();
                        marketcreate.FMUser = FMUserList.AsEnumerable();
                        return View(marketcreate);
                    }
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return RedirectToAction("Login", "User");
            }
        }
예제 #42
0
        public ActionResult Edit(AspUser user, string GroupGUID, string RegionGUID, string TerritoryGUID, string RoleGUID)
        {
            Logger.Debug("Inside User Controller- Edit HttpPost");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    DropdownValues();
                    ViewBag.UserName = user.UserName;
                    string oldpassword = _IUserRepository.DecodeFrom64(_IGlobalUserRepository.GetPassword(new Guid(user.UserGUID)));
                    if (ModelState.IsValid)
                    {
                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(user.AddressLine1, user.AddressLine2, user.City, user.State, user.Country, user.ZipCode);
                        GlobalUser globalUser = new GlobalUser();
                        globalUser.UserGUID = new Guid(user.UserGUID);
                        globalUser.USERID = !string.IsNullOrEmpty(user.UserID) ? user.UserID.Trim() : "";
                        globalUser.Role_Id = RoleGUID;
                        globalUser.UserName = !string.IsNullOrEmpty(user.UserName) ? user.UserName.Trim() : "";
                        globalUser.Password = _IUserRepository.EncodeTo64(user.PasswordHash);
                        globalUser.IsActive = true;
                        globalUser.IsDelete = false;
                        globalUser.Latitude = latLong.Latitude;
                        globalUser.Longitude = latLong.Longitude;
                        globalUser.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            globalUser.LastModifiedBy = new Guid(Session["UserGUID"].ToString());




                        if (_IGlobalUserRepository.GetRole(globalUser.Role_Id).UserType == "ENT_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "WIM_A" && r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }
                        else if (_IGlobalUserRepository.GetRole(globalUser.Role_Id).UserType == "WIM_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }

                        UserProfile userprofile = new UserProfile();
                        userprofile.ProfileGUID = new Guid(user.ProfileGUID);
                        userprofile.UserGUID = new Guid(user.UserGUID);
                        userprofile.CompanyName = user.CompanyName;
                        userprofile.FirstName = !string.IsNullOrEmpty(user.FirstName) ? user.FirstName.Trim() : "";
                        userprofile.LastName = !string.IsNullOrEmpty(user.LastName) ? user.LastName.Trim() : "";
                        userprofile.MobilePhone = user.MobilePhone;
                        userprofile.BusinessPhone = user.BusinessPhone;
                        userprofile.HomePhone = user.HomePhone;
                        userprofile.EmailID = !string.IsNullOrEmpty(user.EmailID) ? user.EmailID.Trim() : "";
                        userprofile.AddressLine1 = user.AddressLine1;
                        userprofile.AddressLine2 = user.AddressLine2;
                        userprofile.City = user.City;
                        userprofile.State = user.State;
                        userprofile.Country = user.Country;
                        userprofile.Latitude = latLong.Latitude;
                        userprofile.Longitude = latLong.Longitude;
                        userprofile.ZipCode = user.ZipCode;
                        userprofile.IsDeleted = false;
                        userprofile.PicFileURL = user.ImageURL;
                        userprofile.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            userprofile.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                        AspNetUser aspnetuser = new AspNetUser();
                        aspnetuser.Id = user.UserGUID;
                        aspnetuser.UserName = !string.IsNullOrEmpty(user.UserName) ? user.UserName.Trim() : "";
                        aspnetuser.FirstName = !string.IsNullOrEmpty(user.FirstName) ? user.FirstName.Trim() : "";
                        aspnetuser.LastName = !string.IsNullOrEmpty(user.LastName) ? user.LastName.Trim() : "";
                        aspnetuser.PasswordHash = _IUserRepository.EncodeTo64(user.PasswordHash);
                        aspnetuser.PhoneNumber = user.MobilePhone;
                        aspnetuser.EmailID = !string.IsNullOrEmpty(user.EmailID) ? user.EmailID.Trim() : "";
                        aspnetuser.OrganizationGUID = new Guid(user.OrganizationGUID);
                        aspnetuser.SecurityStamp = "";
                        aspnetuser.Discriminator = "";

                        OrganizationUsersMap organizationUserMap = new OrganizationUsersMap();
                        organizationUserMap.OrganizationUserMapGUID = new Guid(user.OrganizationUserMapGUID);
                        organizationUserMap.OrganizationGUID = new Guid(user.OrganizationGUID);
                        organizationUserMap.UserGUID = globalUser.UserGUID;
                        organizationUserMap.IsContractor = false;
                        organizationUserMap.IsActive = true;
                        organizationUserMap.Status = 0;
                        if (!string.IsNullOrEmpty(user.RegionGUID) && user.RegionGUID != Guid.Empty.ToString())
                        {
                            organizationUserMap.RegionGUID = new Guid(user.RegionGUID);
                        }
                        else
                        {
                            organizationUserMap.RegionGUID = null;
                        }
                        if (!string.IsNullOrEmpty(user.TerritoryGUID) && user.TerritoryGUID != Guid.Empty.ToString())
                        {
                            organizationUserMap.TerritoryGUID = new Guid(user.TerritoryGUID);
                        }
                        else
                        {
                            organizationUserMap.TerritoryGUID = null;
                        }

                        organizationUserMap.UserType = "ENT_A";
                        organizationUserMap.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.CreateBy = new Guid(Session["UserGUID"].ToString());
                        organizationUserMap.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.LastModifiedBy = new Guid(Session["UserGUID"].ToString());



                        int userresult = _IUserRepository.UpdateUser(aspnetuser);
                        //int userresult = _IUserRepository.Save();
                        if (userresult > 0)
                        {
                            int guresult = _IGlobalUserRepository.UpdateGlobalUser(globalUser);
                            //int guresult = _IGlobalUserRepository.Save();
                            if (guresult > 0)
                            {
                                int usrresult = _IUserProfileRepository.UpdateUserProfile(userprofile);
                                //int usrresult = _IUserProfileRepository.Save();
                                if (usrresult > 0)
                                {

                                    if (_IOrganizationRepository.UpdateOrganizationUserMap(organizationUserMap) > 0)
                                    {
                                        if (oldpassword != user.PasswordHash)
                                        {
                                            TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Password Changed Successfully');</script>";
                                            if (user.UserGUID == Session["UserGUID"].ToString())
                                                return RedirectToAction("../User/Login");
                                            else
                                                return RedirectToAction("Index", "MyCompany", new { id = "Users" });
                                        }
                                        else if (Session["UserType"] != null && Session["UserType"].ToString() == "SFT_A")
                                        {
                                            return RedirectToAction("Index", "Organization");
                                        }
                                        else if (Session["UserType"] != null && Session["UserType"].ToString() == "ENT_A")
                                        {
                                            return RedirectToAction("Index", "MyCompany", new { id = "Users" });
                                        }
                                        else
                                        {
                                            return RedirectToAction("Dashboard", "User");
                                        }
                                    }

                                }
                            }
                        }
                    }
                    else
                    {

                        if (Session["UserType"] != null && Session["UserType"].ToString() == "ENT_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "WIM_A" && r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }
                        else if (Session["UserType"] != null && Session["UserType"].ToString() == "WIM_A")
                        {
                            var RoleDetails = _IGlobalUserRepository.GetRoles().ToList().Where(r => r.UserType != "IND_C").OrderBy(r => r.Name).Select(r => new SelectListItem
                            {
                                Value = r.Id.ToString(),
                                Text = r.Name
                            });
                            ViewBag.RoleDetails = new SelectList(RoleDetails, "Value", "Text");
                        }
                        var TerritoryDetails = _ITerritoryRepository.GetTerritoryByRegionGUID(new Guid(RegionGUID)).ToList().OrderBy(r => r.Name).Select(r => new SelectListItem
                        {
                            Value = r.TerritoryGUID.ToString(),
                            Text = r.Name
                        });
                        ViewBag.TerritoryDetails = new SelectList(TerritoryDetails, "Value", "Text");
                    }
                    return View(user);

                }
                else
                {
                    //TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Session Expired');</script>";
                    //return RedirectToAction("../User/Login");
                    return RedirectToAction("SessionTimeOut", "User");
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(user);
            }
        }
예제 #43
0
        public ActionResult Create(AspUser user, string GroupGUID, string RegionGUID, string TerritoryGUID, string RoleGUID)
        {
            Logger.Debug("Inside User Controller- Create HttpPost");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    DropdownValues();
                    ViewBag.OrganizationName = _IOrganizationRepository.GetOrganizationByID(new Guid(Session["OrganizationGUID"].ToString())).OrganizationFullName;
                    if (ModelState.IsValid)
                    {
                        OrganizationSubscription orgSubscription = _IOrganizationSubscriptionRepository.GetOrganizationSubscriptionByOrgID(new Guid(Session["OrganizationGUID"].ToString()));
                        // if (orgSubscription.SubscriptionPurchased > orgSubscription.SubscriptionConsumed)
                        {
                            GlobalUser aspuser = _IUserRepository.GlobalUserLogin(user.UserName, Session["OrganizationGUID"].ToString());
                            GlobalUser aUser = _IGlobalUserRepository.GetGlobalUserByUserID(user.UserID, Session["OrganizationGUID"].ToString());
                            if (aspuser == null && aUser == null)
                            {
                                LatLong latLong = new LatLong();
                                latLong = GetLatLngCode(user.AddressLine1, user.AddressLine2, user.City, user.State, user.Country, user.ZipCode);
                                GlobalUser globalUser = new GlobalUser();
                                globalUser.UserGUID = Guid.NewGuid();
                                globalUser.USERID = user.UserID;
                                globalUser.Role_Id = RoleGUID;
                                globalUser.UserName = !string.IsNullOrEmpty(user.UserName) ? user.UserName.Trim() : "";
                                globalUser.Password = _IUserRepository.EncodeTo64(user.PasswordHash);
                                globalUser.IsActive = true;
                                globalUser.IsDelete = false;
                                globalUser.Latitude = latLong.Latitude;
                                globalUser.Longitude = latLong.Longitude;
                                globalUser.CreateDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    globalUser.CreateBy = new Guid(Session["UserGUID"].ToString());
                                globalUser.LastModifiedDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    globalUser.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                                OrganizationUsersMap organizationUserMap = new OrganizationUsersMap();
                                organizationUserMap.OrganizationUserMapGUID = Guid.NewGuid();
                                organizationUserMap.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                organizationUserMap.UserGUID = globalUser.UserGUID;
                                organizationUserMap.IsContractor = false;
                                organizationUserMap.IsActive = true;
                                organizationUserMap.Status = 0;

                                if (!string.IsNullOrEmpty(RegionGUID) && RegionGUID != Guid.Empty.ToString())
                                {
                                    organizationUserMap.RegionGUID = new Guid(RegionGUID);
                                }
                                else
                                {
                                    organizationUserMap.RegionGUID = null;
                                }
                                if (!string.IsNullOrEmpty(TerritoryGUID) && TerritoryGUID != Guid.Empty.ToString())
                                {
                                    organizationUserMap.TerritoryGUID = new Guid(TerritoryGUID);
                                }
                                else
                                {
                                    organizationUserMap.TerritoryGUID = null;
                                }


                                organizationUserMap.UserType = "ENT_A";
                                organizationUserMap.CreateDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    organizationUserMap.CreateBy = new Guid(Session["UserGUID"].ToString());
                                organizationUserMap.LastModifiedDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    organizationUserMap.LastModifiedBy = new Guid(Session["UserGUID"].ToString());


                                UserProfile userprofile = new UserProfile();
                                userprofile.ProfileGUID = Guid.NewGuid();
                                userprofile.UserGUID = globalUser.UserGUID;
                                userprofile.CompanyName = _IOrganizationRepository.GetOrganizationByID(new Guid(Session["OrganizationGUID"].ToString())).OrganizationFullName;
                                userprofile.FirstName = !string.IsNullOrEmpty(user.FirstName) ? user.FirstName.Trim() : "";
                                userprofile.LastName = !string.IsNullOrEmpty(user.LastName) ? user.LastName.Trim() : "";
                                userprofile.MobilePhone = user.MobilePhone;
                                userprofile.BusinessPhone = user.BusinessPhone;
                                userprofile.HomePhone = user.HomePhone;
                                userprofile.EmailID = !string.IsNullOrEmpty(user.EmailID) ? user.EmailID.Trim() : "";
                                userprofile.AddressLine1 = user.AddressLine1;
                                userprofile.AddressLine2 = user.AddressLine2;
                                userprofile.City = user.City;
                                userprofile.State = user.State;
                                userprofile.Country = user.Country;
                                userprofile.Latitude = latLong.Latitude;
                                userprofile.Longitude = latLong.Longitude;
                                userprofile.ZipCode = user.ZipCode;
                                userprofile.IsDeleted = false;
                                userprofile.PicFileURL = user.ImageURL;
                                userprofile.LastModifiedDate = DateTime.UtcNow;
                                if (Session["UserGUID"] != null)
                                    userprofile.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                                AspNetUser aspnetuser = new AspNetUser();
                                aspnetuser.Id = globalUser.UserGUID.ToString();
                                aspnetuser.UserName = !string.IsNullOrEmpty(user.UserName) ? user.UserName.Trim() : "";
                                aspnetuser.FirstName = !string.IsNullOrEmpty(user.FirstName) ? user.FirstName.Trim() : "";
                                aspnetuser.LastName = !string.IsNullOrEmpty(user.LastName) ? user.LastName.Trim() : "";
                                aspnetuser.PasswordHash = _IUserRepository.EncodeTo64(user.PasswordHash);
                                aspnetuser.PhoneNumber = user.MobilePhone;
                                aspnetuser.EmailID = !string.IsNullOrEmpty(user.EmailID) ? user.EmailID.Trim() : "";
                                aspnetuser.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                                aspnetuser.SecurityStamp = "";
                                aspnetuser.Discriminator = "";


                                UserSubscription userSubscription = new UserSubscription();
                                if (orgSubscription != null)
                                {

                                    userSubscription.UserSubscriptionGUID = Guid.NewGuid();
                                    userSubscription.UserGUID = globalUser.UserGUID;
                                    userSubscription.OrganizationSubscriptionGUID = orgSubscription.OrganizationSubscriptionGUID;
                                    userSubscription.IsActive = true;
                                    userSubscription.CreatedDate = DateTime.UtcNow;
                                }

                                int userresult = _IUserRepository.InsertUser(aspnetuser);
                                //int userresult = _IUserRepository.Save();
                                if (userresult > 0)
                                {
                                    int guresult = _IGlobalUserRepository.InsertGlobalUser(globalUser);
                                    //int guresult = _IGlobalUserRepository.Save();
                                    if (guresult > 0)
                                    {
                                        int usrresult = _IUserProfileRepository.InsertUserProfile(userprofile);
                                        //int usrresult = _IUserProfileRepository.Save();
                                        if (usrresult > 0)
                                        {
                                            int uSubscriptionResult = _IUserSubscriptionRepository.InsertUserSubscription(userSubscription);
                                            //int uSubscriptionResult = _IUserSubscriptionRepository.Save();
                                            if (uSubscriptionResult > 0)
                                            {
                                                int orgusermap = _IOrganizationRepository.InsertOrganizationUserMap(organizationUserMap);
                                                //int orgusermap = _IOrganizationRepository.Save();
                                                if (orgusermap > 0)
                                                {
                                                    orgSubscription.SubscriptionConsumed = orgSubscription.SubscriptionConsumed + 1;
                                                    _IOrganizationSubscriptionRepository.UpdateOrganizationSubscription(orgSubscription);
                                                    //_IOrganizationSubscriptionRepository.Save();
                                                    return RedirectToAction("Index", "MyCompany", new { id = "Users" });
                                                }
                                                else
                                                {
                                                    _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                                    //_IUserSubscriptionRepository.Save();
                                                    _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                                    // _IUserProfileRepository.Save();
                                                    _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                                    //_IGlobalUserRepository.Save();
                                                    _IUserRepository.DeleteUser(aspnetuser.Id);
                                                    //_IUserRepository.Save();
                                                }
                                            }
                                            else
                                            {
                                                _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                                // _IUserProfileRepository.Save();
                                                _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                                //_IGlobalUserRepository.Save();
                                                _IUserRepository.DeleteUser(aspnetuser.Id);
                                                // _IUserRepository.Save();
                                            }

                                        }
                                        else
                                        {
                                            _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                            //_IGlobalUserRepository.Save();
                                            _IUserRepository.DeleteUser(aspnetuser.Id);
                                            //_IUserRepository.Save();
                                        }
                                    }
                                    else
                                    {
                                        _IUserRepository.DeleteUser(aspnetuser.Id);
                                        // _IUserRepository.Save();
                                    }
                                }
                                else
                                {
                                    _IUserRepository.DeleteUser(aspnetuser.Id);
                                    // _IUserRepository.Save();
                                }
                            }
                            else if (aspuser != null)
                            {
                                //UserName already exists for this Organization
                                TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','User Aleady Exists');</script>";
                            }
                            else if (aUser != null)
                            {
                                //UserID already exists for this Organization
                                TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','UserID is Aleady Exists');</script>";
                            }
                        }
                    }
                    else
                    {
                        var TerritoryDetails = _ITerritoryRepository.GetTerritoryByRegionGUID(new Guid(RegionGUID)).ToList().OrderBy(r => r.Name).Select(r => new SelectListItem
                        {
                            Value = r.TerritoryGUID.ToString(),
                            Text = r.Name
                        });
                        ViewBag.TerritoryDetails = new SelectList(TerritoryDetails, "Value", "Text");

                    }

                    return View(user);
                }
                else
                {
                    //TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Session Expired');</script>";
                    //return RedirectToAction("../User/Login");
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(user);
            }
        }
예제 #44
0
            //O(n)
            public LatLong BaseGetClosestPoint(LatLong from, List<LatLong> list)
            {
                double min = double.MaxValue;
                LatLong closests = null;
                foreach (var p in list)
                {
                    var d = MathTool.Distance(from, p);
                    if (d >= min)
                        continue;

                    // update
                    min = d;
                    closests = p;
                }
                return closests;
            }
예제 #45
0
        public ActionResult Edit(PlaceModel place)
        {
            Logger.Debug("Inside Place Controller- Edit Http Post");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    if (ModelState.IsValid)
                    {
                        Place Place = new Place();
                        Place.PlaceGUID = new Guid(place.PlaceGUID);
                        Place.PlaceID = place.PlaceID;
                        Place.UserGUID = new Guid(place.UserGUID);
                        if (!string.IsNullOrEmpty(place.OrganizationGUID) && place.OrganizationGUID != Guid.Empty.ToString())
                        {
                            Place.OrganizationGUID = new Guid(place.OrganizationGUID);
                        }
                        else
                        {
                            Place.OrganizationGUID = null;
                        }
                        Place.PlaceName = place.PlaceName;
                        Place.FirstName = place.FirstName;
                        Place.LastName = place.LastName;
                        Place.MobilePhone = place.MobilePhone;
                        Place.PlacePhone = place.PlacePhone;
                        Place.HomePhone = place.HomePhone;
                        Place.Emails = place.Emails;
                        Place.AddressLine1 = place.AddressLine1;
                        Place.AddressLine2 = place.AddressLine2;
                        Place.City = place.City;
                        Place.State = place.State;
                        Place.Country = place.Country;
                        Place.ZipCode = place.ZipCode;
                        Place.UpdatedDate = DateTime.UtcNow;
                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(Place.AddressLine1, Place.AddressLine2, Place.City, Place.State, Place.Country, Place.ZipCode);
                        Place.TimeZone = getTimeZone(latLong.Latitude, latLong.Longitude).ToString();

                        int placeInsertResult = _IPlaceRepository.UpdatePlace(Place);
                        //int placeInsertResult = _IPlaceRepository.Save();
                        if (placeInsertResult > 0)
                        {
                            return RedirectToAction("Index");
                        }
                        else
                        {
                            return View(place);
                        }
                    }
                    return View(place);
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(place);
            }
        }
예제 #46
0
 public static bool DistWithin(LatLong a, LatLong b, double d)
 {
     // var dist = Distance(a, b);
     var dist = StraightLineDistance(a.Latitude, a.Longitude, b.Latitude, b.Longitude);
     return dist < d;
 }
예제 #47
0
            //O(n)
            public static LatLong BaseGetCentroidFromCluster(List<LatLong> list)
            {
                int count = list.Count;
                if (list == null || count == 0)
                    return null;

                // color is set for the points and the cluster point here
                LatLong centroid = new LatLong(0, 0) { Size = list.Count };//O(1)
                foreach (LatLong p in list)
                {
                    centroid.Latitude += p.Latitude;
                    centroid.Longitude += p.Longitude;
                }
                centroid.Latitude /= count;
                centroid.Longitude /= count;
                var cp = new LatLong(centroid.Latitude, centroid.Longitude) { Size = count };

                return cp;
            }
예제 #48
0
        private async Task ExecuteFarmingPokestopsAndPokemons(Client client)
        {
            var mapObjects = await client.GetMapObjects();

            FortData[] rawPokeStops = mapObjects.MapCells.SelectMany(i => i.Forts).Where(i => i.Type == FortType.Checkpoint && i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime()).ToArray();
            if (rawPokeStops == null || rawPokeStops.Count() <= 0)
            {
                ColoredConsoleWrite(Color.Red, $"No PokeStops to visit here, please stop the bot and change your location.");
                return;
            }
            pokeStops = rawPokeStops;
            UpdateMap();
            ColoredConsoleWrite(Color.Cyan, $"Finding fastest route through all PokeStops..");
            LatLong startingLatLong = new LatLong(ClientSettings.DefaultLatitude, ClientSettings.DefaultLongitude);
            pokeStops = RouteOptimizer.Optimize(rawPokeStops, startingLatLong, pokestopsOverlay);
            wildPokemons = mapObjects.MapCells.SelectMany(i => i.WildPokemons);
            if (!ForceUnbanning && !Stopping)
                ColoredConsoleWrite(Color.Cyan, $"Visiting {pokeStops.Count()} PokeStops");

            UpdateMap();
            foreach (var pokeStop in pokeStops)
            {
                if (ForceUnbanning || Stopping)
                    break;

                FarmingStops = true;
                await locationManager.update(pokeStop.Latitude, pokeStop.Longitude);
                UpdatePlayerLocation(pokeStop.Latitude, pokeStop.Longitude);
                UpdateMap();

                var fortInfo = await client.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);
                var fortSearch = await client.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);
                StringWriter PokeStopOutput = new StringWriter();
                PokeStopOutput.Write($"");
                if (fortInfo.Name != string.Empty)
                    PokeStopOutput.Write("PokeStop: " + fortInfo.Name);
                if (fortSearch.ExperienceAwarded != 0)
                    PokeStopOutput.Write($", XP: {fortSearch.ExperienceAwarded}");
                if (fortSearch.GemsAwarded != 0)
                    PokeStopOutput.Write($", Gems: {fortSearch.GemsAwarded}");
                if (fortSearch.PokemonDataEgg != null)
                    PokeStopOutput.Write($", Eggs: {fortSearch.PokemonDataEgg}");
                if (GetFriendlyItemsString(fortSearch.ItemsAwarded) != string.Empty)
                    PokeStopOutput.Write($", Items: {GetFriendlyItemsString(fortSearch.ItemsAwarded)} ");
                ColoredConsoleWrite(Color.Cyan, PokeStopOutput.ToString());

                if (fortSearch.ExperienceAwarded != 0)
                    TotalExperience += (fortSearch.ExperienceAwarded);

                pokeStop.CooldownCompleteTimestampMs = DateTime.UtcNow.ToUnixTime() + 300000;

                if (ClientSettings.CatchPokemon)
                    await ExecuteCatchAllNearbyPokemons(client);
            }
            FarmingStops = false;
            if (!ForceUnbanning && !Stopping)
            {
                client.RecycleItems(client);
                await ExecuteFarmingPokestopsAndPokemons(client);
            }
        }
예제 #49
0
            void RunAlgo()
            {
                // Init clusters
                var centroids = BaseGetRandomCentroids(BaseDataset, _InitClusterSize);
                for (int i = 0; i < centroids.Length; i++)
                {
                    var pid = i.ToString();
                    var newbucket = new Bucket(pid) { Centroid = centroids[i] };
                    BaseBucketsLookup.Add(pid, newbucket);
                }

                //
                double currentMaxError = double.MaxValue;
                while (currentMaxError > MAX_ERROR && BaseBucketsLookup.Count < _MaxClusters)
                {
                    RunIterationsUntilKClusterPlacementAreDone();

                    var id = BaseGetMaxError();
                    var bucket = BaseBucketsLookup[id];
                    currentMaxError = bucket.ErrorLevel; //update
                    if (currentMaxError > MAX_ERROR)
                    {
                        // Here it is linear speed when putting one new centroid at a time
                        // should be semi-fast because the new point is inserted at best area
                        //from current centroids view.
                        // possible improvement exists by log2 search by inserting multiple centroids and
                        // reducing centroid again if needed

                        // put new centroid in area where maxError but farthest away from current centroid in area
                        var longest = BaseGetLongestPoint(bucket.Centroid, bucket.Points);
                        var newcentroid = new LatLong(longest);
                        var newid = BaseBucketsLookup.Count.ToString();
                        var newbucket = new Bucket(newid) { Centroid = newcentroid };
                        BaseBucketsLookup.Add(newid, newbucket);
                    }
                }
            }
 /// <summary>
 /// Convert latitude and longitude in degrees to a locator
 /// </summary>
 /// <param name="ll">LatLong structure to convert</param>
 /// <param name="Ext">Extra precision (0, 1, 2)</param>
 /// <returns>Locator string</returns>
 public static string LatLongToLocator(LatLong ll, int Ext)
 {
     return LatLongToLocator(ll.Lat, ll.Long, Ext);
 }
예제 #51
0
            //O(n)
            public LatLong BaseGetLongestPoint(LatLong from, List<LatLong> list)
            {
                double max = -double.MaxValue;
                LatLong longest = null;
                foreach (var p in list)
                {
                    var d = MathTool.Distance(from, p);
                    if (d <= max)
                        continue;

                    // update
                    max = d;
                    longest = p;
                }
                return longest;
            }
        public ActionResult EditOrg(mycompany mycompany)
        {
            Logger.Debug("Inside Organization Controller- Edit HttpPost");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    if (ModelState.IsValid)
                    {
                        if (mycompany.OrganizationEditView != null)
                        {
                            OrganizationEditView organization = mycompany.OrganizationEditView;

                            Organization Organization = new Organization();
                            Organization.OrganizationFullName = organization.OrganizationFullName;
                            Organization.OrganizationName = organization.OrganizationFullName.Trim();
                            Organization.OrganizationGUID = organization.OrganizationGUID;
                            Organization.Website = organization.Website;
                            Organization.Phone = organization.Phone;
                            // Organization.TimeZone = organization.TimeZone;
                            Organization.AddressLine1 = organization.AddressLine1;
                            Organization.AddressLine2 = organization.AddressLine2;
                            Organization.ImageURL = organization.ImageURL;
                            Organization.City = organization.City;
                            Organization.Country = organization.Country;
                            Organization.State = organization.State;
                            Organization.ZipCode = organization.ZipCode;
                            Organization.EmailID = organization.EmailID;
                            Organization.IsActive = organization.IsActive;
                            Organization.IsDeleted = organization.IsDeleted;
                            Organization.AllowContractors = true;
                            Organization.CreateDate = organization.CreatedDate;
                            Organization.CreateBy = organization.CreateBy;
                            Organization.LastModifiedDate = DateTime.UtcNow;
                            if (Session["UserGUID"] != null)
                                Organization.LastModifiedBy = new Guid(Session["UserGUID"].ToString());


                            LatLong latLong = new LatLong();
                            latLong = GetLatLngCode(Organization.AddressLine1, Organization.AddressLine2, Organization.City, Organization.State, Organization.Country, Organization.ZipCode);
                            Organization.TimeZone = Convert.ToDouble(getTimeZone(latLong.Latitude, latLong.Longitude));


                            if (_IOrganizationRepository.UpdateOrganization(Organization) > 0)
                            {
                                return RedirectToAction("Index", "MyCompany");
                            }
                            else
                            {
                                TempData["TabName"] = "Details";
                                mycompany.AspNetUserViewModel = UserDetails();

                                mycompany.RegionViewModel = RegionDetails();

                                mycompany.TerritoryViewModel = TerritoryDetails();
                                return View("Index", mycompany);
                            }
                        }
                        else
                        {
                            return RedirectToAction("Index", "MyCompany");
                        }

                    }
                    else
                    {
                        TempData["TabName"] = "Details";
                        mycompany.AspNetUserViewModel = UserDetails();

                        mycompany.RegionViewModel = RegionDetails();

                        mycompany.TerritoryViewModel = TerritoryDetails();
                        return View("Index", mycompany);
                    }
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(mycompany);
            }
        }
 public QueryDto()
 {
     Pickup = new LatLong();
     Dropoff = new LatLong();
 }
        public int UserCreate(AspUser user)
        {
            Logger.Debug("Inside CustomerView Controller- UserCreate");
            int result = 0;
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    OrganizationSubscription orgSubscription = _IOrganizationSubscriptionRepository.GetOrganizationSubscriptionByOrgID(new Guid(Session["OrganizationGUID"].ToString()));
                    //if (orgSubscription.SubscriptionPurchased > orgSubscription.SubscriptionConsumed)
                    GlobalUser aspuser = _IUserRepository.GlobalUserLogin(user.UserName, Session["OrganizationGUID"].ToString());
                    if (aspuser == null)
                    {
                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(user.AddressLine1, user.AddressLine2, user.City, user.State, user.Country, user.ZipCode);
                        GlobalUser globalUser = new GlobalUser();
                        globalUser.UserGUID = Guid.NewGuid();
                        globalUser.USERID = user.UserID;
                        globalUser.Role_Id = user.RoleGUID;
                        globalUser.UserName = user.UserName;
                        globalUser.Password = _IUserRepository.EncodeTo64(user.PasswordHash);
                        globalUser.IsActive = true;
                        globalUser.IsDelete = false;
                        globalUser.Latitude = latLong.Latitude;
                        globalUser.Longitude = latLong.Longitude;
                        globalUser.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            globalUser.CreateBy = new Guid(Session["UserGUID"].ToString());
                        globalUser.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            globalUser.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                        OrganizationUsersMap organizationUserMap = new OrganizationUsersMap();
                        organizationUserMap.OrganizationUserMapGUID = Guid.NewGuid();
                        organizationUserMap.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                        organizationUserMap.UserGUID = globalUser.UserGUID;
                        organizationUserMap.IsContractor = false;
                        organizationUserMap.IsActive = true;
                        organizationUserMap.Status = 0;

                        if (!string.IsNullOrEmpty(user.RegionGUID) && user.RegionGUID != Guid.Empty.ToString())
                        {
                            organizationUserMap.RegionGUID = new Guid(user.RegionGUID);
                        }
                        else
                        {
                            organizationUserMap.RegionGUID = null;
                        }
                        if (!string.IsNullOrEmpty(user.TerritoryGUID) && user.TerritoryGUID != Guid.Empty.ToString())
                        {
                            organizationUserMap.TerritoryGUID = new Guid(user.TerritoryGUID);
                        }
                        else
                        {
                            organizationUserMap.TerritoryGUID = null;
                        }


                        organizationUserMap.UserType = "ENT_A";
                        organizationUserMap.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.CreateBy = new Guid(Session["UserGUID"].ToString());
                        organizationUserMap.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.LastModifiedBy = new Guid(Session["UserGUID"].ToString());


                        UserProfile userprofile = new UserProfile();
                        userprofile.ProfileGUID = Guid.NewGuid();
                        userprofile.UserGUID = globalUser.UserGUID;
                        userprofile.CompanyName = _IOrganizationRepository.GetOrganizationByID(new Guid(Session["OrganizationGUID"].ToString())).OrganizationFullName;
                        userprofile.FirstName = user.FirstName;
                        userprofile.LastName = user.LastName;
                        userprofile.MobilePhone = user.MobilePhone;
                        userprofile.BusinessPhone = user.BusinessPhone;
                        userprofile.HomePhone = user.HomePhone;
                        userprofile.EmailID = user.EmailID;
                        userprofile.AddressLine1 = user.AddressLine1;
                        userprofile.AddressLine2 = user.AddressLine2;
                        userprofile.City = user.City;
                        userprofile.State = user.State;
                        userprofile.Country = user.Country;
                        userprofile.Latitude = latLong.Latitude;
                        userprofile.Longitude = latLong.Longitude;
                        userprofile.ZipCode = user.ZipCode;
                        userprofile.IsDeleted = false;
                        userprofile.PicFileURL = user.ImageURL;
                        userprofile.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            userprofile.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                        AspNetUser aspnetuser = new AspNetUser();
                        aspnetuser.Id = globalUser.UserGUID.ToString();
                        aspnetuser.UserName = user.UserName;
                        aspnetuser.FirstName = user.FirstName;
                        aspnetuser.LastName = user.LastName;
                        aspnetuser.PasswordHash = _IUserRepository.EncodeTo64(user.PasswordHash);
                        aspnetuser.PhoneNumber = user.MobilePhone;
                        aspnetuser.EmailID = user.EmailID;
                        aspnetuser.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                        aspnetuser.SecurityStamp = "";
                        aspnetuser.Discriminator = "";


                        UserSubscription userSubscription = new UserSubscription();
                        if (orgSubscription != null)
                        {

                            userSubscription.UserSubscriptionGUID = Guid.NewGuid();
                            userSubscription.UserGUID = globalUser.UserGUID;
                            userSubscription.OrganizationSubscriptionGUID = orgSubscription.OrganizationSubscriptionGUID;
                            userSubscription.IsActive = true;
                            userSubscription.CreatedDate = DateTime.UtcNow;
                        }

                        int userresult = _IUserRepository.InsertUser(aspnetuser);
                        //int userresult = _IUserRepository.Save();
                        if (userresult > 0)
                        {
                            int guresult = _IGlobalUserRepository.InsertGlobalUser(globalUser);
                            //int guresult = _IGlobalUserRepository.Save();
                            if (guresult > 0)
                            {
                                int usrresult = _IUserProfileRepository.InsertUserProfile(userprofile);
                                // int usrresult = _IUserProfileRepository.Save();
                                if (usrresult > 0)
                                {
                                    int uSubscriptionResult = _IUserSubscriptionRepository.InsertUserSubscription(userSubscription);
                                    //int uSubscriptionResult = _IUserSubscriptionRepository.Save();
                                    if (uSubscriptionResult > 0)
                                    {
                                        int orgusermap = _IOrganizationRepository.InsertOrganizationUserMap(organizationUserMap);
                                        //int orgusermap = _IOrganizationRepository.Save();
                                        if (orgusermap > 0)
                                        {
                                            orgSubscription.SubscriptionConsumed = orgSubscription.SubscriptionConsumed + 1;
                                            result = _IOrganizationSubscriptionRepository.UpdateOrganizationSubscriptionCount(orgSubscription);
                                        }
                                        else
                                        {
                                            _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                            //_IUserSubscriptionRepository.Save();
                                            _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                            //_IUserProfileRepository.Save();
                                            _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                            //_IGlobalUserRepository.Save();
                                            _IUserRepository.DeleteUser(aspnetuser.Id);
                                            // _IUserRepository.Save();
                                        }
                                    }
                                    else
                                    {
                                        _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                        // _IUserProfileRepository.Save();
                                        _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                        //_IGlobalUserRepository.Save();
                                        _IUserRepository.DeleteUser(aspnetuser.Id);
                                        // _IUserRepository.Save();
                                    }

                                }
                                else
                                {
                                    _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                    //_IGlobalUserRepository.Save();
                                    _IUserRepository.DeleteUser(aspnetuser.Id);
                                    //_IUserRepository.Save();
                                }
                            }
                            else
                            {
                                _IUserRepository.DeleteUser(aspnetuser.Id);
                                // _IUserRepository.Save();
                            }
                        }
                        else
                        {
                            _IUserRepository.DeleteUser(aspnetuser.Id);
                            //_IUserRepository.Save();
                        }
                    }
                    return result;
                }
                else
                {
                    return result;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return 0;
            }
        }
        public ActionResult Create(OrganizationView organization)
        {
            Logger.Debug("Inside Organization Controller- Create HttpPost");
            try
            {
                if (ModelState.IsValid)
                {
                    if (_IOrganizationRepository.GetOrganizationByID(organization.OrganizationGUID) == null)
                    {
                        Organization Organization = new Organization();
                        Organization.OrganizationFullName = organization.OrganizationFullName;
                        Organization.OrganizationName = organization.OrganizationFullName.Trim();
                        Organization.OrganizationGUID = Guid.NewGuid();
                        Organization.Website = organization.Website;
                        Organization.Phone = organization.Phone;
                        Organization.AddressLine1 = organization.AddressLine1;
                        Organization.AddressLine2 = organization.AddressLine2;
                        Organization.City = organization.City;
                        Organization.Country = organization.Country;
                        Organization.ZipCode = organization.ZipCode;
                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(Organization.AddressLine1, Organization.AddressLine2, Organization.City, Organization.State, Organization.Country, Organization.ZipCode);
                        Organization.TimeZone = Convert.ToDouble(getTimeZone(latLong.Latitude, latLong.Longitude));
                        Organization.Latitude = latLong.Latitude;
                        Organization.Longitude = latLong.Longitude;
                        Organization.EmailID = organization.EmailID;
                        Organization.State = organization.State;
                        Organization.IsActive = false;
                        Organization.IsDeleted = false;
                        Organization.AllowContractors = true;
                        Organization.ImageURL = organization.ImageURL;
                        Organization.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            Organization.CreateBy = new Guid(Session["UserGUID"].ToString());
                        Organization.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            Organization.LastModifiedBy = new Guid(Session["UserGUID"].ToString());
                        //Group Group = new Group();
                        //Group.GroupGUID = Guid.NewGuid();
                        //Group.Name = "Default";
                        //Group.Description = "Default";
                        //Group.OrganizationGUID = Organization.OrganizationGUID;
                        //Group.IsDefault = false;

                        Region Region = new Region();
                        Region.RegionGUID = Guid.NewGuid();
                        Region.Name = "Default";
                        Region.Description = "Default";
                        if (Organization.OrganizationGUID != Guid.Empty)
                        {
                            Region.OrganizationGUID = Organization.OrganizationGUID;
                        }
                        else
                        {
                            Region.OrganizationGUID = null;
                        }
                        Region.IsDefault = false;

                        Territory Territory = new Territory();
                        Territory.TerritoryGUID = Guid.NewGuid();
                        if (Territory.RegionGUID != Guid.Empty)
                        {
                            Territory.RegionGUID = Territory.RegionGUID;
                        }
                        else
                        {
                            Territory.RegionGUID = null;
                        }
                        Territory.Name = "Default";
                        Territory.Description = "Default";
                        if (Organization.OrganizationGUID != Guid.Empty)
                        {
                            Territory.OrganizationGUID = Organization.OrganizationGUID;
                        }
                        else
                        {
                            Territory.OrganizationGUID = null;
                        }
                        Territory.IsDefault = false;




                        GlobalUser globalUser = new GlobalUser();
                        globalUser.UserGUID = Guid.NewGuid();
                        globalUser.USERID = organization.UserID;
                        globalUser.UserName = organization.UserName;
                        globalUser.Password = _IUserRepository.EncodeTo64(organization.Password);
                        globalUser.IsActive = true;
                        globalUser.IsDelete = false;
                        globalUser.Latitude = latLong.Latitude;
                        globalUser.Longitude = latLong.Longitude;
                        globalUser.Role_Id = _IGlobalUserRepository.GetOrganizationAdminRoleID();
                        globalUser.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            globalUser.CreateBy = new Guid(Session["UserGUID"].ToString());
                        globalUser.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            globalUser.LastModifiedBy = new Guid(Session["UserGUID"].ToString());

                        UserProfile userprofile = new UserProfile();
                        userprofile.ProfileGUID = Guid.NewGuid();
                        userprofile.UserGUID = globalUser.UserGUID;
                        userprofile.CompanyName = Organization.OrganizationFullName;
                        userprofile.FirstName = organization.FirstName;
                        userprofile.LastName = organization.LastName;
                        userprofile.MobilePhone = "";
                        userprofile.BusinessPhone = organization.Phone;
                        userprofile.HomePhone = "";
                        userprofile.EmailID = organization.EmailID;
                        userprofile.AddressLine1 = organization.AddressLine1;
                        userprofile.AddressLine2 = organization.AddressLine2;
                        userprofile.City = organization.City;
                        userprofile.State = organization.State;
                        userprofile.Country = organization.Country;
                        userprofile.Latitude = latLong.Latitude;
                        userprofile.Longitude = latLong.Longitude;
                        userprofile.ZipCode = organization.ZipCode;
                        userprofile.IsDeleted = false;
                        userprofile.PicFileURL = Organization.ImageURL;
                        userprofile.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            userprofile.LastModifiedBy = new Guid(Session["UserGUID"].ToString());


                        userprofile.CompanyName = Organization.OrganizationName;

                        AspNetUser aspnetuser = new AspNetUser();
                        aspnetuser.Id = globalUser.UserGUID.ToString();
                        aspnetuser.UserName = organization.UserName;
                        aspnetuser.FirstName = organization.FirstName;
                        aspnetuser.LastName = organization.LastName;
                        aspnetuser.PasswordHash = _IUserRepository.EncodeTo64(organization.Password);
                        aspnetuser.PhoneNumber = organization.Phone;
                        aspnetuser.EmailID = organization.EmailID;
                        if (Organization.OrganizationGUID != Guid.Empty)
                        {
                            aspnetuser.OrganizationGUID = Organization.OrganizationGUID;
                        }
                        else
                        {
                            aspnetuser.OrganizationGUID = null;
                        }
                        aspnetuser.SecurityStamp = "";
                        aspnetuser.Discriminator = "";

                        OrganizationSubscription organizationSubscription = new OrganizationSubscription();
                        organizationSubscription.OrganizationSubscriptionGUID = Guid.NewGuid();
                        organizationSubscription.OrganizationGUID = Organization.OrganizationGUID;
                        organizationSubscription.IsActive = true;
                        organizationSubscription.Version = 1;
                        organizationSubscription.SubscriptionPurchased = 100;
                        organizationSubscription.SubscriptionConsumed = 1;
                        organizationSubscription.StartDate = DateTime.UtcNow;
                        organizationSubscription.ExpiryDate = DateTime.UtcNow.AddDays(30);
                        organizationSubscription.CreatedDate = DateTime.UtcNow;


                        UserSubscription userSubscription = new UserSubscription();
                        userSubscription.UserSubscriptionGUID = Guid.NewGuid();
                        userSubscription.UserGUID = globalUser.UserGUID;
                        if (organizationSubscription.OrganizationSubscriptionGUID != Guid.Empty)
                        {
                            userSubscription.OrganizationSubscriptionGUID = organizationSubscription.OrganizationSubscriptionGUID;
                        }
                        else
                        {
                            userSubscription.OrganizationSubscriptionGUID = null;
                        }

                        userSubscription.IsActive = true;
                        userSubscription.CreatedDate = DateTime.UtcNow;

                        Market Market = new Market();
                        Market.MarketGUID = Guid.NewGuid();
                        Market.IsDefault = true;
                        if (globalUser.UserGUID != Guid.Empty)
                        {
                            Market.UserGUID = globalUser.UserGUID;
                        }
                        else
                        {
                            Market.UserGUID = null;
                        }
                        Market.EntityType = 0;
                        if (Organization.OrganizationGUID != Guid.Empty)
                        {
                            Market.OrganizationGUID = Organization.OrganizationGUID;
                        }
                        else
                        {
                            Market.OrganizationGUID = null;
                        }
                        if (Organization.OrganizationGUID != Guid.Empty)
                        {
                            Market.OwnerGUID = Organization.OrganizationGUID;
                        }
                        else
                        {
                            Market.OwnerGUID = null;
                        }
                        Market.MarketName = Organization.OrganizationFullName;
                        if (Region.RegionGUID != Guid.Empty)
                        {
                            Market.RegionGUID = Region.RegionGUID;
                        }
                        else
                        {
                            Market.RegionGUID = null;
                        }
                        if (Territory.TerritoryGUID != Guid.Empty)
                        {
                            Market.TerritoryGUID = Territory.TerritoryGUID;
                        }
                        else
                        {
                            Market.TerritoryGUID = null;
                        }
                        if (globalUser.UserGUID != Guid.Empty)
                        {
                            Market.PrimaryContactGUID = globalUser.UserGUID;
                        }
                        else
                        {
                            Market.PrimaryContactGUID = null;
                        }
                        Market.FirstName = organization.FirstName;
                        Market.LastName = organization.LastName;
                        Market.MobilePhone = "";
                        Market.MarketPhone = organization.Phone;
                        Market.HomePhone = "";
                        Market.Emails = organization.EmailID;
                        Market.TimeZone = Organization.TimeZone.ToString();
                        Market.AddressLine1 = organization.AddressLine1;
                        Market.AddressLine2 = organization.AddressLine2;
                        Market.City = organization.City;
                        Market.State = organization.State;
                        Market.Country = organization.Country;
                        Market.ZipCode = organization.ZipCode;
                        Market.Latitude = latLong.Latitude;
                        Market.Longitude = latLong.Longitude;
                        Market.ImageURL = organization.ImageURL;
                        Market.IsDeleted = false;
                        Market.CreateDate = DateTime.UtcNow;
                        Market.UpdatedDate = DateTime.UtcNow;

                        OrganizationUsersMap organizationUserMap = new OrganizationUsersMap();
                        organizationUserMap.OrganizationUserMapGUID = Guid.NewGuid();
                        organizationUserMap.OrganizationGUID = Organization.OrganizationGUID;
                        organizationUserMap.UserGUID = globalUser.UserGUID;
                        organizationUserMap.IsContractor = false;
                        organizationUserMap.IsActive = true;
                        organizationUserMap.Status = 0;
                        if (Region.RegionGUID != Guid.Empty)
                        {
                            organizationUserMap.RegionGUID = Region.RegionGUID;
                        }
                        else
                        {
                            organizationUserMap.RegionGUID = null;
                        }
                        if (Territory.TerritoryGUID != Guid.Empty)
                        {
                            organizationUserMap.TerritoryGUID = Territory.TerritoryGUID;
                        }
                        else
                        {
                            organizationUserMap.TerritoryGUID = null;
                        }
                        organizationUserMap.UserType = "ENT_A";
                        organizationUserMap.CreateDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.CreateBy = new Guid(Session["UserGUID"].ToString());
                        organizationUserMap.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            organizationUserMap.LastModifiedBy = new Guid(Session["UserGUID"].ToString());



                        int result = _IOrganizationRepository.InsertOrganization(Organization);
                        // int result = _IOrganizationRepository.Save();
                        if (result > 0)
                        {
                            _IOrganizationSubscriptionRepository.InsertOrganizationSubscription(organizationSubscription);
                            //_IOrganizationSubscriptionRepository.Save();
                            //_IGroupRepository.InsertGroup(Group);
                            //_IGroupRepository.Save();
                            _IRegionRepository.InsertRegion(Region);
                            //_IRegionRepository.Save();
                            _ITerritoryRepository.InsertTerritory(Territory);
                            // _ITerritoryRepository.Save();

                            int userresult = _IUserRepository.InsertUser(aspnetuser);
                            // int userresult = _IUserRepository.Save();
                            if (userresult > 0)
                            {
                                int guresult = _IGlobalUserRepository.InsertGlobalUser(globalUser);
                                //int guresult = _IGlobalUserRepository.Save();

                                if (guresult > 0)
                                {
                                    int OrgUserMap = _IOrganizationRepository.InsertOrganizationUserMap(organizationUserMap);
                                    //int OrgUserMap = _IOrganizationRepository.Save();
                                    if (OrgUserMap > 0)
                                    {
                                        int usrresult = _IUserProfileRepository.InsertUserProfile(userprofile);
                                        //int usrresult = _IUserProfileRepository.Save();
                                        if (usrresult > 0)
                                        {
                                            int usubresult = _IUserSubscriptionRepository.InsertUserSubscription(userSubscription);
                                            //int usubresult = _IUserSubscriptionRepository.Save();
                                            if (usubresult > 0)
                                            {
                                                int marketresult = _IMarketRepository.InsertMarket(Market);
                                                //int marketresult = _IMarketRepository.Save();
                                                if (marketresult > 0)
                                                {
                                                    if (Session["UserType"] != null && Session["UserType"].ToString() == "WIM_A")
                                                    {
                                                        TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Organization Created Successfully');</script>";
                                                        return RedirectToAction("Index", "Organization");
                                                    }
                                                    else
                                                    {
                                                        TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Organization Created Successfully');</script>";
                                                        return RedirectToAction("../User/Login");
                                                    }
                                                }
                                                else
                                                {
                                                    _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                                    //_IUserSubscriptionRepository.Save();
                                                    //_IGroupRepository.DeleteGroup(Group.GroupGUID);
                                                    //_IGroupRepository.Save();
                                                    _ITerritoryRepository.DeleteTerritoryByRegionGUID(Region.RegionGUID);
                                                    //_ITerritoryRepository.Save();
                                                    _IRegionRepository.DeleteRegion(Region.RegionGUID);
                                                    //_IRegionRepository.Save();


                                                    _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                                    //_IUserSubscriptionRepository.Save();
                                                    _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                                    //_IUserProfileRepository.Save();
                                                    _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                                    //_IGlobalUserRepository.Save();
                                                    _IUserRepository.DeleteUser(aspnetuser.Id);
                                                    // _IUserRepository.Save();
                                                }
                                            }
                                            else
                                            {
                                                //_IGroupRepository.DeleteGroup(Group.GroupGUID);
                                                //_IGroupRepository.Save();
                                                _ITerritoryRepository.DeleteTerritoryByRegionGUID(Region.RegionGUID);
                                                //_ITerritoryRepository.Save();
                                                _IRegionRepository.DeleteRegion(Region.RegionGUID);
                                                // _IRegionRepository.Save();


                                                _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                                //_IUserSubscriptionRepository.Save();
                                                _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                                //_IUserProfileRepository.Save();
                                                _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                                //_IGlobalUserRepository.Save();
                                                _IUserRepository.DeleteUser(aspnetuser.Id);
                                                //_IUserRepository.Save();

                                                _IOrganizationSubscriptionRepository.DeleteOrganizationSubscription(organizationSubscription.OrganizationSubscriptionGUID);
                                                //_IOrganizationSubscriptionRepository.Save();
                                                //_IUserSubscriptionRepository.Save();
                                                _IOrganizationRepository.DeleteOrganization(Organization.OrganizationGUID);
                                                //_IOrganizationRepository.Save();
                                            }
                                        }
                                        else
                                        {
                                            _IOrganizationRepository.DeleteOrganizationUserMap(organizationUserMap.OrganizationUserMapGUID);
                                            //_IOrganizationRepository.Save();
                                            _ITerritoryRepository.DeleteTerritoryByRegionGUID(Region.RegionGUID);
                                            //_ITerritoryRepository.Save();
                                            _IRegionRepository.DeleteRegion(Region.RegionGUID);
                                            //_IRegionRepository.Save();


                                            _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                            //_IUserSubscriptionRepository.Save();
                                            _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                            //_IUserProfileRepository.Save();
                                            _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                            //_IGlobalUserRepository.Save();
                                            _IUserRepository.DeleteUser(aspnetuser.Id);
                                            //_IUserRepository.Save();

                                            _IOrganizationSubscriptionRepository.DeleteOrganizationSubscription(organizationSubscription.OrganizationSubscriptionGUID);
                                            //_IOrganizationSubscriptionRepository.Save();
                                            //_IUserSubscriptionRepository.Save();
                                            _IOrganizationRepository.DeleteOrganization(Organization.OrganizationGUID);
                                            //_IOrganizationRepository.Save();
                                        }
                                    }
                                    else
                                    {
                                        //_IGroupRepository.DeleteGroup(Group.GroupGUID);
                                        //_IGroupRepository.Save();
                                        _ITerritoryRepository.DeleteTerritoryByRegionGUID(Region.RegionGUID);
                                        //_ITerritoryRepository.Save();
                                        _IRegionRepository.DeleteRegion(Region.RegionGUID);
                                        // _IRegionRepository.Save();


                                        _IUserSubscriptionRepository.DeleteUserSubscription(userSubscription.UserSubscriptionGUID);
                                        //_IUserSubscriptionRepository.Save();
                                        _IUserProfileRepository.DeleteUserProfile(userprofile.ProfileGUID);
                                        // _IUserProfileRepository.Save();
                                        _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                        //_IGlobalUserRepository.Save();
                                        _IUserRepository.DeleteUser(aspnetuser.Id);
                                        //_IUserRepository.Save();

                                        _IOrganizationSubscriptionRepository.DeleteOrganizationSubscription(organizationSubscription.OrganizationSubscriptionGUID);
                                        //_IOrganizationSubscriptionRepository.Save();
                                        //_IUserSubscriptionRepository.Save();
                                        _IOrganizationRepository.DeleteOrganization(Organization.OrganizationGUID);
                                        //_IOrganizationRepository.Save();
                                    }
                                }
                                else
                                {
                                    _IGlobalUserRepository.DeleteGlobalUser(globalUser.UserGUID);
                                    //_IGlobalUserRepository.Save();
                                    _IUserRepository.DeleteUser(aspnetuser.Id);
                                    // _IUserRepository.Save();
                                    _IOrganizationRepository.DeleteOrganization(Organization.OrganizationGUID);
                                    //_IOrganizationRepository.Save();
                                }
                            }
                            else
                            {
                                _IUserRepository.DeleteUser(aspnetuser.Id);
                                // _IUserRepository.Save();
                                _IOrganizationSubscriptionRepository.DeleteOrganizationSubscription(organizationSubscription.OrganizationSubscriptionGUID);
                                //_IOrganizationSubscriptionRepository.Save();
                                _IOrganizationRepository.DeleteOrganization(Organization.OrganizationGUID);
                                // _IOrganizationRepository.Save();
                            }
                        }
                        else
                        {
                            _IOrganizationRepository.DeleteOrganization(Organization.OrganizationGUID);
                            //_IOrganizationRepository.Save();
                        }
                    }
                    else
                    {
                        //UserName already exists
                        TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Organization Name is Aleady Exists');</script>";
                    }
                }
                return View(organization);

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(organization);
            }
        }
        public ActionResult Edit(OrganizationEditView organization)
        {
            Logger.Debug("Inside Organization Controller- Edit HttpPost");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    if (ModelState.IsValid)
                    {
                        Organization Organization = new Organization();
                        Organization.OrganizationFullName = organization.OrganizationFullName;
                        Organization.OrganizationName = organization.OrganizationFullName.Trim();
                        Organization.OrganizationGUID = organization.OrganizationGUID;
                        Organization.Website = organization.Website;
                        Organization.Phone = organization.Phone;
                        // Organization.TimeZone = organization.TimeZone;
                        Organization.AddressLine1 = organization.AddressLine1;
                        Organization.AddressLine2 = organization.AddressLine2;
                        Organization.ImageURL = organization.ImageURL;
                        Organization.City = organization.City;
                        Organization.Country = organization.Country;
                        Organization.State = organization.State;
                        Organization.ZipCode = organization.ZipCode;
                        Organization.EmailID = organization.EmailID;
                        Organization.IsActive = organization.IsActive;
                        Organization.IsDeleted = organization.IsDeleted;
                        Organization.AllowContractors = true;
                        Organization.CreateDate = organization.CreatedDate;
                        Organization.CreateBy = organization.CreateBy;
                        Organization.LastModifiedDate = DateTime.UtcNow;
                        if (Session["UserGUID"] != null)
                            Organization.LastModifiedBy = new Guid(Session["UserGUID"].ToString());


                        LatLong latLong = new LatLong();
                        latLong = GetLatLngCode(Organization.AddressLine1, Organization.AddressLine2, Organization.City, Organization.State, Organization.Country, Organization.ZipCode);
                        Organization.TimeZone = Convert.ToDouble(getTimeZone(latLong.Latitude, latLong.Longitude));

                        _IOrganizationRepository.UpdateOrganization(Organization);
                        //_IOrganizationRepository.Save();
                        return RedirectToAction("Index");
                    }
                    // else
                    {
                        return View(organization);
                    }
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(organization);
            }
        }
예제 #57
0
        public ActionResult Create(PlaceModel place)
        {
            Logger.Debug("Inside Place Controller- Create Http Post");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    if (ModelState.IsValid)
                    {
                        Place _place = _IPlaceRepository.GetPlaceByID(place.PlaceID, new Guid(Session["OrganizationGUID"].ToString()));
                        if (_place == null)
                        {
                            Place Place = new Place();
                            Place.PlaceGUID = Guid.NewGuid();
                            Place.UserGUID = new Guid(Session["UserGUID"].ToString());
                            Place.OrganizationGUID = new Guid(Session["OrganizationGUID"].ToString());
                            Place.PlaceID = place.PlaceID;
                            Place.PlaceName = place.PlaceName;
                            Place.FirstName = place.FirstName;
                            Place.LastName = place.LastName;
                            Place.MobilePhone = place.MobilePhone;
                            Place.PlacePhone = place.PlacePhone;
                            Place.HomePhone = place.HomePhone;
                            Place.Emails = place.Emails;
                            Place.AddressLine1 = place.AddressLine1;
                            Place.AddressLine2 = place.AddressLine2;
                            Place.City = place.City;
                            Place.State = place.State;
                            Place.Country = place.Country;
                            Place.ZipCode = place.ZipCode;
                            Place.CategoryID = 0;
                            Place.IsDeleted = false;
                            Place.CreateDate = DateTime.UtcNow;
                            Place.UpdatedDate = DateTime.UtcNow;
                            LatLong latLong = new LatLong();
                            latLong = GetLatLngCode(Place.AddressLine1, Place.AddressLine2, Place.City, Place.State, Place.Country, Place.ZipCode);
                            Place.TimeZone = getTimeZone(latLong.Latitude, latLong.Longitude).ToString();

                            Person People = new Person();
                            People.PeopleGUID = Guid.NewGuid();
                            People.UserGUID = Place.UserGUID;
                            People.OrganizationGUID = Place.OrganizationGUID;
                            People.IsPrimaryContact = true;
                            People.PlaceGUID = Place.PlaceGUID;
                            People.FirstName = place.FirstName;
                            People.LastName = place.LastName;
                            People.MobilePhone = place.MobilePhone;
                            People.CompanyName = place.PlaceName;
                            People.BusinessPhone = place.PlacePhone;
                            People.HomePhone = place.HomePhone;
                            People.Emails = place.Emails;
                            People.AddressLine1 = place.AddressLine1;
                            People.AddressLine2 = place.AddressLine2;
                            People.City = place.City;
                            People.State = place.State;
                            People.Country = place.Country;
                            People.ZipCode = place.ZipCode;
                            People.CategoryID = 0;
                            People.IsDeleted = false;
                            People.CreatedDate = DateTime.UtcNow;
                            People.UpdatedDate = DateTime.UtcNow;

                            //Market Market = new Market();
                            //Market.MarketGUID = Guid.NewGuid();
                            //Market.IsDefault = true;
                            //Market.UserGUID = Place.UserGUID;
                            //Market.EntityType = 1;
                            //Market.OrganizationGUID = Place.OrganizationGUID;
                            //Market.OwnerGUID = Place.PlaceGUID;
                            //Market.MarketName = Place.PlaceName;
                            //Market.PrimaryContactGUID = People.PeopleGUID;
                            //Market.FirstName = place.FirstName;
                            //Market.LastName = place.LastName;
                            //Market.MobilePhone = place.MobilePhone;
                            //Market.MarketPhone = place.PlacePhone;
                            //Market.HomePhone = place.HomePhone;
                            //Market.Emails = place.Emails;
                            //Market.AddressLine1 = place.AddressLine1;
                            //Market.AddressLine2 = place.AddressLine2;
                            //Market.City = place.City;
                            //Market.State = place.State;
                            //Market.Country = place.Country;
                            //Market.ZipCode = place.ZipCode;
                            //Market.IsDeleted = false;
                            //Market.CreateDate = DateTime.UtcNow;
                            //Market.UpdatedDate = DateTime.UtcNow;

                            int placeInsertResult = _IPlaceRepository.InsertPlace(Place);
                            //int placeInsertResult = _IPlaceRepository.Save();
                            if (placeInsertResult > 0)
                            {
                                int peopleInsertResult = _IPeopleRepository.InsertPeople(People);
                                // int peopleInsertResult = _IPeopleRepository.Save();
                                if (peopleInsertResult > 0)
                                {
                                    //_IMarketRepository.InsertMarket(Market);
                                    //int marketInsertResult = _IMarketRepository.Save();
                                    //if (marketInsertResult > 0)
                                    //{
                                    return RedirectToAction("Index");
                                    //}
                                    //else
                                    //{
                                    //    _IMarketRepository.DeleteMarket(Market.MarketGUID);
                                    //    _IMarketRepository.Save();
                                    //    _IPeopleRepository.DeletePeople(People.PeopleGUID);
                                    //    _IPeopleRepository.Save();
                                    //    _IPlaceRepository.DeletePlace(Place.PlaceGUID);
                                    //    _IPlaceRepository.Save();
                                    //}
                                }
                                else
                                {
                                    _IPeopleRepository.DeletePeople(People.PeopleGUID);
                                    // _IPeopleRepository.Save();
                                    _IPlaceRepository.DeletePlace(Place.PlaceGUID);
                                    //_IPlaceRepository.Save();
                                }
                            }
                            else
                            {
                                _IPlaceRepository.DeletePlace(Place.PlaceGUID);
                                // _IPlaceRepository.Save();
                            }
                        }
                        else
                        {
                            TempData["msg"] = "<script>ModalPopupsAlert('Workers-In-Motion','Client ID already configured');</script>";
                            return View(place);
                        }
                    }
                    else
                    {
                        return View(place);
                    }
                    return View();
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(place);
            }
        }
        public ActionResult EditCustomer(customerview pcustomerview)
        {
            Logger.Debug("Inside Place Controller- Edit Http Post");
            try
            {
                if (Session["OrganizationGUID"] != null)
                {
                    if (ModelState.IsValid)
                    {
                        if (pcustomerview.PlaceModel != null)
                        {
                            Place Place = new Place();
                            Place.PlaceGUID = new Guid(pcustomerview.PlaceModel.PlaceGUID);
                            Place.UserGUID = new Guid(pcustomerview.PlaceModel.UserGUID);
                            Place.PlaceID = pcustomerview.PlaceModel.PlaceID;
                            Place.OrganizationGUID = !string.IsNullOrEmpty(pcustomerview.PlaceModel.OrganizationGUID) ? new Guid(pcustomerview.PlaceModel.OrganizationGUID) : Guid.Empty;
                            Place.PlaceName = pcustomerview.PlaceModel.PlaceName;
                            Place.FirstName = pcustomerview.PlaceModel.FirstName;
                            Place.LastName = pcustomerview.PlaceModel.LastName;
                            Place.MobilePhone = pcustomerview.PlaceModel.MobilePhone;
                            Place.PlacePhone = pcustomerview.PlaceModel.PlacePhone;
                            Place.HomePhone = pcustomerview.PlaceModel.HomePhone;
                            Place.Emails = pcustomerview.PlaceModel.Emails;
                            Place.AddressLine1 = pcustomerview.PlaceModel.AddressLine1;
                            Place.AddressLine2 = pcustomerview.PlaceModel.AddressLine2;
                            Place.City = pcustomerview.PlaceModel.City;
                            Place.State = pcustomerview.PlaceModel.State;
                            Place.Country = pcustomerview.PlaceModel.Country;
                            Place.ZipCode = pcustomerview.PlaceModel.ZipCode;
                            Place.UpdatedDate = DateTime.UtcNow;
                            LatLong latLong = new LatLong();
                            latLong = GetLatLngCode(Place.AddressLine1, Place.AddressLine2, Place.City, Place.State, Place.Country, Place.ZipCode);
                            Place.TimeZone = getTimeZone(latLong.Latitude, latLong.Longitude).ToString();

                            int placeInsertResult = _IPlaceRepository.UpdatePlace(Place);
                            // int placeInsertResult = _IPlaceRepository.Save();
                            if (placeInsertResult > 0)
                            {
                                //return RedirectToAction("Index", "CustomerView", new { id = "Details", customerid = Place.PlaceGUID.ToString() });
                                return RedirectToAction("Index", "Place");
                            }
                            else
                            {
                                TempData["TabName"] = "Details";
                                pcustomerview.PeopleViewModel = ContactDetails(pcustomerview.PlaceModel.PlaceGUID);
                                pcustomerview.MarketViewModel = CustomerStopDetails(pcustomerview.PlaceModel.PlaceGUID);
                            }
                        }
                    }
                    else
                    {
                        TempData["TabName"] = "Details";
                        pcustomerview.PeopleViewModel = ContactDetails(pcustomerview.PlaceModel.PlaceGUID);
                        pcustomerview.MarketViewModel = CustomerStopDetails(pcustomerview.PlaceModel.PlaceGUID);

                    }
                    return View("Index", pcustomerview);
                }
                else
                {
                    return RedirectToAction("SessionTimeOut", "User");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return View(pcustomerview);
            }
        }
 /// <summary>
 /// Convert latitude and longitude in degrees to a locator
 /// </summary>
 /// <param name="ll">LatLong structure to convert</param>
 /// <returns>Locator string</returns>
 public static string LatLongToLocator(LatLong ll)
 {
     return LatLongToLocator(ll.Lat, ll.Long, 0);
 }
예제 #60
0
            //O(k?? random fn can be slow, but is not slow because atm the k is always 1)
            public static LatLong[] BaseGetRandomCentroids(List<LatLong> list, int k)
            {
                var set = new HashSet<LatLong>();
                int i = 0;
                var kcentroids = new LatLong[k];

                int MAX = list.Count;
                while (MAX >= k)
                {
                    int index = Rand.Next(0, MAX - 1);
                    var xy = list[index];
                    if (set.Contains(xy))
                        continue;

                    set.Add(xy);
                    kcentroids[i++] = new LatLong(xy.Latitude, xy.Longitude);

                    if (i >= k)
                        break;
                }
                return kcentroids;
            }