public IEnumerable<Weather> GetForecast(Location location)
        {
            string rawJson;

            string appid = WebConfigurationManager.AppSettings["owmKey"];

            var requestUriString = String.Format("http://api.openweathermap.org/data/2.5/forecast?lat={0}&lon={1}&appid={2}&units=metric", location.Latitude, location.Longitude, appid);

            var request = (HttpWebRequest)WebRequest.Create(requestUriString);

            using (var response = request.GetResponse())
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                rawJson = reader.ReadToEnd();
            }

            JObject results = JObject.Parse(rawJson);
            var Forecasts = new List<Weather>();

            foreach (var result in results["list"])
            {
                int locationID = location.LocationID;
                string Period = (string)result["dt_txt"];
                string temp = (string)result["main"]["temp"];
                string symbol = (string)result["weather"][0]["icon"];
                string rainfall;

                // Rain and snow is not included in every places so this is my hack for it.

                try
                {
                    rainfall = (string)result["rain"]["3h"];
                }
                catch
                {
                    rainfall = "0";
                }

                string wind = (string)result["wind"]["speed"];
                string degrees = (string)result["wind"]["deg"];
                string description = (string)result["weather"][0]["description"];
                Forecasts.Add(new Weather(locationID, Period, symbol, temp, rainfall, wind, degrees, description));
            }

            return Forecasts;
        }
Exemple #2
0
        public Location[] GetLocationsForSection(long section, out long QueryExecutedTime)
        {
            DateTime start = DateTime.Now;
            QueryExecutedTime = DateTime.Now.ToUniversalTime().Ticks;
            try
            {

                //IQueryable<DBLocation> queryResults = from l in db.DBLocations where ((double)section) == l.Z select l;
                IList<DBLocation> locations = db.SectionLocationsAndLinks(section);
                //List<DBLocation> locations = queryResults.ToList<DBLocation>();

                Debug.WriteLine(section.ToString() + ": Query: " + new TimeSpan(DateTime.Now.Ticks - start.Ticks).TotalMilliseconds);

                Location[] retList = new Location[locations.Count];

                Debug.WriteLine(section.ToString() + ": To list: " + new TimeSpan(DateTime.Now.Ticks - start.Ticks).TotalMilliseconds);
                for(int i = 0; i < locations.Count; i++)
                {
                    retList[i] = new Location(locations[i]);
                }

                Debug.WriteLine(section.ToString() + ": Loop: " + new TimeSpan(DateTime.Now.Ticks - start.Ticks).TotalMilliseconds);

                return retList;
            }
            catch (System.ArgumentNullException)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find locations for section: " + section.ToString());
            }
            catch (System.InvalidOperationException e)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find locations for section: " + section.ToString());
            }

            return new Location[0];
        }
Exemple #3
0
        public Location[] GetLocationsForStructure(long structureID)
        {
            try
            {
                IQueryable<DBLocation> queryResults = from l in db.DBLocations where (l.ParentID == structureID) select l;
                List<Location> retList = new List<Location>(queryResults.Count());
                foreach (DBLocation dbl in queryResults)
                {
                    Location loc = new Location(dbl);
                    retList.Add(loc);
                }
                return retList.ToArray();
            }
            catch (System.ArgumentNullException)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find locations for ID: " + structureID.ToString());
            }
            catch (System.InvalidOperationException e)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find locations for ID: " + structureID.ToString());
            }

            return new Location[0];
        }
