public async Task <IActionResult> Edit(int id, [Bind("id,name,url,shootingtime,content,placeID")] photo photo)
        {
            if (id != photo.id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(photo);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!photoExists(photo.id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["placeID"] = new SelectList(_context.places, "id", "id", photo.placeID);
            return(View(photo));
        }
Exemple #2
0
 private void UploadCallback(photo p, object state, FacebookException e)
 {
     if (friendsUids != null && friendsPositions != null)
     {
         PhotoTagger(p.pid);
     }
 }
        public ActionResult DeleteConfirmed2(int id)
        {
            photo photo = db.photo.Find(id);

            db.photo.Remove(photo);
            db.SaveChanges();
            return(RedirectToAction("Mygalleries", "Galleries"));
        }
        private PhotoInstance?GetPhotoInstance(newsItem ni, enumeratedTypes.enumPhotoInstanceType[] photoTypes)
        {
            IEnumerator <photo> phEn = ni.photos.GetEnumerator();

            if (!phEn.MoveNext())
            {
                return(null);
            }

            PhotoInstance phIns = new PhotoInstance();
            bool          found = false;
            photo         ph    = phEn.Current;
            IEnumerator <photo.Instance> phIEn = ph.Instances.GetEnumerator();

            while (phIEn.MoveNext())
            {
                foreach (enumeratedTypes.enumPhotoInstanceType phType in photoTypes)
                {
                    if (phIEn.Current.type == phType)
                    {
                        phIns.Width  = phIEn.Current.width;
                        phIns.Height = phIEn.Current.height;
                        phIns.Url    = phIEn.Current.url;
                        phIns.Type   = phIEn.Current.type;
                        phIns.Type   = phType;

                        string cleanedUrl = phIns.Url;
                        if (cleanedUrl.IndexOf('?') >= 0)
                        {
                            cleanedUrl = cleanedUrl.Substring(0, cleanedUrl.IndexOf('?'));
                        }

                        string phTypeSlug = Slugify(phType);
                        phIns.DestinationFileName = Slugify(ni.headline) + (phTypeSlug == "" ? "" : "-" + phTypeSlug) + Path.GetExtension(cleanedUrl);

                        found = true;
                        break;
                    }
                }

                if (found)
                {
                    phIns.AltText     = phEn.Current.htmlAlt;
                    phIns.Caption     = phEn.Current.caption;
                    phIns.Id          = phEn.Current.id;
                    phIns.Orientation = phEn.Current.orientation;

                    break;
                }
            }

            if (!found)
            {
                return(null);
            }
            return(phIns);
        }
        public async Task <IActionResult> Create([Bind("id,name,url,shootingtime,content,placeID")] photo photo)
        {
            if (ModelState.IsValid)
            {
                _context.Add(photo);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["placeID"] = new SelectList(_context.places, "id", "id", photo.placeID);
            return(View(photo));
        }
Exemple #6
0
        //插入图片
        public void insertPhoto(int _userId, string _photoName, string _photoUrl, DateTime _dateTime)
        {
            photo photoItem = new photo
            {
                userId    = _userId,
                photoName = _photoName,
                photoUrl  = _photoUrl,
                photoTime = _dateTime
            };

            db.photo.InsertOnSubmit(photoItem);
            db.SubmitChanges();
        }
Exemple #7
0
 /// <summary>
 /// Initializes FacebookPhoto object
 /// </summary>
 internal FacebookPhoto(photo photo)
 {
     aid        = photo.aid;
     caption    = photo.caption;
     created    = photo.created;
     link       = photo.link;
     modified   = photo.modified;
     owner      = photo.owner;
     pid        = photo.pid;
     src        = photo.src;
     src_big    = photo.src_big;
     src_small  = photo.src_small;
     story_fbid = photo.story_fbid;
 }
        public ActionResult Details2(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            photo photo = db.photo.Find(id);

            if (photo == null)
            {
                return(HttpNotFound());
            }
            return(View(photo));
        }
        public ActionResult FullImage(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            photo galleries = db.photo.Find(id);

            if (galleries == null)
            {
                return(HttpNotFound());
            }
            return(View(galleries));
        }
        public static async Task <photo> GetPhoto(string photoId)
        {
            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new Uri("https://us-central1-project-caitlin-c71a9.cloudfunctions.net/GetPhotoDetails"),
                Method     = HttpMethod.Get
            };

            var requestData = new Dictionary <string, Dictionary <string, string> >
            {
                {
                    "data",
                    new Dictionary <string, string>
                    {
                        { "userId", App.User.id },
                        { "photoId", photoId }
                    }
                },
            };

            string dataString  = JsonConvert.SerializeObject(requestData);
            var    formContent = new StringContent(dataString, Encoding.UTF8, "application/json");
            photo  photo       = new photo();

            using (var client = new HttpClient())
            {
                // without async, will get stuck, needs bug fix
                HttpResponseMessage response = client.PostAsync(request.RequestUri, formContent).Result;
                var photosResponse           = await response.Content.ReadAsStringAsync();

                try
                {
                    JObject photosJson  = JObject.Parse(photosResponse);
                    var     photo_field = photosJson["result"];

                    photo.id          = photo_field["photo_id"] + "";
                    photo.description = photo_field["description"] + "";
                    photo.note        = photo_field["notes"] + "";

                    App.User.FirebasePhotos.Add(photo);
                }
                catch
                {
                    Console.WriteLine($"error with photo id: {photoId}");
                }
                return(photo);
            }
        }
Exemple #11
0
        public void uploadTest2()
        {
            photo actual  = null;
            var   aid     = Constants.FBSamples_aid;
            var   caption = "caption";

            // TODO: find a better way to be able to access this file universally from any computer, running the tests from any location
            var data = new FileInfo(@"C:\Clarity.jpg");

            if (!data.Exists)
            {
                Assert.Fail(string.Format("Unable to load photo from {0}.", data.FullName));
                return;
            }

            actual = _api.Photos.Upload(aid, caption, data, Constants.FBSamples_UserId);
            Assert.IsNotNull(actual);
        }
        public ActionResult Edit2([Bind(Include = "ID,Image,ImageName,GalleryName")] photo photo, HttpPostedFileBase files, int?id)
        {
            if (ModelState.IsValid)
            {
                // extract only the filename
                var fileName = Path.GetFileName(files.FileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/Content"), fileName);
                files.SaveAs(path);


                photo.Image           = "~/Content/" + fileName;
                db.Entry(photo).State = EntityState.Modified;
                db.SaveChanges();
                return(View("Success"));
            }
            return(View("View"));
        }
        public async Task LoadFirebasePhoto()
        {
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri("https://firestore.googleapis.com/v1/projects/project-caitlin-c71a9/databases/(default)/documents/users/" + uid + "/photo?pageSize=100"),
                Method     = HttpMethod.Get
            };
            var client = new HttpClient();
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                HttpContent content        = response.Content;
                var         photosResponse = await content.ReadAsStringAsync();

                JObject photosJson = JObject.Parse(photosResponse);

                if (photosJson["documents"] != null)
                {
                    List <photo> photos = new List <photo>();
                    foreach (JToken photoToken in photosJson["documents"])
                    {
                        try
                        {
                            var   photo_field = photoToken["fields"];
                            photo photo       = new photo();
                            photo.id          = photo_field["photo_id"]["stringValue"].ToString();
                            photo.description = photo_field["description"]["stringValue"].ToString();
                            photo.note        = photo_field["notes"]["stringValue"].ToString();

                            App.User.FirebasePhotos.Add(photo);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 从XML文件中得到相关属性值
        /// </summary>
        /// <param name="Xmldata">XML数据</param>
        /// <param name="PoiData">酒店数据</param>
        /// <param name="PhotoData">照片数据</param>
        static void ReadXmlNodes(string Xmldata, List <poi> PoiData, List <photo> PhotoData)
        {
            /*
             * List<poi> PoiData = new List<poi>();
             * List<photo> PhotoData = new List<photo>();
             */
            poi p1 = new poi();

            PoiData.Add(p1);
            photo p2 = new photo();

            PhotoData.Add(p2);
            int         i      = 0;
            int         j      = 0;
            string      t      = null;
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(Xmldata);
            XmlNode     xnresponse = xmlDoc.SelectSingleNode("response");
            XmlNodeList xnList     = xnresponse.ChildNodes;

            foreach (XmlNode xn in xnList)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.Name == "pois")
                {
                    XmlNodeList xnList2 = xe.ChildNodes;
                    foreach (XmlNode xn2 in xnList2)
                    {
                        XmlElement  xe2     = (XmlElement)xn2;
                        XmlNodeList xnList3 = xe2.ChildNodes;
                        PoiData[i].Id      = (xn2.SelectSingleNode("id")).InnerText;
                        PoiData[i].Name    = xn2.SelectSingleNode("name").InnerText;
                        PoiData[i].Type    = (xn2.SelectSingleNode("type")).InnerText;
                        PoiData[i].Address = (xn2.SelectSingleNode("address")).InnerText;
                        PoiData[i].Address = PoiData[i].Address.Replace(",", "  ");
                        string poiLoc = (xn2.SelectSingleNode("location")).InnerText;
                        PoiData[i].Lng       = poiLoc.Split(',')[0];
                        PoiData[i].Lat       = poiLoc.Split(',')[1];
                        PoiData[i].Pname     = (xn2.SelectSingleNode("pname")).InnerText;
                        PoiData[i].Cityname  = (xn2.SelectSingleNode("cityname")).InnerText;
                        PoiData[i].Adminname = (xn2.SelectSingleNode("adname")).InnerText;
                        t = (xn2.SelectSingleNode("tel")).InnerText;
                        if (t != "")
                        {
                            PoiData[i].Telephone = (xn2.SelectSingleNode("tel")).InnerText;
                        }
                        foreach (XmlNode xn3 in xnList3)
                        {
                            XmlElement xe3 = (XmlElement)xn3;
                            if (xe3.Name == "biz_ext")
                            {
                                t = (xn3.SelectSingleNode("rating")).InnerText;
                                if (t != "")
                                {
                                    PoiData[i].Rating = (xn3.SelectSingleNode("rating")).InnerText;
                                }
                                t = (xn3.SelectSingleNode("star")).InnerText;
                                if (t != "")
                                {
                                    PoiData[i].Star = (xn3.SelectSingleNode("star")).InnerText;
                                }
                            }
                            if (xe3.Name == "photos")
                            {
                                XmlNodeList xnList4 = xe3.ChildNodes;
                                foreach (XmlNode xn4 in xnList4)
                                {
                                    t = (xn4.SelectSingleNode("title")).InnerText;
                                    if (t != "")
                                    {
                                        PhotoData[j].Title = (xn4.SelectSingleNode("title")).InnerText;
                                    }
                                    t = (xn4.SelectSingleNode("url")).InnerText;
                                    if (t != "")
                                    {
                                        PhotoData[j].Url = (xn4.SelectSingleNode("url")).InnerText;
                                    }
                                    j++;
                                    if (j == PhotoData.Count)
                                    {
                                        photo p3 = new photo();
                                        PhotoData.Add(p3);
                                    }
                                }
                            }
                        }
                        i++;
                        poi p4 = new poi();
                        PoiData.Add(p4);
                        if (j != 3 * i)
                        {
                            int x = j;
                            j = 3 * i;
                            for (int k = 0; k < j - x; k++)
                            {
                                photo p5 = new photo();
                                PhotoData.Add(p5);
                            }
                        }
                    }
                }
            }
        }
        public string updateScriptDebug()
        {
            if (MyGlobals.ArtOrBlog == "articles")
            {
                MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Start of articles<br>";
                connection.Open();
                cmd.Connection = connection;

                //Get current directory for style sheets and images
                //was getting errors from the following so simplified it to AppDomainAppPath.ToString();
                string appPath = HttpRuntime.AppDomainAppVirtualPath == "/" ? appPath = "" : appPath = HttpRuntime.AppDomainAppVirtualPath;
                //string appPath = HttpRuntime.AppDomainAppVirtualPath.ToString();//AppDomainAppPath

                //Base api URL
                string newsURL = getNewsURL();
                string baseUrl = getBaseURL();
                //  MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "<br>************************************************<br>";
                // MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "newsURL " + newsURL + "<br>";
                //  MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "baseUrl " + baseUrl + "<br>";
                // MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "<br>************************************************<br>";

                ApiContext ac;

                if (MyGlobals.ArtOrBlog == "archive")
                {
                    ac = new ApiContext(MyGlobals.ArchiveLink);
                }
                else
                {
                    ac = new ApiContext(newsURL, baseUrl);
                }

                //Since this column is an identity column in the table this value does not actually get inserted.
                int entryID = 0;

                //Used to compare the current BraftonID from the xml feed to the Brafton IDs in the Blog_Entries table
                int compareIDs;

                //Blog_Entries table variables
                string   artBlogID;
                string   title;
                string   entry;
                DateTime addedDate;
                string   description       = string.Empty;
                string   description_debug = string.Empty;
                bool     published         = true;
                bool     allowComments     = false;
                bool     displayCopyright  = false;
                string   photoURL;
                string   byline;
                string   caption;
                int      PageTabId = getTabID();
                ////////////////////////////

                //Blog_Categories table variables
                string slug;
                string category;
                int    parentID    = 0;
                int    intPortalID = getPortalID();
                ////////////////////////////

                //This is for storing all of the category xml urls during the iteration
                ArrayList xmlArtCatURLs = new ArrayList();

                //Blog_Entry_Categories table Arrays, these are populated while populating
                //The Blog_Entry DataTable and Blog_Categories DataTable
                ArrayList entryIDArray  = new ArrayList();
                ArrayList categoryArray = new ArrayList();
                /////////////////////////////////////////////////////////////////////////

                DataTable articleTable = DataTables.GetTable("Blog_Entries");

                //For Limit
                int l = 0;

                //Set the limit of the amount of articles that can be imported at a time
                int limit = getLimit();


                #region Article Loop DEBUG
                //Fill Blog_Entries DataTable
                foreach (newsItem ni in ac.News)
                {
                    if (l < limit)
                    {
                        artBlogID   = ni.id.ToString();
                        title       = ni.headline;
                        entry       = ni.text;
                        description = ni.extract;
                        addedDate   = ni.publishDate;
                        photoURL    = ni.PhotosHref;
                        byline      = ni.byLine;
                        DateTime today = DateTime.Today;
                        //for operations after update or insert
                        int    entryId;
                        string tempSlug;



                        using (DNNDataLayerDataContext dnnContext = new DNNDataLayerDataContext())
                        {
                            Blog_Entry be = dnnContext.Blog_Entries.FirstOrDefault(x => x.BraftonID == artBlogID);

                            if (be != null)
                            {
                                #region Update Article
                                MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Start of update<br>";

                                //If update feed content is on we do some stuff
                                int updateCheck = MyGlobals.IncludeUpdatedFeedContent;
                                int lastDayUpd  = 0;
                                int todayDay    = 0;

                                lastDayUpd = be.LastUpdatedOn.Value.DayOfYear;
                                //todayDay = DateTime.Today.DayOfYear;
                                //TODO set this check back in place FJD


                                //if the article has not been updated today
                                if (lastDayUpd != todayDay)
                                {
                                    //if they have updated feed content checked
                                    if (updateCheck == 1)
                                    {
                                        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                        //Update the article
                                        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                        //Lets get the entryID that matches the BraftonID
                                        //But if there isn't one it means this is a new article and we should skip the update

                                        //cmd.CommandText = "IF (SELECT EntryID FROM Blog_Entries WHERE BraftonID='" + artBlogID + "') IS NULL BEGIN SELECT 0 END ELSE (SELECT EntryID FROM Blog_Entries WHERE BraftonID=" + artBlogID + ")";

                                        //int getDNNID = (int)cmd.ExecuteScalar();

                                        //if (getDNNID > 0)
                                        //{
                                        // DateTime today = DateTime.Today;
                                        //string displayDate = today.ToString("dd/MM/yyyy");

                                        #region IMAGE HANDLER

                                        //photo img = ni.photos.First();
                                        //photo.Instance photoInstance = img.Instances.Where(x => x.type == enumeratedTypes.enumPhotoInstanceType.Medium).FirstOrDefault();
                                        //string photoTest = photoInstance.type.ToString();

                                        photo          img = ni.photos.First();
                                        photo.Instance photoInstanceLarge  = img.Instances.Where(x => x.type == enumeratedTypes.enumPhotoInstanceType.Large).FirstOrDefault();
                                        photo.Instance photoInstanceMedium = img.Instances.Where(x => x.type == enumeratedTypes.enumPhotoInstanceType.Medium).FirstOrDefault();
                                        photo.Instance photoInstanceSmall  = img.Instances.Where(x => x.type == enumeratedTypes.enumPhotoInstanceType.Small).FirstOrDefault();
                                        photo.Instance photoInstance;

                                        if (photoInstanceLarge != null)
                                        {
                                            photoInstance = photoInstanceLarge;
                                            //MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Using Large<br>";
                                        }
                                        else if (photoInstanceMedium != null)
                                        {
                                            photoInstance = photoInstanceMedium;
                                            // MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Using Medium<br>";
                                        }
                                        else if (photoInstanceSmall != null)
                                        {
                                            photoInstance = photoInstanceSmall;
                                            // MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Using Small<br>";
                                        }
                                        else
                                        {
                                            photoInstance = null;
                                        }
                                        //Otherwise leave it as null and move on


                                        //Checks to see if large images are enabled on the feed
                                        if (photoInstance != null)
                                        {
                                            photoURL = photoInstance.url.ToString();
                                            caption  = img.caption.ToString();


                                            //Checks to see if the feed has photos enabled.
                                            if (!string.IsNullOrEmpty(photoURL))
                                            {
                                                GetImages retrieveImage2 = new GetImages(photoURL, entry, description, appPath, caption);
                                                retrieveImage2.DownloadImageDebug();

                                                //The images is placed into the description and the entry here


                                                entry                   = retrieveImage2._entry;
                                                description             = retrieveImage2._description;
                                                MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "**********************************************************<br>";
                                                MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "brafton ID: " + artBlogID + "<br>";
                                                MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Description: " + description + "<br>";
                                                MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "**********************************************************<br>";
                                                //string testUrl = HttpContext.Current.Request.Url.Host;
                                            }
                                        }



                                        #endregion IMAGE HANDLER

                                        //Checks to see if the feed has the byline enabled.
                                        if (!string.IsNullOrEmpty(byline))
                                        {
                                            entry = entry.Insert(entry.Length, "<br /><br /><span class='byline'> By " + byline + "</span>");
                                        }


                                        #region Update Article


                                        be.Title       = title;
                                        be.Entry       = entry;
                                        be.Description = description;
                                        //be.Copyright = null;
                                        be.LastUpdatedOn = today;
                                        be.AllowComments = false;
                                        //dnnContext.
                                        dnnContext.SubmitChanges();
                                        #endregion

                                        entryId  = be.EntryID;
                                        tempSlug = title;

                                        //Update Permalinks
                                        setPermalinks(PageTabId, entryId, tempSlug, artBlogID);
                                    } //end of update check
                                }     //end of check for update today
                                #endregion Update Article
                            }

                            else

                            {
                                #region New Article
                                photo          img = ni.photos.First();
                                photo.Instance photoInstanceLarge  = img.Instances.Where(x => x.type == enumeratedTypes.enumPhotoInstanceType.Large).FirstOrDefault();
                                photo.Instance photoInstanceMedium = img.Instances.Where(x => x.type == enumeratedTypes.enumPhotoInstanceType.Medium).FirstOrDefault();
                                photo.Instance photoInstanceSmall  = img.Instances.Where(x => x.type == enumeratedTypes.enumPhotoInstanceType.Small).FirstOrDefault();
                                photo.Instance photoInstance;

                                if (photoInstanceLarge != null)
                                {
                                    photoInstance = photoInstanceLarge;
                                    // MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Using Large<br>";
                                }
                                else if (photoInstanceMedium != null)
                                {
                                    photoInstance = photoInstanceMedium;
                                    //  MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Using Medium<br>";
                                }
                                else if (photoInstanceSmall != null)
                                {
                                    photoInstance = photoInstanceSmall;
                                    // MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Using Small<br>";
                                }
                                //Otherwise leave it as null and move on
                                else
                                {
                                    photoInstance = null;
                                }



                                #region IMAGE HANDLER
                                //Checks to see if medium images are enabled on the feed
                                if (photoInstance != null)
                                {
                                    photoURL = photoInstance.url.ToString();
                                    caption  = img.caption.ToString();

                                    //Checks to see if the feed has photos enabled.
                                    if (!string.IsNullOrEmpty(photoURL))
                                    {
                                        GetImages retrieveImage2 = new GetImages(photoURL, entry, description, appPath, caption);
                                        retrieveImage2.DownloadImageDebug();

                                        //The images is placed into the description and the entry here

                                        description_debug = retrieveImage2._description;
                                        entry             = retrieveImage2._entry;
                                    }
                                }
                                #endregion IMAGE HANDLER
                                //Checks to see if the feed has the byline enabled.
                                if (!string.IsNullOrEmpty(byline))
                                {
                                    entry = entry.Insert(entry.Length, "<br /><br /><span class='byline'> By " + byline + "</span>");
                                }

                                Blog_Entry newBlogEntry = new Blog_Entry();

                                newBlogEntry.BlogID           = getBlogID();
                                newBlogEntry.Title            = title;
                                newBlogEntry.Entry            = entry;
                                newBlogEntry.AddedDate        = addedDate;
                                newBlogEntry.Published        = published;
                                newBlogEntry.Description      = description_debug;
                                newBlogEntry.AllowComments    = allowComments;
                                newBlogEntry.DisplayCopyright = displayCopyright;
                                newBlogEntry.BraftonID        = artBlogID;
                                newBlogEntry.LastUpdatedOn    = today;

                                dnnContext.Blog_Entries.InsertOnSubmit(newBlogEntry);
                                dnnContext.SubmitChanges();



                                entryId  = newBlogEntry.EntryID;
                                tempSlug = title;


                                //For Permalinks
                                setPermalinks(PageTabId, entryId, tempSlug, artBlogID);

                                ///////////////////////////////////////////////////

                                //Place the category URL into the array for future use
                                xmlArtCatURLs.Add(ni.CategoriesHref);

                                //For Future Use with Blog_Entry_Categories
                                entryIDArray.Add(artBlogID);

                                //increment limit
                                l++;
                                /////////////////////////////////////////////////////
                                #endregion New Article
                            }
                        }

                        //////Passes all Brafton posts from the Database into this method and checks to see if this posts already exists
                        ////cmd.CommandText = "IF (SELECT BraftonID FROM Blog_Entries WHERE BraftonID='" + artBlogID + "') IS NOT NULL BEGIN SELECT 0 END ELSE SELECT 1";
                        //////cmd.CommandText = "SELECT 1";
                        ////compareIDs = (int)cmd.ExecuteScalar();

                        ////if it doesn't exist
                        //if (compareIDs == 1)
                        //#region Write Article DEBUG

                        //{



                        //   // articleTable.Rows.Add(getBlogID(), entryID, title, entry, addedDate, published, description, allowComments, displayCopyright, null, "", artBlogID);



                        //}

                        //else

                        //    //***************************************************************************************
                        //    //***************************************************************************************
                        //    //***************************************************************************************


                        //}
                        //#endregion Write Article DEBUG
                    }
                }

                #endregion Article Loop DEBUG
                //Check to see if the article table is empty, if it is, cancel the whole operation.
                if (articleTable != null && articleTable.Rows.Count > 0)
                {
                    ///////////////////////////////////////////////////////////////////////////////////
                    //TODO: category stuff
                    ///////////////////////////////////////////////////////////////////////////////////
                    #region Category stuff


                    using (DNNDataLayerDataContext dnnContext = new DNNDataLayerDataContext())
                    {
                        //Blog_Category bc = dnnContext.Blog_Categories.FirstOrDefault(x => x.Category == artBlogID);
                    }


                    //Used to copy the DataTables to the MSSQL Database
                    //using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
                    //{
                    //    bulkCopy.DestinationTableName = "Blog_Entries";
                    //    bulkCopy.WriteToServer(articleTable);
                    //}

                    DataTable categoryTable = DataTables.GetTable("Blog_Categories");
                    /////////////////////////////////////////////////////////////

                    //Fill Blog_Categories DataTable
                    for (int i = 0; i < articleTable.Rows.Count; i++)
                    {
                        XmlDocument tmpXMLDoc = new XmlDocument();
                        tmpXMLDoc.Load(xmlArtCatURLs[i].ToString());
                        XmlNode name = tmpXMLDoc.GetElementsByTagName("name")[0];

                        if (name != null)
                        {
                            category = name.InnerText;
                        }
                        else
                        {
                            category = "Uncategorized";
                        }

                        slug = strip(category) + ".aspx";

                        cmd.CommandText = "IF (SELECT Category FROM Blog_Categories WHERE Category='" + category + "') IS NOT NULL BEGIN SELECT 0 END ELSE SELECT 1";
                        compareIDs      = (int)cmd.ExecuteScalar();

                        if (compareIDs == 1)
                        {
                            //Compares the rows in the categoryTable to the category currently being processed.
                            categoryTable.DefaultView.Sort = "Category";
                            int findRow = categoryTable.DefaultView.Find(category);

                            if (findRow == -1)
                            {
                                //Create the row in the datatable
                                categoryTable.Rows.Add(entryID, category, slug, parentID, intPortalID);
                            }
                        }

                        //For Future Use with Blog_Entry_Categories
                        categoryArray.Add(category);
                    }

                    //Used to copy the DataTables to the MSSQL Database
                    if (categoryTable != null && categoryTable.Rows.Count > 0)
                    {
                        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
                        {
                            bulkCopy.DestinationTableName = "Blog_Categories";
                            //bulkCopy.WriteToServer(categoryTable);
                        }
                    }

                    //Temporary variables that change with each iteration
                    int    tempCatID;
                    int    tempEntryID;
                    string tempSlug;
                    //int PageTabId = getTabID();

                    //Match the CategoryIDs with the EntryIDs for the Blog_Entry_Categories Table
                    DataTable catEntryTable = DataTables.GetTable("Blog_Entry_Categories");
                    for (int i = 0; i < articleTable.Rows.Count; i++)
                    {
                        category  = categoryArray[i].ToString();
                        artBlogID = entryIDArray[i].ToString();

                        cmd.CommandText = "Select EntryID From Blog_Entries Where BraftonID = '" + artBlogID + "'";
                        tempEntryID     = (int)cmd.ExecuteScalar();

                        cmd.CommandText = "Select Title From Blog_Entries Where BraftonID = '" + artBlogID + "'";
                        tempSlug        = (string)cmd.ExecuteScalar();

                        cmd.CommandText = "Select CatID From Blog_Categories Where Category ='" + category + "'";
                        tempCatID       = (int)cmd.ExecuteScalar();

                        catEntryTable.Rows.Add(entryID, tempEntryID, tempCatID);

                        //For Permalinks
                        //setPermalinks(PageTabId, tempEntryID, tempSlug, artBlogID);
                    }

                    //Used to copy the DataTables to the MSSQL Database
                    if (catEntryTable != null && catEntryTable.Rows.Count > 0)
                    {
                        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
                        {
                            bulkCopy.DestinationTableName = "Blog_Entry_Categories";
                            bulkCopy.WriteToServer(catEntryTable);
                        }
                    }

                    //Dispose of all of the tables, datasets and commands
                    catEntryTable.Dispose();
                    categoryTable.Dispose();
                }

                articleTable.Dispose();
                cmd.Dispose();

                connection.Close();
                #endregion Category Stuff

                return(description_debug);
            }//end of articles
            MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Video Include Global =" + MyGlobals.IncludeVideo;
            //If the feed includes videos
            if (MyGlobals.IncludeVideo == 1)
            {
                ImportVideos();
            }
            MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "ARTORBLOG" + MyGlobals.ArtOrBlog;
            string returnVal = "include video";
            return(returnVal);
        }
        public String updateScript()
        {
            connection.Open();
            cmd.Connection = connection;

            //Get current directory for style sheets and images
            string appPath = HttpRuntime.AppDomainAppVirtualPath == "/" ? appPath = "" : appPath = HttpRuntime.AppDomainAppVirtualPath;

            //Base api URL
            string newsURL = getNewsURL();
            string baseUrl = getBaseURL();

            ApiContext ac = new ApiContext(newsURL, baseUrl);

            //Since this column is an identity column in the table this value does not actually get inserted.
            int entryID = 0;

            //Used to compare the current BraftonID from the xml feed to the Brafton IDs in the Blog_Entries table
            int compareIDs;

            //Blog_Entries table variables
            string   artBlogID;
            string   title;
            string   entry;
            DateTime addedDate;
            string   description      = string.Empty;
            string   published        = "True";
            string   allowComments    = "False";
            string   displayCopyright = "False";
            string   photoURL;
            string   byline;
            string   caption;
            ////////////////////////////

            //Blog_Categories table variables
            string slug;
            string category;
            int    parentID    = 0;
            int    intPortalID = getPortalID();
            ////////////////////////////

            //This is for storing all of the category xml urls during the iteration
            ArrayList xmlArtCatURLs = new ArrayList();

            //Blog_Entry_Categories table Arrays, these are populated while populating
            //The Blog_Entry DataTable and Blog_Categories DataTable
            ArrayList entryIDArray  = new ArrayList();
            ArrayList categoryArray = new ArrayList();
            /////////////////////////////////////////////////////////////////////////

            DataTable articleTable = DataTables.GetTable("Blog_Entries");

            //For Limit
            int l = 0;

            //Set the limit of the amount of articles that can be imported at a time
            int limit = getLimit();

            //Fill Blog_Entries DataTable
            foreach (newsItem ni in ac.News)
            {
                if (l < limit)
                {
                    artBlogID   = ni.id.ToString();
                    title       = ni.headline;
                    entry       = ni.text;
                    description = ni.extract;
                    addedDate   = ni.publishDate;
                    photoURL    = ni.PhotosHref;
                    byline      = ni.byLine;
                    //////////////////////////////////////////////////////////////////////////

                    //Passes all Brafton posts from the Database into this method and checks to see if this posts already exists
                    cmd.CommandText = "IF (SELECT BraftonID FROM Blog_Entries WHERE BraftonID='" + artBlogID + "') IS NOT NULL BEGIN SELECT 0 END ELSE SELECT 1";
                    compareIDs      = (int)cmd.ExecuteScalar();

                    if (compareIDs == 1)
                    {
                        photo          img           = ni.photos.First();
                        photo.Instance photoInstance = img.Instances.Where(x => x.type == enumeratedTypes.enumPhotoInstanceType.Large).FirstOrDefault();

                        //Checks to see if large images are enabled on the feed
                        if (photoInstance != null)
                        {
                            photoURL = photoInstance.url.ToString();
                            caption  = img.caption.ToString();

                            //Checks to see if the feed has photos enabled.
                            if (!string.IsNullOrEmpty(photoURL))
                            {
                                GetImages retrieveImage = new GetImages(photoURL, entry, description, appPath, caption);
                                retrieveImage.DownloadImage();



                                //The images is placed into the description and the entry here
                                description = retrieveImage._description;
                                entry       = retrieveImage._entry;

                                //errorCheckingLabel.text = description;
                            }
                        }

                        //Checks to see if the feed has the byline enabled.
                        if (!string.IsNullOrEmpty(byline))
                        {
                            entry = entry.Insert(entry.Length, "<br /><br /><span class='byline'> By " + byline + "</span>");
                        }

                        articleTable.Rows.Add(getBlogID(), entryID, title, entry, addedDate, published, description, allowComments, displayCopyright, null, "", artBlogID);

                        //Place the category URL into the array for future use
                        xmlArtCatURLs.Add(ni.CategoriesHref);

                        //For Future Use with Blog_Entry_Categories
                        entryIDArray.Add(artBlogID);

                        //increment limit
                        l++;
                    }
                }
            }

            //Check to see if the article table is empty, if it is, cancel the whole operation.
            if (articleTable != null && articleTable.Rows.Count > 0)
            {
                //Used to copy the DataTables to the MSSQL Database
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
                {
                    bulkCopy.DestinationTableName = "Blog_Entries";
                    bulkCopy.WriteToServer(articleTable);
                }

                DataTable categoryTable = DataTables.GetTable("Blog_Categories");
                /////////////////////////////////////////////////////////////

                //Fill Blog_Categories DataTable
                for (int i = 0; i < articleTable.Rows.Count; i++)
                {
                    XmlDocument tmpXMLDoc = new XmlDocument();
                    tmpXMLDoc.Load(xmlArtCatURLs[i].ToString());
                    XmlNode name = tmpXMLDoc.GetElementsByTagName("name")[0];

                    if (name != null)
                    {
                        category = name.InnerText;
                    }
                    else
                    {
                        category = "Uncategorized";
                    }

                    slug = strip(category) + ".aspx";

                    cmd.CommandText = "IF (SELECT Category FROM Blog_Categories WHERE Category='" + category + "') IS NOT NULL BEGIN SELECT 0 END ELSE SELECT 1";
                    compareIDs      = (int)cmd.ExecuteScalar();

                    if (compareIDs == 1)
                    {
                        //Compares the rows in the categoryTable to the category currently being processed.
                        categoryTable.DefaultView.Sort = "Category";
                        int findRow = categoryTable.DefaultView.Find(category);

                        if (findRow == -1)
                        {
                            //Create the row in the datatable
                            categoryTable.Rows.Add(entryID, category, slug, parentID, intPortalID);
                        }
                    }

                    //For Future Use with Blog_Entry_Categories
                    categoryArray.Add(category);
                }

                //Used to copy the DataTables to the MSSQL Database
                if (categoryTable != null && categoryTable.Rows.Count > 0)
                {
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
                    {
                        bulkCopy.DestinationTableName = "Blog_Categories";
                        bulkCopy.WriteToServer(categoryTable);
                    }
                }

                //Temporary variables that change with each iteration
                int    tempCatID;
                int    tempEntryID;
                string tempSlug;
                int    PageTabId = getTabID();

                //Match the CategoryIDs with the EntryIDs for the Blog_Entry_Categories Table
                DataTable catEntryTable = DataTables.GetTable("Blog_Entry_Categories");
                for (int i = 0; i < articleTable.Rows.Count; i++)
                {
                    category  = categoryArray[i].ToString();
                    artBlogID = entryIDArray[i].ToString();

                    cmd.CommandText = "Select EntryID From Blog_Entries Where BraftonID = '" + artBlogID + "'";
                    tempEntryID     = (int)cmd.ExecuteScalar();

                    cmd.CommandText = "Select Title From Blog_Entries Where BraftonID = '" + artBlogID + "'";
                    tempSlug        = (string)cmd.ExecuteScalar();

                    cmd.CommandText = "Select CatID From Blog_Categories Where Category ='" + category + "'";
                    tempCatID       = (int)cmd.ExecuteScalar();

                    catEntryTable.Rows.Add(entryID, tempEntryID, tempCatID);

                    //For Permalinks
                    setPermalinks(PageTabId, tempEntryID, tempSlug, artBlogID);
                }

                //Used to copy the DataTables to the MSSQL Database
                if (catEntryTable != null && catEntryTable.Rows.Count > 0)
                {
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
                    {
                        bulkCopy.DestinationTableName = "Blog_Entry_Categories";
                        bulkCopy.WriteToServer(catEntryTable);
                    }
                }

                //Dispose of all of the tables, datasets and commands
                catEntryTable.Dispose();
                categoryTable.Dispose();
            }

            articleTable.Dispose();
            cmd.Dispose();

            connection.Close();

            return(description);
        }
Exemple #17
0
        public static async Task <List <List <string> > > GetPhotos()
        {
            //Make HTTP Request
            var request = new HttpRequestMessage();

            request.RequestUri = new Uri("https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100");
            request.Method     = HttpMethod.Get;

            //Format Headers of Request with included Token
            string bearerString = string.Format("Bearer {0}", App.User.access_token);

            request.Headers.Add("Authorization", bearerString);
            request.Headers.Add("Accept", "application/json");
            var client = new HttpClient();
            HttpResponseMessage response = await client.SendAsync(request);

            HttpContent content = response.Content;
            var         json    = await content.ReadAsStringAsync();

            //return json;
            //Deserialize JSON Result
            var result = JsonConvert.DeserializeObject <ProjectCaitlin.Methods.GetPhotoAlbumMethod>(json);
            //Create itemList
            var itemList = new List <List <string> >();
            //var itemMap = new Dictionary<string, string>();

            String creationTime      = "";
            String storePicUri       = "";
            String date              = "";
            String thumbNailAlbumUri = "";
            String description       = "";
            String id = "";

            //String note = "";

            try
            {
                foreach (var product in result.MediaItems)
                {
                    var subList = new List <string>();

                    DateTimeOffset GreenwichMeanTime = product.MediaMetadata.CreationTime; //Google photo api sends time in GreenwichMeanTime.
                    DateTimeOffset utcTime           = GreenwichMeanTime.ToLocalTime();    //convert GreenwichMeanTime to local time.

                    //creationTime = utcTime.ToString();
                    creationTime = utcTime.ToString();
                    date         = creationTime.Substring(0, creationTime.IndexOf(" "));// date = yyyy/mm/dd
                    creationTime = utcTime.TimeOfDay.ToString();
                    id           = product.Id;
                    string fileName = product.Filename;
                    storePicUri = product.BaseUrl.ToString();
                    description = product.Description + "";

                    App.User.allDates.Add(date);
                    subList.Add(product.BaseUrl.ToString());
                    subList.Add(date);
                    subList.Add(description);
                    subList.Add(creationTime);
                    subList.Add(id);

                    bool post = true;
                    foreach (photo photo in App.User.FirebasePhotos)
                    {
                        if (id.Equals(photo.id))
                        {
                            post = false;
                        }
                    }

                    // If there is a photo in Google but not in Firebase, post it.
                    if (post)
                    {
                        //Post photo to Firebase
                        await FirebaseFunctionsService.PostPhoto(id, description, " ");

                        subList.Add("");
                    }
                    else
                    {
                        //Get photo from Firebase and add note
                        photo photo = await FirebaseFunctionsService.GetPhoto(id);

                        subList.Add(photo.note);
                    }
                    App.User.photoURIs.Add(subList);
                    itemList.Add(subList);
                }
            }
            catch (NullReferenceException e)
            {
                var googleService = new GoogleService();
                if (await googleService.RefreshToken())
                {
                    Console.WriteLine("RefreshToken Done!");
                    App.User.photoURIs = await GooglePhotoService.GetPhotos();
                }
            }
            if (itemList.Count == 0)
            {
                return(new List <List <string> >());
            }
            else
            {
                return(itemList);
            }
        }
        public string getOutputPath(string albumDirectory, photo curPhoto)
        {
            string outputPath;

            outputPath = albumDirectory + "\\" + curPhoto.id;

            //Make sure we don't go over windows path limits
            if (outputPath.Length > 255)
                outputPath = outputPath.Substring(0, 255);

            outputPath += ".jpg";

            return outputPath;
        }
Exemple #19
0
    protected void PhotoUpload_Submit_Click(object sender, EventArgs e)
    {
        if (upload_File.FileContent.Length > 0 && CheckFileType(upload_File.FileName))
        {
            setting s;
            int photoSeqNumber = 0;
            string filename;
            System.Drawing.Image img;

            /* Validate and resize image */
            img = PhotoReformat(upload_File.FileContent);

            /* Get filename and increment setting */
            var q = from p in db.settings
                    where p.settingName == "NextImageFilename"
                    select p;
            s = q.First();

            filename = "images/image" + q.First().settingInt.ToString().PadLeft(3, '0');
            filename += System.IO.Path.GetExtension(upload_File.FileName);

            s.settingInt++;
            db.SubmitChanges();

            /* Copy file into image store */
            img.Save(MapPath(filename), System.Drawing.Imaging.ImageFormat.Jpeg);

            //upload_File.SaveAs(MapPath(filename));

            /* Build new photo in database */
            photo uploadedPhoto = new photo();

            uploadedPhoto.photoId = Guid.NewGuid();
            uploadedPhoto.photoDate = Convert.ToDateTime(upload_PhotoDate.Text.ToString());
            uploadedPhoto.photoCaption = upload_Caption.Text.ToString();
            uploadedPhoto.photoLocation = filename;
            uploadedPhoto.photoPageType = 0;
            uploadedPhoto.photoUploadedTimestamp = DateTime.Now;
            uploadedPhoto.photoUploader = upload_Username.Text.ToString();
            uploadedPhoto.photoIsMemorial = rbMemorial.Checked;

            /* get next sequence number */
            var sq = from p in db.photos
                    where p.photoSequenceNumber != null
                    orderby p.photoSequenceNumber descending
                    select p.photoSequenceNumber;

            if (sq.Count() != 0)
            {
                photoSeqNumber = sq.First().Value + 1;
            }

            uploadedPhoto.photoSequenceNumber = photoSeqNumber;

            db.photos.InsertOnSubmit(uploadedPhoto);
            db.SubmitChanges();

            lnkImageUploadLink.NavigateUrl = "PhotoView.aspx?p=" + photoSeqNumber;
            MultiView1.ActiveViewIndex = 1;

            Session["nbpName"] = upload_Username.Text.ToString();
            Session["nbpEmail"] = upload_Email.Text.ToString();

        }

        // audit stuff
        audit a = new audit();
        a.auditId = Guid.NewGuid();
        a.auditRemoteAddr = Request.ServerVariables["REMOTE_ADDR"].ToString();
        a.auditRequestedUrl = "PhotoUpload.aspx";
        a.auditSessionEmail = Session["nbpEmail"] != null ? Session["nbpEmail"].ToString() : "";
        a.auditSessionId = Session.SessionID.ToString();
        a.auditSessionName = Session["nbpName"] != null ? Session["nbpName"].ToString() : "";
        a.auditTimestamp = DateTime.Now;
        a.auditType = "PhotoUpload attempt";
        a.auditDescription = "PhotoDate: " + upload_PhotoDate.Text.ToString() +
            " Caption: " + upload_Caption.Text.ToString() +
            " Filename: " + upload_File.FileName.ToString() +
            " Name: " + upload_Username.Text.ToString();
        a.auditReferrer = Request.UrlReferrer.AbsolutePath.ToString();
        a.auditLogonUser = Request.ServerVariables["LOGON_USER"];
        db.audits.InsertOnSubmit(a);
        db.SubmitChanges();
    }
Exemple #20
0
        private void GetPatterns()
        {
            string url = "https://api.ravelry.com/patterns/search.json?page=";

            for (int i = 1; i < 10000; i++)
            {
                var            newUrl  = url + i;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newUrl);
                request.Method      = "GET";
                request.ContentType = "application/json";
                request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("A557BB258D37DE039AC3:VVaoS9R2Lvwhy_ToXF9AtyyBN9czTkD8IyTK7bvU"));

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader         reader = new StreamReader(responseStream, Encoding.UTF8);
                    JavaScriptSerializer js     = new JavaScriptSerializer();
                    var obj = js.Deserialize <dynamic>(reader.ReadToEnd());

                    pattern _pattern = new pattern();


                    foreach (var o in obj["patterns"])
                    {
                        _pattern = new pattern();

                        _pattern.id = o["id"];


                        if (db.patterns.Any(x => x.id == _pattern.id))
                        {
                        }
                        else
                        {
                            _pattern.name = o["name"];
                            _pattern.free = o["free"];
                            if (o["permalink"] != null)
                            {
                                _pattern.permalink = o["permalink"];
                            }

                            //photo
                            if (o["first_photo"] != null)
                            {
                                photo _photo = new photo();
                                _pattern.first_photo_id = o["first_photo"]["id"];
                                int photoId = o["first_photo"]["id"];
                                if (db.photos.Any(x => x.id == photoId))
                                {
                                }
                                else
                                {
                                    _photo.id = o["first_photo"]["id"];
                                    if (o["first_photo"]["caption"] != null)
                                    {
                                        _photo.caption = o["first_photo"]["caption"];
                                    }
                                    if (o["first_photo"]["caption_html"] != null)
                                    {
                                        _photo.caption_html = o["first_photo"]["caption_html"];
                                    }
                                    if (o["first_photo"]["copyright_holder"] != null)
                                    {
                                        _photo.copyright_holder = o["first_photo"]["copyright_holder"];
                                    }
                                    if (o["first_photo"]["medium2_url"] != null)
                                    {
                                        _photo.medium2_url = o["first_photo"]["medium2_url"];
                                    }
                                    if (o["first_photo"]["small2_url"] != null)
                                    {
                                        _photo.small2_url = o["first_photo"]["small2_url"];
                                    }
                                    if (o["first_photo"]["small_url"] != null)
                                    {
                                        _photo.small_url = o["first_photo"]["small_url"];
                                    }
                                    if (o["first_photo"]["sort_order"] != null)
                                    {
                                        _photo.sort_order = o["first_photo"]["sort_order"];
                                    }
                                    if (o["first_photo"]["square_url"] != null)
                                    {
                                        _photo.square_url = o["first_photo"]["square_url"];
                                    }
                                    if (o["first_photo"]["thumbnail_url"] != null)
                                    {
                                        _photo.thumbnail_url = o["first_photo"]["thumbnail_url"];
                                    }
                                    if (o["first_photo"]["x_offset"] != null)
                                    {
                                        _photo.x_offset = o["first_photo"]["x_offset"];
                                    }
                                    if (o["first_photo"]["y_offset"] != null)
                                    {
                                        _photo.y_offset = o["first_photo"]["y_offset"];
                                    }
                                    db.photos.Add(_photo);
                                    try
                                    {
                                        db.SaveChanges();
                                    }
                                    catch (DbUpdateException ex)
                                    {
                                        string test = ex.Message;
                                        throw;
                                    }
                                }
                            }

                            //designer
                            if (o["designer"] != null)
                            {
                                int id = o["designer"]["id"];

                                if (db.pattern_author.Any(x => x.id == id))
                                {
                                }
                                else
                                {
                                    pattern_author designer = new pattern_author();
                                    _pattern.designer_id = o["designer"]["id"];
                                    designer.id          = o["designer"]["id"];
                                    if (o["designer"]["name"] != null)
                                    {
                                        designer.name = o["designer"]["name"];
                                    }
                                    if (o["designer"]["permalink"] != null)
                                    {
                                        designer.permalink = o["designer"]["permalink"];
                                    }
                                    designer.favorites_count = o["designer"]["favorites_count"];
                                    designer.patterns_count  = o["designer"]["patterns_count"];
                                    db.pattern_author.Add(designer);
                                    try
                                    {
                                        db.SaveChanges();
                                    }
                                    catch (DbUpdateException ex)
                                    {
                                        string test = ex.Message;
                                        throw;
                                    }
                                }
                            }

                            _pattern.pattern_author_id = o["pattern_author"]["id"];
                            //pattern_author
                            if (o["pattern_author"] != null)
                            {
                                int id = o["pattern_author"]["id"];
                                if (db.pattern_author.Any(x => x.id == id))
                                {
                                }
                                else
                                {
                                    pattern_author _pattern_author = new pattern_author();
                                    _pattern.designer_id = o["pattern_author"]["id"];
                                    _pattern_author.id   = o["pattern_author"]["id"];
                                    if (o["pattern_author"]["name"] != null)
                                    {
                                        _pattern_author.name = o["pattern_author"]["name"];
                                    }
                                    if (o["pattern_author"]["permalink"] != null)
                                    {
                                        _pattern_author.name = o["pattern_author"]["permalink"];
                                    }
                                    _pattern_author.favorites_count = o["pattern_author"]["favorites_count"];
                                    _pattern_author.patterns_count  = o["pattern_author"]["patterns_count"];

                                    db.pattern_author.Add(_pattern_author);
                                    try
                                    {
                                        db.SaveChanges();
                                    }
                                    catch (DbUpdateException ex)
                                    {
                                        string test = ex.Message;
                                        throw;
                                    }
                                }
                            }

                            db.patterns.Add(_pattern);
                            try
                            {
                                db.SaveChanges();
                            }
                            catch (DbUpdateException ex)
                            {
                                string test = ex.Message;
                                throw;
                            }
                        }
                    }
                }
            }

            /*
             * //  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://api.ravelry.com/needles/sizes.json");
             *
             * HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://api.ravelry.com/needles/types.json");
             * request.Method = "GET";
             * request.ContentType = "application/json";
             * request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("A557BB258D37DE039AC3:VVaoS9R2Lvwhy_ToXF9AtyyBN9czTkD8IyTK7bvU"));
             *
             * HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             * using (Stream responseStream = response.GetResponseStream())
             * {
             *  StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
             *  JavaScriptSerializer js = new JavaScriptSerializer();
             *  var obj = js.Deserialize<dynamic>(reader.ReadToEnd());
             *
             *  needle_types type = new needle_types();
             *
             *
             *  foreach (var o in obj["needle_types"])
             *  {
             *      type = new needle_types();
             *      type.description = o["description"];
             *      type.needle_size_id = o["needle_size_id"];
             *      type.id = o["id"];
             *      type.type_name = o["type_name"];
             *      type.name = o["name"];
             *      type.length = o["length"];
             *      type.metric_name = o["metric_name"];
             *
             *      db.needle_types.Add(type);
             *      try
             *      {
             *          db.SaveChanges();
             *      }
             *      catch (DbUpdateException)
             *      {
             *          throw;
             *      }
             *
             *  }
             *
             *
             *
             * }
             *
             */
            /*
             *
             * using (Stream responseStream = response.GetResponseStream())
             * {
             *   StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
             *   JavaScriptSerializer js = new JavaScriptSerializer();
             *   var obj = js.Deserialize<dynamic>(reader.ReadToEnd());
             *
             *   needle_sizes size = new needle_sizes();
             *
             *
             *   foreach(var o in obj["needle_sizes"])
             *   {
             *       size = new needle_sizes();
             *       size.metric = o["metric"];
             *       size.us = o["us"];
             *       size.id = o["id"];
             *       size.hook = o["hook"];
             *
             *       db.needle_sizes.Add(size);
             *       try
             *       {
             *           db.SaveChanges();
             *       }
             *       catch (DbUpdateException)
             *       {
             *           throw;
             *       }
             *
             *   }
             *
             *
             *
             * }
             *
             */
        }
Exemple #21
0
 private void UploadCompleted(photo actual, object state, FacebookException e)
 {
     Assert.IsNotNull(actual);
     EnqueueTestComplete();
 }
Exemple #22
0
        public static upnpObject Create(FileInfo aInfo, string aArtworkUri, string aResourceUri)
        {
            // check for playlist file
            if (aInfo.Extension == Playlist.kPlaylistExtension)
            {
                playlistContainer playlist = new playlistContainer();
                resource          resource = new resource();
                playlist.Res.Add(resource);

                playlist.Id          = aInfo.FullName;
                playlist.Title       = aInfo.Name;
                playlist.WriteStatus = "PROTECTED";
                playlist.Restricted  = true;

                resource.Size = aInfo.Length;
                resource.Uri  = aResourceUri;

                return(playlist);
            }

            // check for audio/video file
            try
            {
                if (IsTagLibSupported(aInfo))
                {
                    TagLib.File f = TagLib.File.Create(aInfo.FullName);

                    if (f.Properties.MediaTypes == MediaTypes.Audio)
                    {
                        musicTrack track    = new musicTrack();
                        resource   resource = new resource();
                        track.Res.Add(resource);

                        track.Id          = aInfo.FullName;
                        track.WriteStatus = "PROTECTED";
                        track.Restricted  = true;

                        if (!f.Tag.IsEmpty)
                        {
                            if (f.Tag.Title != null)
                            {
                                track.Title = f.Tag.Title;
                            }
                            else
                            {
                                track.Title = aInfo.Name;
                            }
                            if (f.Tag.Album != null)
                            {
                                track.Album.Add(f.Tag.Album);
                            }
                            foreach (string g in f.Tag.Genres)
                            {
                                track.Genre.Add(g);
                            }
                            track.OriginalTrackNumber = (int)f.Tag.Track;
                            track.Date = f.Tag.Year.ToString();
                            foreach (string p in f.Tag.Performers)
                            {
                                artist performer = new artist();
                                performer.Artist = p;
                                performer.Role   = "Performer";
                                track.Artist.Add(performer);
                            }
                            foreach (string a in f.Tag.AlbumArtists)
                            {
                                artist artist = new artist();
                                artist.Artist = a;
                                artist.Role   = "AlbumArtist";
                                track.Artist.Add(artist);
                            }
                            foreach (string c in f.Tag.Composers)
                            {
                                artist composer = new artist();
                                composer.Artist = c;
                                composer.Role   = "Composer";
                                track.Artist.Add(composer);
                            }
                            if (f.Tag.Conductor != null)
                            {
                                artist conductor = new artist();
                                conductor.Artist = f.Tag.Conductor;
                                conductor.Role   = "Conductor";
                                track.Artist.Add(conductor);
                            }
                        }
                        else
                        {
                            track.Title = aInfo.Name;
                        }

                        resource.Bitrate         = (int)((f.Properties.AudioBitrate * 1000.0f) / 8.0f);
                        resource.Duration        = new Time((int)f.Properties.Duration.TotalSeconds).ToString();
                        resource.NrAudioChannels = f.Properties.AudioChannels;
                        resource.SampleFrequency = f.Properties.AudioSampleRate;
                        resource.Size            = aInfo.Length;
                        resource.Uri             = aResourceUri;

                        resource.ProtocolInfo = string.Format("http-get:*:{0}:*", f.MimeType.Replace("taglib", "audio"));
                        resource.ProtocolInfo = resource.ProtocolInfo.Replace("flac", "x-flac");
                        resource.ProtocolInfo = resource.ProtocolInfo.Replace("aif:", "aiff:");
                        resource.ProtocolInfo = resource.ProtocolInfo.Replace("wma", "x-ms-wma");
                        resource.ProtocolInfo = resource.ProtocolInfo.Replace("asf", "x-ms-asf");
                        resource.ProtocolInfo = resource.ProtocolInfo.Replace("mp3", "mpeg");
                        resource.ProtocolInfo = resource.ProtocolInfo.Replace("mpeg3", "mpeg");
                        resource.ProtocolInfo = resource.ProtocolInfo.Replace("m4a", "x-m4a");

                        if (!string.IsNullOrEmpty(aArtworkUri))
                        {
                            track.AlbumArtUri.Add(aArtworkUri);
                        }

                        return(track);
                    }
                    else if (f.Properties.MediaTypes == TagLib.MediaTypes.Video)
                    {
                        videoItem video    = new videoItem();
                        resource  resource = new resource();
                        video.Res.Add(resource);

                        video.Id          = aInfo.FullName;
                        video.WriteStatus = "PROTECTED";
                        video.Restricted  = true;

                        if (!f.Tag.IsEmpty)
                        {
                            if (f.Tag.Title != null)
                            {
                                video.Title = f.Tag.Title;
                            }
                            else
                            {
                                video.Title = aInfo.Name;
                            }
                            foreach (string g in f.Tag.Genres)
                            {
                                video.Genre.Add(g);
                            }
                            foreach (string p in f.Tag.Performers)
                            {
                                actor performer = new actor();
                                performer.Actor = p;
                                performer.Role  = "Actor";
                                video.Actor.Add(performer);
                            }
                        }
                        else
                        {
                            video.Title = aInfo.Name;
                        }

                        resource.Bitrate         = (int)((f.Properties.AudioBitrate * 1000.0f) / 8.0f);
                        resource.Duration        = new Time((int)f.Properties.Duration.TotalSeconds).ToString();
                        resource.NrAudioChannels = f.Properties.AudioChannels;
                        resource.SampleFrequency = f.Properties.AudioSampleRate;
                        resource.Size            = aInfo.Length;
                        resource.Uri             = aResourceUri;

                        resource.ProtocolInfo = string.Format("http-get:*:{0}:*", f.MimeType.Replace("taglib", "video"));

                        if (!string.IsNullOrEmpty(aArtworkUri))
                        {
                            video.AlbumArtUri.Add(aArtworkUri);
                        }

                        return(video);
                    }
                }
            }
            catch (TagLib.UnsupportedFormatException)
            {
            }
            catch (Exception e)
            {
                UserLog.WriteLine(aInfo.FullName + ": " + e.Message);
            }

            // check for image file
            string mimeType;

            if (IsImageFile(aInfo, out mimeType))
            {
                photo    photo    = new photo();
                resource resource = new resource();
                photo.Res.Add(resource);

                photo.Id          = aInfo.FullName;
                photo.Title       = aInfo.Name;
                photo.WriteStatus = "PROTECTED";
                photo.Restricted  = true;

                resource.Size         = aInfo.Length;
                resource.Uri          = aResourceUri;
                resource.ProtocolInfo = string.Format("http-get:*:{0}:*", mimeType);

                if (!string.IsNullOrEmpty(aArtworkUri))
                {
                    photo.AlbumArtUri.Add(aArtworkUri);
                }

                return(photo);
            }

            // all other types
            {
                item     item     = new item();
                resource resource = new resource();
                item.Res.Add(resource);

                item.Id          = aInfo.FullName;
                item.Title       = aInfo.Name;
                item.WriteStatus = "PROTECTED";
                item.Restricted  = true;

                resource.Size         = aInfo.Length;
                resource.Uri          = aResourceUri;
                resource.ProtocolInfo = string.Format("http-get:*:application/octet-stream:*");

                if (!string.IsNullOrEmpty(aArtworkUri))
                {
                    item.AlbumArtUri.Add(aArtworkUri);
                }

                return(item);
            }
        }
Exemple #23
0
 partial void Deletephoto(photo instance);
Exemple #24
0
 partial void Updatephoto(photo instance);
Exemple #25
0
 partial void Insertphoto(photo instance);
Exemple #26
0
        private void GetYarns()
        {
            string url = "https://api.ravelry.com/yarns/search.json?page=";

            for (int i = 1; i < 10000; i++)
            {
                var            newUrl  = url + i;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newUrl);
                request.Method      = "GET";
                request.ContentType = "application/json";
                request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("A557BB258D37DE039AC3:VVaoS9R2Lvwhy_ToXF9AtyyBN9czTkD8IyTK7bvU"));

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader         reader = new StreamReader(responseStream, Encoding.UTF8);
                    JavaScriptSerializer js     = new JavaScriptSerializer();
                    var obj = js.Deserialize <dynamic>(reader.ReadToEnd());

                    yarn _yarn = new yarn();


                    foreach (var o in obj["yarns"])
                    {
                        _yarn = new yarn();

                        _yarn.id = o["id"];


                        if (db.yarns.Any(x => x.id == _yarn.id))
                        {
                        }
                        else
                        {
                            if (o["yarn_company_name"] != null)
                            {
                                _yarn.yarn_company_name = o["yarn_company_name"];
                            }
                            if (o["rating_total"] != null)
                            {
                                _yarn.rating_total = o["rating_total"];
                            }
                            if (o["max_gauge"] != null)
                            {
                                _yarn.max_gauge = o["max_gauge"];
                            }
                            if (o["permalink"] != null)
                            {
                                _yarn.permalink = o["permalink"];
                            }
                            if (o["min_gauge"] != null)
                            {
                                _yarn.min_gauge = o["min_gauge"];
                            }
                            if (o["grams"] != null)
                            {
                                _yarn.grams = o["grams"];
                            }
                            if (o["discontinued"] != null)
                            {
                                _yarn.discontinued = o["discontinued"];
                            }
                            if (o["gauge_divisor"] != null)
                            {
                                _yarn.gauge_divisor = o["gauge_divisor"];
                            }
                            if (o["texture"] != null)
                            {
                                _yarn.texture = o["texture"];
                            }
                            if (o["name"] != null)
                            {
                                _yarn.name = o["name"];
                            }
                            if (o["rating_average"] != null)
                            {
                                _yarn.rating_average = o["rating_average"];
                            }
                            if (o["machine_washable"] != null)
                            {
                                _yarn.machine_washable = o["machine_washable"];
                            }
                            if (o["yardage"] != null)
                            {
                                _yarn.yardage = o["yardage"];
                            }


                            //photo
                            if (o["first_photo"] != null)
                            {
                                photo _photo = new photo();
                                _yarn.first_photo_id = o["first_photo"]["id"];
                                int photoId = o["first_photo"]["id"];
                                if (db.photos.Any(x => x.id == photoId))
                                {
                                }
                                else
                                {
                                    _photo.id            = photoId;
                                    _yarn.first_photo_id = o["first_photo"]["id"];
                                    if (o["first_photo"]["caption"] != null)
                                    {
                                        _photo.caption = o["first_photo"]["caption"];
                                    }
                                    if (o["first_photo"]["caption_html"] != null)
                                    {
                                        _photo.caption_html = o["first_photo"]["caption_html"];
                                    }
                                    if (o["first_photo"]["copyright_holder"] != null)
                                    {
                                        _photo.copyright_holder = o["first_photo"]["copyright_holder"];
                                    }
                                    if (o["first_photo"]["medium2_url"] != null)
                                    {
                                        _photo.medium2_url = o["first_photo"]["medium2_url"];
                                    }
                                    if (o["first_photo"]["small2_url"] != null)
                                    {
                                        _photo.small2_url = o["first_photo"]["small2_url"];
                                    }
                                    if (o["first_photo"]["small_url"] != null)
                                    {
                                        _photo.small_url = o["first_photo"]["small_url"];
                                    }
                                    if (o["first_photo"]["sort_order"] != null)
                                    {
                                        _photo.sort_order = o["first_photo"]["sort_order"];
                                    }
                                    if (o["first_photo"]["square_url"] != null)
                                    {
                                        _photo.square_url = o["first_photo"]["square_url"];
                                    }
                                    if (o["first_photo"]["thumbnail_url"] != null)
                                    {
                                        _photo.thumbnail_url = o["first_photo"]["thumbnail_url"];
                                    }
                                    if (o["first_photo"]["x_offset"] != null)
                                    {
                                        _photo.x_offset = o["first_photo"]["x_offset"];
                                    }
                                    if (o["first_photo"]["y_offset"] != null)
                                    {
                                        _photo.y_offset = o["first_photo"]["y_offset"];
                                    }
                                    db.photos.Add(_photo);
                                    try
                                    {
                                        db.SaveChanges();
                                    }
                                    catch (DbUpdateException ex)
                                    {
                                        string test = ex.Message;
                                        throw;
                                    }
                                }
                            }

                            try
                            {
                                if (o["yarn_weight"] != null)
                                {
                                    int id = o["yarn_weight"]["id"];
                                    _yarn.yarn_weight_id = id;
                                    if (db.yarn_weight.Any(x => x.id == id))
                                    {
                                    }
                                    else
                                    {
                                        yarn_weight yarnWeight = new yarn_weight();
                                        _yarn.yarn_weight_id = id;
                                        yarnWeight.id        = o["yarn_weight"]["id"];
                                        if (o["yarn_weight"]["ply"] != null)
                                        {
                                            yarnWeight.ply = o["yarn_weight"]["ply"];
                                        }
                                        if (o["yarn_weight"]["crochet_gauge"] != null)
                                        {
                                            yarnWeight.crochet_gauge = o["yarn_weight"]["crochet_gauge"];
                                        }
                                        if (o["yarn_weight"]["wpi"] != null)
                                        {
                                            yarnWeight.wpi = o["yarn_weight"]["wpi"];
                                        }
                                        if (o["yarn_weight"]["name"] != null)
                                        {
                                            yarnWeight.name = o["yarn_weight"]["name"];
                                        }
                                        if (o["yarn_weight"]["knit_gauge"] != null)
                                        {
                                            yarnWeight.name = o["yarn_weight"]["knit_gauge"];
                                        }


                                        db.yarn_weight.Add(yarnWeight);
                                        try
                                        {
                                            db.SaveChanges();
                                        }
                                        catch (DbUpdateException ex)
                                        {
                                            string test = ex.Message;
                                            throw;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                var test = ex.Message;
                            }
                            //designer



                            db.yarns.Add(_yarn);
                            try
                            {
                                db.SaveChanges();
                            }
                            catch (DbUpdateException ex)
                            {
                                string test = ex.Message;
                                throw;
                            }
                        }
                    }
                }
            }

            /*
             * //  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://api.ravelry.com/needles/sizes.json");
             *
             * HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://api.ravelry.com/needles/types.json");
             * request.Method = "GET";
             * request.ContentType = "application/json";
             * request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("A557BB258D37DE039AC3:VVaoS9R2Lvwhy_ToXF9AtyyBN9czTkD8IyTK7bvU"));
             *
             * HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             * using (Stream responseStream = response.GetResponseStream())
             * {
             *  StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
             *  JavaScriptSerializer js = new JavaScriptSerializer();
             *  var obj = js.Deserialize<dynamic>(reader.ReadToEnd());
             *
             *  needle_types type = new needle_types();
             *
             *
             *  foreach (var o in obj["needle_types"])
             *  {
             *      type = new needle_types();
             *      type.description = o["description"];
             *      type.needle_size_id = o["needle_size_id"];
             *      type.id = o["id"];
             *      type.type_name = o["type_name"];
             *      type.name = o["name"];
             *      type.length = o["length"];
             *      type.metric_name = o["metric_name"];
             *
             *      db.needle_types.Add(type);
             *      try
             *      {
             *          db.SaveChanges();
             *      }
             *      catch (DbUpdateException)
             *      {
             *          throw;
             *      }
             *
             *  }
             *
             *
             *
             * }
             *
             */
            /*
             *
             * using (Stream responseStream = response.GetResponseStream())
             * {
             *   StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
             *   JavaScriptSerializer js = new JavaScriptSerializer();
             *   var obj = js.Deserialize<dynamic>(reader.ReadToEnd());
             *
             *   needle_sizes size = new needle_sizes();
             *
             *
             *   foreach(var o in obj["needle_sizes"])
             *   {
             *       size = new needle_sizes();
             *       size.metric = o["metric"];
             *       size.us = o["us"];
             *       size.id = o["id"];
             *       size.hook = o["hook"];
             *
             *       db.needle_sizes.Add(size);
             *       try
             *       {
             *           db.SaveChanges();
             *       }
             *       catch (DbUpdateException)
             *       {
             *           throw;
             *       }
             *
             *   }
             *
             *
             *
             * }
             *
             */
        }
        public static List<photo> getPhotoData(string url)
        {
            JObject response = JObject.Parse(performWebRequest(url));
            List<photo> photos = new List<photo>();

            foreach (JToken token in response["data"])
            {
                photo curphoto = new photo();
                curphoto.id = token["id"].ToString();
                JEnumerable<JToken> children = token.Children();
                curphoto.name = token.Value<string>("name") ?? "";
                photos.Add(curphoto);
            }

            string next = response["paging"].Value<string>("next");

            if (response["paging"].Value<string>("next") != null)
                photos.AddRange(getPhotoData(response["paging"]["next"].ToString()));

            return photos;
        }