Exemple #4
0
        public Location[] GetLocationChanges(long section, long ModifiedAfterThisUtcTime,  out long QueryExecutedTime, out long[] DeletedIDs)
        {
            DateTime start = DateTime.Now;
            TimeSpan elapsed;

            DateTime? ModifiedAfterThisTime = new DateTime?();
            if(ModifiedAfterThisUtcTime > 0)
                ModifiedAfterThisTime = new DateTime?(new DateTime(ModifiedAfterThisUtcTime, DateTimeKind.Unspecified));

            ModifiedAfterThisTime = AnnotationDataContext.ValidateDate(ModifiedAfterThisTime);

            DeletedIDs = new long[0];

            Location[] retList = new Location[0];

            QueryExecutedTime = DateTime.Now.ToUniversalTime().Ticks;
            try
            {
                //// Find all the IDs that still exist
                //IQueryable<DateTime> queryDebug2 = from l in db.DBLocations
                //                                   where ((double)section) == l.Z
                //                                   select l.LastModified;

                //foreach (DateTime date in queryDebug2)
                //{
                //    System.Diagnostics.Debug.WriteLine(date.ToString());

                //    if (date > ModifiedAfterThisTime)
                //        System.Diagnostics.Debug.WriteLine("*******MATCH*******");
                //}

                /*
                IQueryable<DBLocation> queryResults = from l in db.DBLocations
                                                      where ((double)section) == l.Z &&
                                                            (ModifiedAfterThisTime <= l.LastModified)
                                                      select l;
                */
                IList<DBLocation> listLocations = db.SectionLocationsAndLinks((double)section, ModifiedAfterThisTime);

                elapsed = new TimeSpan(DateTime.Now.Ticks - start.Ticks);
                Debug.WriteLine(section.ToString() + ": Query: " + elapsed.TotalMilliseconds);

                //List<DBLocation> listLocations = queryResults.ToList<DBLocation>();

                retList = new Location[listLocations.Count];

             //               elapsed = new TimeSpan(DateTime.Now.Ticks - start.Ticks);
             //               Debug.WriteLine(section.ToString() + ": To list: " + elapsed.TotalMilliseconds);

                for (int i = 0; i < listLocations.Count; i++)
                {
                    retList[i] = new Location(listLocations[i]);
                }

                elapsed = new TimeSpan(DateTime.Now.Ticks - start.Ticks);
                Debug.WriteLine(section.ToString() + ": Loop: " + elapsed.TotalMilliseconds);
            }
            catch (System.ArgumentNullException)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find locations for section: " + section.ToString());
            }
            catch (System.InvalidOperationException e)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find locations for section: " + section.ToString());
            }

            //Try to find if any rows were deleted from the passed list of IDs
            try
            {
                if (ModifiedAfterThisTime.HasValue)
                {
                    //// Find all the IDs that still exist
                    //IQueryable<DateTime> queryDebug = from l in db.DBDeletedLocations
                    //                                select l.DeletedOn;

                    //foreach (DateTime date in queryDebug)
                    //{
                    //    System.Diagnostics.Debug.WriteLine(date.ToString());

                    //    if(date > ModifiedAfterThisTime)
                    //        System.Diagnostics.Debug.WriteLine("*******MATCH*******");
                    //}

                    // Find all the IDs that still exist
                    IQueryable<long> queryResults = from l in db.DBDeletedLocations
                                                    where (l.DeletedOn > ModifiedAfterThisTime)
                                                    select l.ID;

                    elapsed = new TimeSpan(DateTime.Now.Ticks - start.Ticks);
                    Debug.WriteLine(section.ToString() + ": Deleted Query: " + elapsed.TotalMilliseconds);

                    //Figure out which IDs are not in the returned list
                    DeletedIDs = queryResults.ToArray();
                }
                else
                {
                    DeletedIDs = new long[0];
                }

            }
            catch (System.ArgumentNullException)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find locations for section: " + section.ToString());
            }
            catch (System.InvalidOperationException e)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find locations for section: " + section.ToString());
            }
            finally
            {
                if (db != null)
                    db.Connection.Close();
            }

            return retList;
        }
Exemple #5
0
        public Location[] GetLocationsByID(long[] IDs)
        {
            List<long> ListIDs = new List<long>(IDs);
            List<Location> ListLocations = new List<Location>(IDs.Length);

            //LINQ creates a SQL query with parameters when using contains, and there is a 2100 parameter limit.  So we cut the query into smaller chunks and run
            //multiple queries
            ListIDs.Sort();  //Sort the list to slightly optimize the query

            int QueryChunkSize = 2000;

            while (ListIDs.Count > 0)
            {
                int NumIDs = ListIDs.Count < QueryChunkSize ? ListIDs.Count : QueryChunkSize;

                long[] ShorterIDArray = new long[NumIDs];

                ListIDs.CopyTo(0, ShorterIDArray, 0, NumIDs);
                ListIDs.RemoveRange(0, NumIDs);

                //I do this hoping that it will allow SQL to not check the entire table for each chunk
                long minIDValue = ShorterIDArray[0];
                long maxIDValue = ShorterIDArray[ShorterIDArray.Length - 1];

                List<long> ShorterListIDs = new List<long>(ShorterIDArray);

                try
                {
                    IQueryable<DBLocation> locObjs = from s in db.DBLocations
                                                                 where s.ID >= minIDValue &&
                                                                       s.ID <= maxIDValue &&
                                                                       ShorterListIDs.Contains(s.ID)
                                                                 select s;
                    if (locObjs == null)
                        return null;

                    foreach (DBLocation locObj in locObjs)
                    {
                        Location newLocation = new Location(locObj);
                        ListLocations.Add(newLocation);
                    }

                }
                catch (System.ArgumentNullException)
                {
                    //This means there was no row with that ID;
                    Debug.WriteLine("Could not find requested location IDs: " + IDs.ToString());
                }
                catch (System.InvalidOperationException e)
                {
                    //This means there was no row with that ID;
                    Debug.WriteLine("Could not find requested location IDs: " + IDs.ToString());
                }
                finally
                {
                    if (db != null)
                        db.Connection.Close();
                }
            }

            return ListLocations.ToArray();
        }
Exemple #6
0
        public Location GetLocationByID(long ID)
        {
            try
            {
                DBLocation obj = (from t in db.DBLocations where t.ID == ID select t).Single();
                if (obj == null)
                    return null;
                Location retLoc = new Location(obj);
                return retLoc;
            }
            catch (System.ArgumentNullException)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find requested location ID: " + ID.ToString());
            }
            catch (System.InvalidOperationException e)
            {
                //This means there was no row with that ID;
                Debug.WriteLine("Could not find requested location ID: " + ID.ToString());
            }

            return null;
        }
Exemple #7
0
        public CreateStructureRetval CreateStructure(Structure structure, Location location)
        {
            try
            {
                DBStructure DBStruct = new DBStructure();
                structure.Sync(DBStruct);

                db.DBStructures.InsertOnSubmit(DBStruct);

                DBLocation DBLoc = new DBLocation();
                location.Sync(DBLoc);
                DBLoc.DBStructure = DBStruct;

                db.DBLocations.InsertOnSubmit(DBLoc);

                db.SubmitChanges();

                //Return new ID's to the caller
                CreateStructureRetval retval = new CreateStructureRetval(new Structure(DBStruct, false), new Location(DBLoc));
                return retval;
            }
            finally
            {
                if (db != null)
                    db.Connection.Close();
            }

            return null;
        }
Exemple #8
0
        public long[] Update(Location[] locations)
        {
            Dictionary<DBLocation, int> mapNewTypeToIndex = new Dictionary<DBLocation, int>(locations.Length);

            //Stores the ID of each object manipulated for the return value
            long[] listID = new long[locations.Length];
            try
            {

                for (int iObj = 0; iObj < locations.Length; iObj++)
                {
                    Location t = locations[iObj];

                    switch (t.DBAction)
                    {
                        case DBACTION.INSERT:

                            DBLocation newObj = new DBLocation();
                            t.Sync(newObj);
                            db.DBLocations.InsertOnSubmit(newObj);
                            mapNewTypeToIndex.Add(newObj, iObj);
                            break;
                        case DBACTION.UPDATE:
                            DBLocation updateRow;
                            try
                            {
                                updateRow = (from u in db.DBLocations where u.ID == t.ID select u).Single();
                            }
                            catch (System.ArgumentNullException e)
                            {
                                Debug.WriteLine("Could not find structuretype to update: " + t.ID.ToString());
                                break;
                            }
                            catch (System.InvalidOperationException e)
                            {
                                Debug.WriteLine("Could not find structuretype to update: " + t.ID.ToString());
                                break;
                            }

                            t.Sync(updateRow);
                            listID[iObj] = updateRow.ID;
                            //  db.DBStructureTypes.(updateType);
                            break;
                        case DBACTION.DELETE:
                            DBLocation deleteRow;
                            try
                            {
                                deleteRow = (from u in db.DBLocations where u.ID == t.ID select u).Single();
                            }
                            catch (System.ArgumentNullException e)
                            {
                                Debug.WriteLine("Could not find structuretype to update: " + t.ID.ToString());
                                break;
                            }
                            catch (System.InvalidOperationException e)
                            {
                                Debug.WriteLine("Could not find structuretype to update: " + t.ID.ToString());
                                break;
                            }

                            //Remove any links that exist before calling delete
                            foreach (DBLocationLink link in deleteRow.IsLinkedFrom)
                            {
                                db.DBLocationLinks.DeleteOnSubmit(link);
                            }

                            foreach (DBLocationLink link in deleteRow.IsLinkedTo)
                            {
                                db.DBLocationLinks.DeleteOnSubmit(link);
                            }

                            t.Sync(deleteRow);
                            deleteRow.ID = t.ID;
                            listID[iObj] = deleteRow.ID;
                            db.DBLocations.DeleteOnSubmit(deleteRow);

                            break;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                throw e;
            }

            db.Log = Console.Out;
            db.SubmitChanges();
            Console.Out.Flush();

            //Recover the ID's for new objects
            foreach (DBLocation newObj in mapNewTypeToIndex.Keys)
            {
                int iIndex = mapNewTypeToIndex[newObj];
                listID[iIndex] = newObj.ID;
            }

            if (db != null)
                db.Connection.Close();

            return listID;
        }
Exemple #9
0
        public Location CreateLocation(Location new_location, long[] links)
        {
            try
            {
                DBLocation db_obj = new DBLocation();
                string username = ServiceModelUtil.GetUserForCall();
                using (var transaction = new TransactionScope())
                {
                    //Create the object to get the ID
                    new_location.Sync(db_obj);
                    new_location.Username = username;
                    db.DBLocations.InsertOnSubmit(db_obj);

                    db.Log = Console.Out;
                    db.SubmitChanges();
                    Console.Out.Flush();

                    //Build a new location link for every link in the array
                    List<DBLocationLink> listLinks = new List<DBLocationLink>(links.Length);
                    foreach (long linked_locationID in links)
                    {
                        DBLocationLink created_link = _CreateLocationLink(db_obj.ID, linked_locationID, username);
                        listLinks.Add(created_link);
                    }

                    db.DBLocationLinks.InsertAllOnSubmit(listLinks);
                    db.SubmitChanges();
                    transaction.Complete();
                }

                Location output_loc = new Location(db_obj);
                output_loc.Links = links;
                return output_loc;
            }
            finally
            {
                if (db != null)
                    db.Connection.Close();
            }
        }
		void StoreLocation (string name, XmlTextReader reader)
		{
			string path = null;
			bool haveAllow = false;
			bool allowOverride = true;
			string att = null;

			while (reader.MoveToNextAttribute ()) {
				att = reader.Name;

				if (att == "path") {
					if (path != null)
						ThrowException ("Duplicate path attribute", reader);

					path = reader.Value;
					if (path.StartsWith ("."))
						ThrowException ("Path cannot begin with '.'", reader);

					if (path.IndexOfAny (forbiddenPathChars) != -1)
						ThrowException ("Path cannot contain " + forbiddenStr, reader);

					continue;
				}

				if (att == "allowOverride") {
					if (haveAllow)
						ThrowException ("Duplicate allowOverride attribute", reader);

					haveAllow = true;
					allowOverride = (reader.Value == "true");
					if (!allowOverride && reader.Value != "false")
						ThrowException ("allowOverride must be either true or false", reader);
					continue;
				}

				ThrowException ("Unrecognized attribute.", reader);
			}

			if (att == null)
				return; // empty location tag

			Location loc = new Location (this, path, allowOverride);
			if (locations == null)
				locations = new Hashtable ();
			else if (locations.ContainsKey (loc.Path))
				ThrowException ("Duplicated location path: " + loc.Path, reader);

			reader.MoveToElement ();
			loc.LoadFromString (reader.ReadInnerXml ());
			locations [loc.Path] = loc;
			if (!loc.AllowOverride) {
				XmlTextReader inner = loc.GetReader ();
				if (inner != null) {
					MoveToNextElement (inner);
					ReadConfig (loc.GetReader (), true);
				}
			}

			loc.XmlStr = null;
		}