Ejemplo n.º 1
0
        public static async Task DownloadPhoto(PhotoItem photo, String path, ProgressBar ProgressBar)
        {
            try
            {
                if (path[path.Length - 1] != '\\')
                {
                    path = path + "\\";
                }
                var fileName = photo.UrlPhoto;
                if (fileName.Length > 40)
                {
                    fileName = fileName.Substring(0, 40);
                }
                fileName = fileName.Replace(":", "").Replace("\\", "").Replace("/", "").Replace("*", "").Replace("?", "").Replace("\"", "");
                using (var client = new WebClient())
                {

                    client.DownloadProgressChanged += (o, args) =>
                    {
                        ProgressBar.Value = args.ProgressPercentage;
                    };
                    client.DownloadFileCompleted += (o, args) =>
                    {
                        ProgressBar.Value = 0;
                    };
                    await client.DownloadFileTaskAsync(new Uri(photo.UrlPhoto), path + fileName + ".jpg");
                }
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 2
0
        public async void add_Book(object sender, ItemClickEventArgs e)
        {
            var           localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            String        uniqueId      = "book" + localSettings.Values["bookCount"].ToString();
            PhotoItem     selImage      = (PhotoItem)e.ClickedItem;
            String        imageName     = selImage.Name;
            StorageFolder imageFolder   = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync(selImage.Loc.Replace("/", "\\"));

            StorageFile storageFile = await imageFolder.GetFileAsync(imageName);

            imageFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync("thumbs");

            await storageFile.CopyAsync(imageFolder, uniqueId + ".jpg");

            var books = new Book(compositelocal["uniqueid"].ToString(), compositelocal["title"].ToString(), compositelocal["author"].ToString(),
                                 compositelocal["image"].ToString(), compositelocal["location"].ToString());

            BookSource.AddBookAsync(books);
            if (localSettings.Containers.ContainsKey("booksContainer"))
            {
                localSettings.Containers["booksContainer"].Values[uniqueId] = compositelocal;
                int count = (int)localSettings.Values["bookCount"];
                localSettings.Values["bookCount"] = ++count;
            }
            //this.Add.IsEnabled = true;
            this.imageGrid.Visibility   = Windows.UI.Xaml.Visibility.Collapsed;
            this.imageGridViewText.Text = "";
            BookPhotos.Photos.Clear();
            //this.pbar.IsIndeterminate = false;
            storageFile = null;
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> AddPhoto(PhotoItem newProduct)
        {
            _logger.LogInformation($"Add new photo item is called");

            //Call API to add new product
            var response = await _client.AddNewProduct(newProduct);

            //check response for errors
            if (response.IsSuccessStatusCode)
            {
                var modelJson = await response.Content.ReadAsStringAsync();

                var model = JsonConvert.DeserializeObject <PhotoItem>(modelJson);
                ViewData["PhotoModel"]      = model;
                ViewData["NewPhotoId"]      = model.Id;
                ViewData["Camera"]          = model.Camera;
                ViewData["ProgressMessage"] = "New photo description added";
                return(View("Index"));
            }
            else
            {
                _logger.LogError("Error happened during adding new photo", response.ReasonPhrase.ToString());
                ViewData["ErrorMessage"] = "Error happened while adding photo description";
                return(View("Index"));
            }
        }
Ejemplo n.º 4
0
        // photo taken or loaded
        async Task SetNewPhoto(Plugin.Media.Abstractions.MediaFile photo)
        {
            if (photo != null)
            {
                PreviewImage = ImageSource.FromStream(() => { return(photo.GetStream()); });
                OnPropertyChanged("PreviewImage");
                IsPhotoSet = true;
                OnPropertyChanged("IsPhotoSet");

                // update photo properties
                PhotoFilePath = photo.Path;
                PhotoTime     = DateTime.Now;
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
                PhotoLocation = await Geolocation.GetLocationAsync(request);

                // set current PhotoItem object
                PhotoItemObject = new PhotoItem(PhotoFilePath, PhotoLocation, PhotoTime);
                PhotoItemObject.PhotoPosition = new Position(PhotoLocation.Latitude, PhotoLocation.Longitude);

                // reset category picker
                for (int i = 0; i < AllCategories.Count; i++)
                {
                    AllCategories[i].IsChecked = false;
                }
            }
        }
        public async Task GetAllProducts_InitializedSuccessfully_ReturnsOkay()
        {
            // Arrange
            var photoItems = new List <PhotoItem>();
            var photoItem  = new PhotoItem
            {
                Id          = Guid.NewGuid().ToString(),
                Camera      = "Diana",
                Description = "Photo taken with Diana camera",
                Name        = "My favorite photo",
                Film        = "Kodak"
            };

            photoItems.Add(photoItem);


            var productController = new ProductController(_loggerMock.Object, _docService.Object, _blobService.Object);

            _docService.Setup(x => x.GetProductsAsync()).ReturnsAsync(photoItems);

            // Act
            var result = await productController.GetAllProducts();

            // Assert
            var jsonResult       = result as JsonResult;
            var photoItemsResult = jsonResult.Value as List <PhotoItem>;

            Assert.AreEqual(1, photoItems.Count);
            Assert.AreEqual(photoItem.Id, photoItemsResult[0].Id);
        }
Ejemplo n.º 6
0
        private void OpenPhoto(object sender, MouseButtonEventArgs e)
        {
            try
            {
                PhotoAlbumsResponse selectedAlbum = (PhotoAlbumsResponse)Albums.SelectedItem;
                PhotoItem           selected      = (PhotoItem)photoListBox.SelectedItem;
                if (selected != null)
                {
                    string userId;
                    if (UserNameOrIdForPhotoAlbums.Text == "")
                    {
                        userId = VkAccount.UserId;
                    }
                    else
                    {
                        userId = UserNameOrIdForPhotoAlbums.Text;
                    }
                    var users = General.GetUsersInfo(userId);

                    var PhotoWindow = new PhotoWindow();
                    PhotoWindow.Show();
                    PhotoWindow.PhotoBrowser.Navigate(String.Format(selected.UrlPhoto));
                    PhotoWindow.Title = String.Format("Photo of {0} {1} from {2}", users.response[0].first_name, users.response[0].last_name, selectedAlbum.PhotoAlbumTitle);
                }
            }
            catch (Exception) { }
        }
Ejemplo n.º 7
0
        protected async override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.activity_image_detail);
            ActionBar.SetDisplayHomeAsUpEnabled(true);
            ActionBar.SetDisplayShowHomeEnabled(true);
            ActionBar.SetIcon(Android.Resource.Color.Transparent);

            var id = Intent.GetIntExtra("id", 0);

            item = Photos.GetPhoto(id);
            if (item == null)
            {
                return;
            }

            name   = FindViewById <TextView> (Resource.Id.name);
            colors = FindViewById <LinearLayout> (Resource.Id.colors);
            var image = FindViewById <ImageView> (Resource.Id.image);

            image.SetImageResource(item.Image);
            name.Text = ActionBar.Title = item.Name;

            FindViewById <Button> (Resource.Id.apply_palette).Click += async(sender, e) => {
                var bitmap = await BitmapFactory.DecodeResourceAsync(Resources, item.Image);

                //generates the pallet with 16 samples(default)
                //Contact images/avatars: optimal values are 24-32
                //Landscapes: optimal values are 8-16
                Palette.GenerateAsync(bitmap, 16, this);
            };
        }
Ejemplo n.º 8
0
 private void setPhotosFromJsonArr(JsonArray photos)
 {
     this._photos = new Collection <PhotoItem>();
     foreach (var pl in photos)
     {
         JsonObject photo = pl.GetObject();
         PhotoItem  p     = new PhotoItem();
         if (photo.ContainsKey(STR_CAPTION))
         {
             p.Caption = photo.GetNamedString(STR_CAPTION);
         }
         if (photo.ContainsKey(STR_ALT_SIZES))
         {
             JsonObject first = photo.GetNamedArray(STR_ALT_SIZES).First().GetObject();
             if (first.ContainsKey(STR_URL))
             {
                 p.Url = first.GetNamedString(STR_URL);
             }
             if (first.ContainsKey(STR_WIDTH))
             {
                 p.Width = (int)first.GetNamedNumber(STR_WIDTH);
             }
             if (first.ContainsKey(STR_HEIGHT))
             {
                 p.Height = (int)first.GetNamedNumber(STR_HEIGHT);
             }
         }
         this._photos.Add(p);
     }
 }
Ejemplo n.º 9
0
        private void TakePicture_Click(object sender, RoutedEventArgs e)
        {
            if (cam != null)
            {
                try
                {
                    // Start image capture.
                    cam.CaptureImage();
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke(delegate()
                    {
                        // Cannot capture an image until the previous capture has completed.
                        // txtDebug.Text = ex.Message;
                    });
                }
            }

            string fileName = "isostore:" + savedCounter + "_th.jpg";

            // Create a new picture caption item based on the text box.
            PhotoItem newPhoto = new PhotoItem {
                PhotoCaption = newCaptionTextBox.Text, PhotoFileName = fileName
            };

            // Add a to-do item to the observable collection.
            App.ViewModel.AddNewPhoto(newPhoto);
        }
        public async Task GetProductById_InitializedSuccessfully_ReturnsOkay()
        {
            // Arrange
            var photoItem = new PhotoItem
            {
                Id          = Guid.NewGuid().ToString(),
                Camera      = "Diana",
                Description = "Photo taken with Diana camera",
                Name        = "My favorite photo",
                Film        = "Kodak"
            };

            var productController = new ProductController(_loggerMock.Object, _docService.Object, _blobService.Object);

            _docService.Setup(x => x.GetProductAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(photoItem);

            // Act
            var result = await productController.GetProductById("123", "Diana");

            // Assert
            var jsonResult       = result as JsonResult;
            var photoItemsResult = jsonResult.Value as PhotoItem;

            Assert.AreEqual(photoItem.Id, photoItemsResult.Id);
        }
Ejemplo n.º 11
0
        private void OnFurniList(DataInterceptedEventArgs e)
        {
            e.Continue();

            IEnumerable <CHItem> items = CHItem.Parse(e.Packet)
                                         .Where(i => i.TypeId == 3 && !Photos.ContainsKey(i.Id));

            int itemCount = items.Count();

            HabboAlert alert = AlertBuilder.CreateAlert(HabboAlertType.Bubble,
                                                        (itemCount == 0 ? Constants.SCANNING_EMPTY : itemCount.ToString())
                                                        + (itemCount == 1 ? Constants.SCANNING_SINGLE : Constants.SCANNING_MULTI)
                                                        + Constants.SCANNING_INVENTORY_DONE)
                               .WithImageUrl(Constants.BASE_URL + Constants.BUBBLE_ICON_URL);

            Connection.SendToClientAsync(alert.ToPacket(In.NotificationDialog));

            //TODO: Show user the queueu in photo processing pipeline

            _isProcessingItems = true;

            //Send all photo items in inventory to photo data processing pipeline.
            foreach (CHItem item in items)
            {
                var photoItem = PhotoItem.Create(item.Id, item.ExtraData, Hotel, SessionUsername,
                                                 roomId: null);

                _photoPublishingQueue.Enqueue(photoItem);
            }
        }
Ejemplo n.º 12
0
 public static async Task DownloadPhoto(PhotoItem photo, String path, ProgressBar ProgressBar)
 {
     try
     {
         if (path[path.Length - 1] != '\\')
         {
             path = path + "\\";
         }
         var fileName = photo.UrlPhoto;
         if (fileName.Length > 40)
         {
             fileName = fileName.Substring(0, 40);
         }
         fileName = fileName.Replace(":", "").Replace("\\", "").Replace("/", "").Replace("*", "").Replace("?", "").Replace("\"", "");
         using (var client = new WebClient())
         {
             client.DownloadProgressChanged += (o, args) =>
             {
                 ProgressBar.Value = args.ProgressPercentage;
             };
             client.DownloadFileCompleted += (o, args) =>
             {
                 ProgressBar.Value = 0;
             };
             await client.DownloadFileTaskAsync(new Uri(photo.UrlPhoto), path + fileName + ".jpg");
         }
     }
     catch (Exception)
     {
     }
 }
        public void Initialize()
        {
            var photoItem1 = new PhotoItem
            {
                Id = Guid.NewGuid().ToString(), Name = "Selfie", Description = "Selfie in the night", Camera = "Lomo", Film = "Kodak"
            };

            var photoItem2 = new PhotoItem
            {
                Id = Guid.NewGuid().ToString(), Name = "Double exposure", Description = "Same frame exposed twice", Camera = "Diana", Film = "Kodak"
            };

            _photos = new List <PhotoItem>();
            _photos.Add(photoItem1);
            _photos.Add(photoItem2);

            var serializedStrings = JsonConvert.SerializeObject(_photos);
            var serializedString  = JsonConvert.SerializeObject(photoItem1);

            _loggerMock = new Mock <ILogger <ProductController> >();

            _httpClientMock = new Mock <IHttCustomClient>();
            _httpClientMock.Setup(x => x.GetAllProducts()).ReturnsAsync(serializedStrings);
            _httpClientMock.Setup(x => x.GetProductById(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(serializedString);
        }
Ejemplo n.º 14
0
        public void Url_GetAndSetShould_WorkProperly(string randomString)
        {
            var obj = new PhotoItem();

            obj.Url = randomString;

            Assert.AreEqual(randomString, obj.Url);
        }
Ejemplo n.º 15
0
        public void IsDeleted_GetAndSetShould_WorkProperly(bool value)
        {
            var obj = new PhotoItem();

            obj.IsDeleted = value;

            Assert.AreEqual(value, obj.IsDeleted);
        }
Ejemplo n.º 16
0
        public void Id_GetAndSetShould_WorkProperly(int randomNumber)
        {
            var obj = new PhotoItem();

            obj.Id = randomNumber;

            Assert.AreEqual(randomNumber, obj.Id);
        }
Ejemplo n.º 17
0
        public async Task <HttpResponseMessage> AddNewProduct(PhotoItem product)
        {
            var httpContent = CreateStringContent(product);

            var response = await _httpClient.PostAsync($"{_productRoute}/{_photoItemRoute}", httpContent);

            return(response);
        }
Ejemplo n.º 18
0
 private void PhotoItemControl_Tapped(object sender, TappedRoutedEventArgs e)
 {
     selected         = true;
     photoitemcontrol = (PhotoItemControl)sender;
     x         = sender;
     photoitem = photoitemcontrol.PhotoItem;
     deletePicButton.Visibility = Visibility.Visible;
     changeView();
 }
Ejemplo n.º 19
0
        public ImageModel(string url, PhotoItem photoItem, PhotoStationClient client)
        {
            Url    = url;
            Client = client;
            var info = photoItem.info;

            Width  = !info.rotated ? info.resolutionx : info.resolutiony;
            Height = !info.rotated ? photoItem.info.resolutiony : info.resolutionx;
        }
Ejemplo n.º 20
0
        public void Initialize()
        {
            _photoItem = new PhotoItem
            {
                Id = Guid.NewGuid().ToString(), Name = "Selfie", Description = "Selfie in the night", Camera = "Lomo", Film = "Kodak"
            };

            _loggerMock = new Mock <ILogger <AdminController> >();
        }
Ejemplo n.º 21
0
    void CreateItem(int index)
    {
        GameObject gonew = GameObject.Instantiate(_ItemPrefab);

        gonew.transform.parent     = _Container;
        gonew.transform.localScale = Vector3.one;
        PhotoItem item = gonew.GetComponent <PhotoItem>();

        item.LoadPhoto(this, Application.streamingAssetsPath + "/Photo/" + (index % 10 + 1).ToString() + ".jpg");
    }
        public void PhotoItem_VerifyNumberOfProperties()
        {
            var obj = new PhotoItem();

            var result = obj.GetType()
                         .GetProperties()
                         .Count();

            Assert.AreEqual(5, result);
        }
Ejemplo n.º 23
0
        public void DeletePhotoItemTest()
        {
            var item = _repository.ReadPhotoItems().FirstOrDefault();

            if (item == null)
            {
                //Arrange
                //Setup a PhotoItem
                var userA = new User()
                {
                    Id = 1, Name = "Teddy", Role_FK = (int)Permission.Guest
                };
                var userB = new User()
                {
                    Id = 2, Name = "Cathrine", Role_FK = (int)Permission.Administrator
                };

                PhotoItem photoitem = new PhotoItem()
                {
                    UserName = userA.Name, Info = "In the Dessert..", Country = "USA", Location = "Salt Lake City", Latitude = 1.1, Longitude = 2.2, TimeStamp = DateTime.Now, Photo = new Photo()
                    {
                        Binary = new byte[] { 1, 0, 1 }
                    }
                };
                _repository.CreateOrUpdatePhotoItem(photoitem);

                var commentA = new Comment()
                {
                    Text = "What a day!", UserName = userA.Name, TimeStamp = DateTime.Now
                };
                var commentB = new Comment()
                {
                    Text = "Good photo", UserName = userB.Name, TimeStamp = DateTime.Now
                };

                //Act
                photoitem.AddComment(commentA);
                photoitem.AddComment(commentB);

                _repository.CreateOrUpdatePhotoItem(photoitem);
            }

            item = _repository.ReadPhotoItems().FirstOrDefault();

            _repository.DeletePhotoItem(item);

            var context       = new EFDbContext();
            var itemresult    = context.PhotoItems.Find(item.Id);
            var photoresult   = context.Photos.Find(item.Id);
            var commentresult = context.Comments.Where(p => p.PhotoItem_FK == item.Id);

            Assert.IsNull(itemresult);
            Assert.IsNull(photoresult);
            Assert.IsEmpty(commentresult);
        }
Ejemplo n.º 24
0
        public void PhotoItem_ShouldImplement_IDbModelInterface()
        {
            var obj = new PhotoItem();

            var result = obj.GetType()
                         .GetInterfaces()
                         .Where(x => x == typeof(IDbModel))
                         .Any();

            Assert.IsTrue(result);
        }
Ejemplo n.º 25
0
        internal void AddNewPhoto(PhotoItem newPhoto)
        {
            // Add a to-do item to the data context.
            PhotoDB.PhotoItems.InsertOnSubmit(newPhoto);

            // Save changes to the database.
            PhotoDB.SubmitChanges();

            // Add a to-do item to the "all" observable collection.
            PhotoItems.Add(newPhoto);
        }
Ejemplo n.º 26
0
        public void Url_ShouldHave_MaxLengthAttribute()
        {
            var obj = new PhotoItem();

            var result = obj.GetType()
                         .GetProperty("Url")
                         .GetCustomAttributes(false)
                         .Where(x => x.GetType() == typeof(MaxLengthAttribute))
                         .Any();

            Assert.IsTrue(result);
        }
Ejemplo n.º 27
0
        public void Id_ShouldHave_KeyAttribute()
        {
            var obj = new PhotoItem();

            var result = obj.GetType()
                         .GetProperty("Id")
                         .GetCustomAttributes(false)
                         .Where(x => x.GetType() == typeof(KeyAttribute))
                         .Any();

            Assert.IsTrue(result);
        }
Ejemplo n.º 28
0
        public bool DeletePhotoItem(PhotoItem item)
        {
            _context.PhotoItems.Remove(item);
            _context.SaveChanges();

            if (_context.PhotoItems.Find(item.Id) != null)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Ejemplo n.º 29
0
        public void Url_ShouldHave_RightMaxValueFor_RequiredAttribute()
        {
            var obj = new PhotoItem();

            var result = obj.GetType()
                         .GetProperty("Url")
                         .GetCustomAttributes(false)
                         .Where(x => x.GetType() == typeof(MaxLengthAttribute))
                         .Select(x => (MaxLengthAttribute)x)
                         .SingleOrDefault();

            Assert.IsNotNull(result);
            Assert.AreEqual(ValidationConstants.UrlLengthMaxValue, result.Length);
        }
Ejemplo n.º 30
0
         public static List<PhotoItem> getPhotos()
         {
             PhotoItem one = new PhotoItem();
             one.Photo = new BitmapImage(new Uri("",UriKind.Relative));
             one.Name = "Image1";
 
             PhotoItem two = new PhotoItem();
             two.Photo = new BitmapImage(new Uri("", UriKind.Relative));
             two.Name = "Image1";
 
             List<PhotoItem> Photos = new List<PhotoItem>();
             Photos.Add(one);
             return Photos;
         }
Ejemplo n.º 31
0
        public PhotoItem[] GetPhotosByCollection(String nickname, String password, String webPhotoCollectionID)
        {
            if (String.IsNullOrEmpty(nickname))
            {
                throw new ArgumentNullException("nickname");
            }
            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }
            if (String.IsNullOrEmpty(webPhotoCollectionID))
            {
                throw new ArgumentNullException("webPhotoCollectionID");
            }

            try
            {
                var member            = Member.GetMemberViaNicknamePassword(nickname, password);
                var photoCollection   = PhotoCollection.GetPhotoCollectionByWebPhotoCollectionID(webPhotoCollectionID);
                var photoCollectionID = photoCollection.PhotoCollectionID;
                var photos            = data.Photo.GetPhotoByPhotoCollectionIDWithJoin(photoCollectionID);

                var result = new PhotoItem[photos.Length];

                for (var i = 0; i < photos.Length; i++)
                {
                    var item = new PhotoItem();
                    item.WebPhotoID = photos[i].WebPhotoID;

                    if (photos[i].PhotoResourceFile != null)
                    {
                        item.MainPhotoURL = _baseUrl + photos[i].PhotoResourceFile.FullyQualifiedURL;
                    }
                    if (photos[i].ThumbnailResourceFile != null)
                    {
                        item.ThumbnailURL = _baseUrl + photos[i].ThumbnailResourceFile.FullyQualifiedURL;
                    }

                    result[i] = item;
                }

                return(result);
            }
            catch (Exception e)
            {
                Log.Logger(String.Format(CultureInfo.InvariantCulture, "GetPhotosByCollection exception: {0}", e.Message), Identifier);
                Trace.Tracer(e.ToString());
                throw e;
            }
        }
Ejemplo n.º 32
0
        public ActionResult Detail(int photoItemID)
        {
            _pitm = new PhotoItem(photoItemID);

            if (_pitm.PhotoItemID == 0)
                return HttpNotFound();

            var sus = new StatusUpdates();

            var su = new StatusUpdate();

            su.GetStatusUpdateByPhotoID(photoItemID);

            su.PhotoDisplay = true;
            sus.Add(su);

            if (string.IsNullOrWhiteSpace(_pitm.Title))
            {
                _pitm.Title = String.Format("{0:u}", _pitm.CreateDate);
            }

            sus.IncludeStartAndEndTags = false;
            ViewBag.StatusUpdateList = string.Format(@"<ul id=""status_update_list_items"">{0}</ul>", sus.ToUnorderdList);

            var pitm2 = new PhotoItem();

            pitm2.GetPreviousPhoto(_pitm.CreateDate);
            if (pitm2.PhotoItemID > 0)
            {
                pitm2.ShowTitle = false;
                pitm2.UseThumb = true;
                ViewBag.PreviousPhoto = pitm2;
            }

            pitm2 = new PhotoItem();
            pitm2.GetNextPhoto(_pitm.CreateDate);

            if (pitm2.PhotoItemID > 0)
            {
                pitm2.ShowTitle = false;
                pitm2.UseThumb = true;
                ViewBag.NextPhoto = pitm2;
            }

            return View(_pitm);
        }
Ejemplo n.º 33
0
        public ActionResult Delete(int photoItemID)
        {
            _mu = MembershipWrapper.GetUser();

            _pitm = new PhotoItem(photoItemID);

            if (_mu == null || _pitm.CreatedByUserID != Convert.ToInt32(_mu.ProviderUserKey))
                return RedirectToAction("Index");

            var s3 = new S3Service
            {
                AccessKeyID = AmazonCloudConfigs.AmazonAccessKey,
                SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey
            };

            _pitm.Delete();

            if (string.IsNullOrEmpty(_pitm.FilePathStandard)) return RedirectToAction("Index");
            // delete the existing photos
            try
            {
                if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, _pitm.FilePathStandard))
                {
                    s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, _pitm.FilePathStandard);
                }

                if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, _pitm.FilePathRaw))
                {
                    s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, _pitm.FilePathRaw);
                }

                if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, _pitm.FilePathThumb))
                {
                    s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, _pitm.FilePathThumb);
                }
            }
            catch
            {
                // whatever
            }

            return RedirectToAction("Index");
        }
        public void GetPhotos()
        {
            //Read reviews into Arraylist
            string sAppPath = System.AppDomain.CurrentDomain.BaseDirectory;
            try
            {
                using (StreamReader sr = new StreamReader(String.Format("{0}/Files/Photos.txt", sAppPath), Encoding.GetEncoding("iso-8859-1")))
                {
                    int count = 0;
                    while (sr.Peek() >= 0)
                    {
                        String line = sr.ReadLine();
                        if (!string.IsNullOrEmpty(line))
                        {
                            string[] array;
                            array = line.Split('|');

                            //Convert the file string to Date
                            string[] format = { "dd/MM/yyyy" };
                            DateTime date;
                            DateTime.TryParseExact(array[5], format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date);

                            PhotoItem t = new PhotoItem(count, array[0], array[1], array[2], array[3], array[4], date);
                            if (t.Folder.Equals("Events"))
                            {
                                photos.Add(t);
                            }
                            ++count;
                        }
                    }
                }
                photos.Sort(new PhotoItemComparer());
            }
            catch (Exception)
            {
                Master.AddErrorMessage("An error occurred retrieving the photos. Please try again soon or contact the crèche for assistance.");
            }
        }
Ejemplo n.º 35
0
        public PhotoItem[] GetPhotosByCollection(String nickname, String password, String webPhotoCollectionID)
        {
            if (String.IsNullOrEmpty(nickname))
                throw new ArgumentNullException("nickname");
            if (String.IsNullOrEmpty(password))
                throw new ArgumentNullException("password");
            if (String.IsNullOrEmpty(webPhotoCollectionID))
                throw new ArgumentNullException("webPhotoCollectionID");

            try
            {
                var member = Member.GetMemberViaNicknamePassword(nickname, password);
                var photoCollection = PhotoCollection.GetPhotoCollectionByWebPhotoCollectionID(webPhotoCollectionID);
                var photoCollectionID = photoCollection.PhotoCollectionID;
                var photos = data.Photo.GetPhotoByPhotoCollectionIDWithJoin(photoCollectionID);

                var result = new PhotoItem[photos.Length];

                for (var i = 0; i < photos.Length; i++)
                {
                    var item = new PhotoItem();
                    item.WebPhotoID = photos[i].WebPhotoID;

                    if (photos[i].PhotoResourceFile != null)
                        item.MainPhotoURL = _baseUrl + photos[i].PhotoResourceFile.FullyQualifiedURL;
                    if (photos[i].ThumbnailResourceFile != null)
                        item.ThumbnailURL = _baseUrl + photos[i].ThumbnailResourceFile.FullyQualifiedURL;

                    result[i] = item;
                }

                return result;
            }
            catch (Exception e)
            {
                Log.Logger(String.Format(CultureInfo.InvariantCulture, "GetPhotosByCollection exception: {0}", e.Message), Identifier);
                Trace.Tracer(e.ToString());
                throw e;
            }
        }
Ejemplo n.º 36
0
        public ActionResult RotateStatusImage(int statusUpdateID)
        {
            mu = Membership.GetUser();

            StatusUpdate su = new StatusUpdate(statusUpdateID);

            if (su.PhotoItemID != null && su.PhotoItemID > 0)
            {
                var acl = CannedAcl.PublicRead;

                S3Service s3 = new S3Service();

                s3.AccessKeyID = AmazonCloudConfigs.AmazonAccessKey;
                s3.SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey;

                PhotoItem pitm = new PhotoItem(Convert.ToInt32(su.PhotoItemID));

                // full
                Image imgFull = DownloadImage(Utilities.S3ContentPath(pitm.FilePathRaw));

                float angle = 90;

                Bitmap b = RotateImage(imgFull, angle);

                System.Drawing.Image fullPhoto = (System.Drawing.Image)b;

                string fileNameFull = Guid.NewGuid() + ".jpg";

                Stream maker = fullPhoto.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameFull,
                    "image/jpg",
                    acl);

                if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw))
                {
                    s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw);
                }

                pitm.FilePathRaw = fileNameFull;

                // resized
                System.Drawing.Image photoResized = (System.Drawing.Image)b;

                string fileNameResize = Guid.NewGuid() + ".jpg";

                photoResized = ImageResize.FixedSize(photoResized, 500, 375, System.Drawing.Color.Black);

                maker = photoResized.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameResize,
                    "image/jpg",
                    acl);

                if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard))
                {
                    s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard);
                }

                pitm.FilePathStandard = fileNameResize;

                // thumb
                System.Drawing.Image thumbPhoto = (System.Drawing.Image)b;

                thumbPhoto = ImageResize.Crop(thumbPhoto, 150, 150, ImageResize.AnchorPosition.Center);

                string fileNameThumb = Guid.NewGuid() + ".jpg";

                maker = thumbPhoto.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameThumb,
                   "image/jpg",
                    acl);

                if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb))
                {
                    s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb);
                }

                pitm.FilePathThumb = fileNameThumb;

                pitm.Update();

            }

            return RedirectToAction("statusupdate", new { @statusUpdateID = statusUpdateID });
        }
Ejemplo n.º 37
0
        public ActionResult Home(string message, HttpPostedFileBase file)
        {
            if (string.IsNullOrWhiteSpace(message) && file == null)
            {
                return RedirectToAction("Home");
            }

            message = message.Trim();

            mu = Membership.GetUser();

            ua = new UserAccount(Convert.ToInt32(mu.ProviderUserKey));
            //StatusUpdates sus = null;

            ViewBag.CurrentUser = ua.ToUnorderdListItem;

            StatusUpdate su = new StatusUpdate();

            su.GetMostRecentUserStatus(ua.UserAccountID);

            DateTime startTime = Utilities.GetDataBaseTime();

            TimeSpan span = startTime.Subtract(su.CreateDate);

            //su = new StatusUpdate();
            // TODO: this is not working properly, preventing posts
            if (su.Message == message && file == null)
            {
                // double post
                return RedirectToAction("Home");
            }
            else
            {
                su = new StatusUpdate();
            }

            if (file != null && Utilities.IsImageFile(file.FileName))
            {
                Bitmap b = new Bitmap(file.InputStream);

                var acl = CannedAcl.PublicRead;

                S3Service s3 = new S3Service();

                s3.AccessKeyID = AmazonCloudConfigs.AmazonAccessKey;
                s3.SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey;

                PhotoItem pitem = new PhotoItem();

                pitem.CreatedByUserID = ua.UserAccountID;
                pitem.Title = message;

                // full
                System.Drawing.Image fullPhoto = (System.Drawing.Image)b;

                string fileNameFull = Utilities.CreateUniqueContentFilename(file);

                Stream maker = fullPhoto.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameFull,
                    file.ContentType,
                    acl);

                pitem.FilePathRaw = fileNameFull;

                // resized
                System.Drawing.Image photoResized = (System.Drawing.Image)b;

                string fileNameResize = Utilities.CreateUniqueContentFilename(file);

                photoResized = ImageResize.FixedSize(photoResized, 500, 375, System.Drawing.Color.Black);

                maker = photoResized.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameResize,
                    file.ContentType,
                    acl);

                pitem.FilePathStandard = fileNameResize;

                // thumb
                System.Drawing.Image thumbPhoto = (System.Drawing.Image)b;

                thumbPhoto = ImageResize.Crop(thumbPhoto, 150, 150, ImageResize.AnchorPosition.Center);

                string fileNameThumb = Utilities.CreateUniqueContentFilename(file);

                maker = thumbPhoto.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameThumb,
                    file.ContentType,
                    acl);

                pitem.FilePathThumb = fileNameThumb;

                pitem.Create();

                su.PhotoItemID = pitem.PhotoItemID;
            }

            su.UserAccountID = ua.UserAccountID;
            su.Message = message;
            su.CreatedByUserID = ua.UserAccountID;
            su.IsMobile = Request.Browser.IsMobileDevice;
            su.Create();

            if (Request.Browser.IsMobileDevice)
            {
                // this will bring them to the post
                return new RedirectResult(Url.Action("Home") + "#most_recent");
            }
            else
            {
                // the menu prevents brining to post correctly
                return RedirectToAction("Home");
            }
        }
Ejemplo n.º 38
0
        public ActionResult UserPhoto(string userName, int photoItemID)
        {
            _ua = new UserAccount(userName);

            ViewBag.UserName = _ua.UserName;

            _pitm = new PhotoItem(photoItemID);

            var sus = new StatusUpdates();

            var su = new StatusUpdate();

            su.GetStatusUpdateByPhotoID(photoItemID);

            su.PhotoDisplay = true;
            sus.Add(su);

            if (string.IsNullOrWhiteSpace(_pitm.Title))
            {
                _pitm.Title = String.Format("{0:u}", _pitm.CreateDate);
            }

            sus.IncludeStartAndEndTags = false;
            ViewBag.StatusUpdateList = @"<ul id=""status_update_list_items"">" + sus.ToUnorderdList + @"</ul>";

            var pitm2 = new PhotoItem();

            pitm2.GetPreviousPhotoForUser(_pitm.CreateDate, _ua.UserAccountID);
            if (pitm2.PhotoItemID > 0)
            {
                pitm2.IsUserPhoto = true;
                pitm2.ShowTitle = false;
                pitm2.UseThumb = true;
                ViewBag.PreviousPhoto = pitm2;
            }

            pitm2 = new PhotoItem();
            pitm2.GetNextPhotoForUser(_pitm.CreateDate, _ua.UserAccountID);

            if (pitm2.PhotoItemID <= 0) return View(_pitm);

            pitm2.IsUserPhoto = true;
            pitm2.ShowTitle = false;
            pitm2.UseThumb = true;
            ViewBag.NextPhoto = pitm2;

            return View(_pitm);
        }
        protected string CreatePhotoLineStringFromPhotoItem(int id, PhotoItem card)
        {
            try
            {
                //Create the new item
                String line = string.Empty;
                line += card.Folder + "|";
                line += card.Name + "|";
                line += card.Caption + "|";
                line += card.Height + "|";
                line += card.Width + "|";
                line += card.Date.ToString() + "|";
                line += System.Environment.NewLine;

                //Edit the photo item by replacing it with this nice new one
                return line;
            }
            catch (Exception)
            {
                Master.AddErrorMessage("There was an error adding a new item.");

            }
            return string.Empty;
        }
Ejemplo n.º 40
0
        public ActionResult Home(string message, HttpPostedFileBase file)
        {
            if (string.IsNullOrWhiteSpace(message) && file == null)
            {
                return RedirectToAction("Home");
            }

            if (message != null) message = message.Trim();

            if (_mu != null) _ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey));

            if (_ua.UserAccountID ==  18136)
            {
                // check if over posting user can take a hint to stop
                var lastUpdate = new StatusUpdate();
                lastUpdate.GetMostRecentUserStatus(_ua.UserAccountID);

                if (lastUpdate.CreateDate > DateTime.UtcNow.AddHours(-24))
                {
                    TempData["user_error"] =
                        "Please STOP posting so much, you are only allowed to post once ever 24 hours! Thank you for keeping the wall clean.";

                    return RedirectToAction("Home");
                }
            }

            ViewBag.CurrentUser = _ua.ToUnorderdListItem;

            var su = new StatusUpdate();

            su.GetMostRecentUserStatus(_ua.UserAccountID);

            DateTime startTime = DateTime.UtcNow;

            TimeSpan span = startTime.Subtract(su.CreateDate);

            // TODO: this is not working properly, preventing posts
            if (su.Message == message && file == null)
            {
                // double post
                return RedirectToAction("Home");
            }
            su = new StatusUpdate();

            if (file != null && Utilities.IsImageFile(file.FileName))
            {
                var b = new Bitmap(file.InputStream);

                const CannedAcl acl = CannedAcl.PublicRead;

                var s3 = new S3Service
                {
                    AccessKeyID = AmazonCloudConfigs.AmazonAccessKey,
                    SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey
                };

                var pitem = new PhotoItem {CreatedByUserID = _ua.UserAccountID, Title = message};

                Image fullPhoto = b;

                string fileNameFull = Utilities.CreateUniqueContentFilename(file);

                Stream maker = fullPhoto.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameFull,
                    file.ContentType,
                    acl);

                pitem.FilePathRaw = fileNameFull;

                // resized
                Image photoResized = b;

                string fileNameResize = Utilities.CreateUniqueContentFilename(file);

                photoResized = ImageResize.FixedSize(photoResized, 500, 375, Color.Black);

                maker = photoResized.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameResize,
                    file.ContentType,
                    acl);

                pitem.FilePathStandard = fileNameResize;

                // thumb
                Image thumbPhoto = b;

                thumbPhoto = ImageResize.Crop(thumbPhoto, 150, 150, ImageResize.AnchorPosition.Center);

                string fileNameThumb = Utilities.CreateUniqueContentFilename(file);

                maker = thumbPhoto.ToAStream(ImageFormat.Jpeg);

                s3.AddObject(
                    maker,
                    maker.Length,
                    AmazonCloudConfigs.AmazonBucketName,
                    fileNameThumb,
                    file.ContentType,
                    acl);

                pitem.FilePathThumb = fileNameThumb;

                pitem.Create();

                su.PhotoItemID = pitem.PhotoItemID;
            }

            su.UserAccountID = _ua.UserAccountID;
            su.Message = message;
            su.CreatedByUserID = _ua.UserAccountID;
            su.IsMobile = Request.Browser.IsMobileDevice;
            su.Create();

            if (Request.Browser.IsMobileDevice)
            {
                return new RedirectResult(Url.Action("Home") + "#most_recent");
            }
            return RedirectToAction("Home");
        }
        protected void EditItemFromForm()
        {
            int id = Convert.ToInt32(txtHiddenId.Value);
            try
            {
                //Convert the file string to Date
                if (!string.IsNullOrEmpty(txtPhotoDate.Value))
                {
                    string[] format = { "dd/MM/yyyy" };
                    DateTime date;
                    DateTime.TryParseExact(txtPhotoDate.Value.ToString(), format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date);

                    //Edit the photo item by replacing it with this nice new one
                    PhotoItem card = new PhotoItem(id, ddlFolder.Value, txtPhotoName.Value, txtCaption.Value, date);
                    PhotoItem p = (PhotoItem)folderPhotos[id];
                    photos.Remove(p);
                    photos.Insert(0, card);
                }
            }
            catch (Exception)
            {
                Master.AddErrorMessage("There was an error adding a new item.");
            }
        }
 protected void ShowItemInForm(int index, PhotoItem card)
 {
     txtHiddenId.Value = index.ToString();
     txtPhotoName.Value = card.Name;
     txtCaption.Value = card.Caption;
     txtPhotoDate.Value = card.Date.ToString("dd/MM/yyyy");
 }
Ejemplo n.º 43
0
 public PhotoSlice(LayoutManager pManager, int pID, PhotoItem pPhotoItem)
 {
     _id = pID;
     _manager = pManager;
     _photoItem = pPhotoItem;
 }
Ejemplo n.º 44
0
        public void ProcessRequest(HttpContext context)
        {
            //        context.Response.ContentType = "text/plain";

               //    context.Response.CacheControl = "no-cache";

               // context.Response.AddHeader("Pragma", "no-cache");

               // //context.Response.AddHeader("Pragma", "no-store");

               // //context.Response.AddHeader("cache-control", "no-cache");

               //context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

               // context.Response.Cache.SetNoServerCaching();

            if (string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.param_type.ToString()])) return;

            SiteEnums.QueryStringNames ptyc = (SiteEnums.QueryStringNames)Enum.Parse(typeof(SiteEnums.QueryStringNames),
                context.Request.QueryString[SiteEnums.QueryStringNames.param_type.ToString()]);

              //  Dictionary<string, Subgurim.Chat.Usuario> usrrs = null;
            StringBuilder sb = null;
            MembershipUser mu = null;

            switch (ptyc)
            {
                case SiteEnums.QueryStringNames.status_update:
                    #region status_update

                    string key = context.Request.QueryString[SiteEnums.QueryStringNames.status_update_id.ToString()];

                    if (string.IsNullOrEmpty(key))
                    {
                        key = context.Request.QueryString[SiteEnums.QueryStringNames.most_applauded_status_update_id.ToString()];
                    }

                    int statusUpdateID = Convert.ToInt32(key);

                    StatusUpdate statup = null;

                    if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_rsp.ToString()]))
                    {
                        mu = Membership.GetUser();

                        Acknowledgement ack = new Acknowledgement();

                        ack.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                        ack.UserAccountID = Convert.ToInt32(mu.ProviderUserKey);
                        ack.AcknowledgementType = Convert.ToChar(context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_rsp.ToString()]);
                        ack.StatusUpdateID = statusUpdateID;

                        statup = new StatusUpdate(statusUpdateID);

                        if (!Acknowledgement.IsUserAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey)))
                        {
                            ack.Create();

                            StatusUpdateNotification sun = new StatusUpdateNotification();

                            if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString()))
                            {
                                //  sun.GetStatusUpdateNotificationForUserStatus(Convert.ToInt32(mu.ProviderUserKey), statusUpdateID, SiteEnums.ResponseType.A);
                                sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.A);
                            }
                            else if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.B.ToString()))
                            {
                                //sun.GetStatusUpdateNotificationForUserStatus(Convert.ToInt32(mu.ProviderUserKey), statusUpdateID, SiteEnums.ResponseType.B);
                                sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.B);
                            }

                            if (Convert.ToInt32(mu.ProviderUserKey) != statup.UserAccountID)
                            {
                                sun.UserAccountID = statup.UserAccountID;

                                SiteEnums.ResponseType rspType = SiteEnums.ResponseType.U;

                                if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString()))
                                {
                                    rspType = SiteEnums.ResponseType.A;
                                    sun.ResponseType = Convert.ToChar(rspType.ToString());
                                }
                                else
                                {
                                    rspType = SiteEnums.ResponseType.B;
                                    sun.ResponseType = Convert.ToChar(rspType.ToString());
                                }

                                sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey);

                                if (sun.StatusUpdateNotificationID == 0)
                                {
                                    sun.IsRead = false;
                                    sun.Create();
                                }
                                else
                                {
                                    sun.IsRead = false;
                                    sun.Update();
                                }

                                SendNotificationEmail(statup.UserAccountID, rspType, sun.StatusUpdateID);
                            }

                            context.Response.Write(@"{""StatusAcks"": """ + HttpUtility.HtmlEncode(statup.StatusAcknowledgements) + @"""}");
                        }
                        else
                        {
                            // reverse

                            ack.GetAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey));

                            ack.Delete();

                            // TODO: DELETE NOTIFICATION

                            context.Response.Write(@"{""StatusAcks"": """ + HttpUtility.HtmlEncode(statup.StatusAcknowledgements) + @"""}");
                        }
                    }
                    else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_comment_rsp.ToString()]))
                    {
                        mu = Membership.GetUser();

                        StatusCommentAcknowledgement ack = new StatusCommentAcknowledgement();

                        ack.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                        ack.UserAccountID = Convert.ToInt32(mu.ProviderUserKey);
                        ack.AcknowledgementType = Convert.ToChar(context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_comment_rsp.ToString()]);
                        ack.StatusCommentID = statusUpdateID; // this is really the commentID (or should be)

                        StatusComment statcomup = new StatusComment(statusUpdateID);

                        statup = new StatusUpdate(statcomup.StatusUpdateID);

                        if (!StatusCommentAcknowledgement.IsUserCommentAcknowledgement(statcomup.StatusCommentID, Convert.ToInt32(mu.ProviderUserKey)))
                        {
                            ack.Create();

                            StatusUpdateNotification sun = new StatusUpdateNotification();

                            if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString()))
                            {
                                sun.GetStatusUpdateNotificationForUserStatus(statcomup.UserAccountID, statcomup.StatusUpdateID, SiteEnums.ResponseType.A);
                            }
                            else
                            {
                                sun.GetStatusUpdateNotificationForUserStatus(statcomup.UserAccountID, statcomup.StatusUpdateID, SiteEnums.ResponseType.B);
                            }

                            if (Convert.ToInt32(mu.ProviderUserKey) != statcomup.UserAccountID)
                            {
                                sun.UserAccountID = statcomup.UserAccountID;

                                SiteEnums.ResponseType rspType = SiteEnums.ResponseType.U;

                                if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString()))
                                {
                                    rspType = SiteEnums.ResponseType.A;
                                    sun.ResponseType = Convert.ToChar(rspType.ToString());
                                }
                                else
                                {
                                    rspType = SiteEnums.ResponseType.B;
                                    sun.ResponseType = Convert.ToChar(rspType.ToString());
                                }

                                if (sun.StatusUpdateNotificationID == 0)
                                {
                                    sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                    sun.IsRead = false;
                                    sun.Create();
                                }
                                else
                                {
                                    sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                    sun.IsRead = false;
                                    sun.Update();
                                }

                                SendNotificationEmail(statup.UserAccountID, rspType, sun.StatusUpdateID);
                            }

                            context.Response.Write(@"{""StatusAcks"": """ + HttpUtility.HtmlEncode(statcomup.StatusCommentAcknowledgementsOptions) + @"""}");
                        }
                        else
                        {
                            // reverse

                            ack.GetCommentAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey));

                            ack.Delete();
                            // TODO: DELETE NOTIFICATION

                            context.Response.Write(@"{""StatusAcks"": """ + HttpUtility.HtmlEncode(statcomup.StatusCommentAcknowledgementsOptions) + @"""}");
                        }
                    }
                    else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]) &&
                        !string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()])
                        )
                    {
                        mu = Membership.GetUser();

                        if (mu == null) return;

                        StatusComment statCom = new StatusComment();
                        statCom.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                        statCom.Message = HttpUtility.HtmlEncode(context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]);
                        statCom.StatusUpdateID = statusUpdateID;
                        statCom.UserAccountID = Convert.ToInt32(mu.ProviderUserKey);

                        //statCom.GetStatusCommentMessage(); // ? ignore this duplicate now

                        // TODO: CHECK IF THERE IS A RECENT MESSAGE THAT IS THE SAME
                        if (statCom.StatusCommentID == 0)
                        {
                            //BUG: THERE IS AN EVENT HANDLER THAT HAS QUEUED UP TOO MANY
                            StatusUpdate suLast = new StatusUpdate();
                            suLast.GetMostRecentUserStatus(Convert.ToInt32(mu.ProviderUserKey));

                            if (suLast.Message.Trim() != statCom.Message.Trim() || (suLast.Message.Trim() == statCom.Message.Trim() && suLast.StatusUpdateID != statCom.StatusUpdateID))
                            {
                                statCom.Create();
                            }

                            statup = new StatusUpdate(statusUpdateID);

                            // create a status update notification for the post maker and all commenters
                            StatusUpdateNotification sun = null;

                            if (Convert.ToInt32(mu.ProviderUserKey) != statup.UserAccountID)
                            {
                                sun = new StatusUpdateNotification();

                                sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.C);

                                if (sun.StatusUpdateNotificationID == 0)
                                {
                                    sun.ResponseType = Convert.ToChar(SiteEnums.ResponseType.C.ToString());
                                    sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                    sun.IsRead = false;
                                    sun.StatusUpdateID = statup.StatusUpdateID;
                                    sun.UserAccountID = statup.UserAccountID;
                                    sun.Create();
                                }
                                else
                                {
                                    sun.IsRead = false;
                                    sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                    sun.Update();
                                }

                                SendNotificationEmail(statup.UserAccountID, SiteEnums.ResponseType.C, sun.StatusUpdateID);
                            }

                            StatusComments statComs = new StatusComments();

                            statComs.GetAllStatusCommentsForUpdate(statusUpdateID);

                            foreach (StatusComment sc1 in statComs)
                            {
                                sun = new StatusUpdateNotification();

                                sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.C);

                                if (Convert.ToInt32(mu.ProviderUserKey) == sc1.UserAccountID ||
                                    Convert.ToInt32(mu.ProviderUserKey) == statup.UserAccountID) continue;

                                if (sun.StatusUpdateNotificationID == 0)
                                {
                                    sun.IsRead = false;
                                    sun.StatusUpdateID = statusUpdateID;
                                    sun.UserAccountID = sc1.UserAccountID;
                                    sun.Create();
                                }
                                else
                                {
                                    sun.IsRead = false;
                                    sun.Update();
                                }
                            }
                            context.Response.Write(@"{""StatusAcks"": """ +  @"""}");
                        }
                    }
                    else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()]) &&
                         context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()] == "P"
                        )
                    {
                        // delete post
                        statup = new StatusUpdate(statusUpdateID);

                        StatusUpdateNotifications.DeleteNotificationsForStatusUpdate(statup.StatusUpdateID);
                        Acknowledgements.DeleteStatusAcknowledgements(statup.StatusUpdateID);

                        StatusComments statComs = new StatusComments();
                        statComs.GetAllStatusCommentsForUpdate(statup.StatusUpdateID);

                        foreach (StatusComment sc1 in statComs)
                        {
                            StatusCommentAcknowledgements.DeleteStatusCommentAcknowledgements(sc1.StatusCommentID);
                        }
                        StatusComments.DeleteStatusComments(statup.StatusUpdateID);

                        statup.Delete();

                        if (statup.PhotoItemID != null)
                        {
                            PhotoItem pitm = new PhotoItem(Convert.ToInt32(statup.PhotoItemID));

                            S3Service s3 = new S3Service();

                            s3.AccessKeyID = AmazonCloudConfigs.AmazonAccessKey;
                            s3.SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey;

                            if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw))
                            {
                                s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw);
                            }

                            if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard))
                            {
                                s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard);
                            }

                            if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb))
                            {
                                s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb);
                            }

                            pitm.Delete();
                        }
                        context.Response.Write(@"{""StatusAcks"": """ + @"""}");
                    }
                    else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()]) &&
                             context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()] == "C"
                            )
                    {
                        // delete comment

                        StatusComment statCom = new StatusComment(
                            Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.status_com_id.ToString()]));

                        StatusCommentAcknowledgements.DeleteStatusCommentAcknowledgements(statCom.StatusCommentID);

                        statCom.Delete();

                        context.Response.Write(@"{""StatusUpdateID"": """ + statCom.StatusUpdateID.ToString() + @"""}");
                    }
                    else if (!string.IsNullOrEmpty(
                        context.Request.QueryString[SiteEnums.QueryStringNames.all_comments.ToString()]))
                    {
                        mu = Membership.GetUser();

                        if (mu == null) return;

                        StatusComments preFilter = new StatusComments();

                        preFilter.GetAllStatusCommentsForUpdate(statusUpdateID);

                        StatusComments statComs = new StatusComments();

                        foreach (BootBaronLib.AppSpec.DasKlub.BOL.StatusComment su1 in preFilter)
                        {
                            if (!BootBaronLib.AppSpec.DasKlub.BOL.BlockedUser.IsBlockingUser(Convert.ToInt32(mu.ProviderUserKey), su1.UserAccountID))
                            {
                                statComs.Add(su1);
                            }
                        }

                        statComs.IncludeStartAndEndTags = true;

                        sb = new StringBuilder(100);

                        sb.Append(statComs.ToUnorderdList);

                        context.Response.Write(@"{""StatusComs"": """ + HttpUtility.HtmlEncode(sb.ToString()) + @"""}");
                    }
                    else if (!string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.comment_page.ToString()]))
                    {
                        int pcount = Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.comment_page.ToString()]);

                        StatusUpdates statups = new StatusUpdates();

                        pcount = pcount + 10;

                        StatusUpdates preFilter = new StatusUpdates();

                        preFilter.GetStatusUpdatesPageWise(pcount, 1);

                        StatusUpdates sus = new StatusUpdates();

                        mu = Membership.GetUser();

                        foreach (BootBaronLib.AppSpec.DasKlub.BOL.StatusUpdate su1
                            in preFilter)
                        {
                            if (!BootBaronLib.AppSpec.DasKlub.BOL.BlockedUser.IsBlockingUser(Convert.ToInt32(mu.ProviderUserKey), su1.UserAccountID))
                            {
                                statups.Add(su1);
                            }
                        }

                        statups.IncludeStartAndEndTags = false;

                        context.Response.Write(@"{""StatusUpdates"": """ + HttpUtility.HtmlEncode(statups.ToUnorderdList) + @"""}");
                    }

                    #endregion
                    break;
                case SiteEnums.QueryStringNames.begin_playlist:
                    #region begin_playlist
                    context.Response.Write(
                       PlaylistVideo.GetFirstVideo(Convert.ToInt32(context.Request.QueryString[
                       SiteEnums.QueryStringNames.playlist.ToString()])));
                    #endregion
                    break;
                case SiteEnums.QueryStringNames.menu:
                    #region menu

                    mu = Membership.GetUser();

                    // menu updates

                    // get count in video room
                    int userCountChat = 0;

                    // get new mail
                    int userMessages = 0;

                    // get new users
                    int unconfirmedUsers = 0;

                    // status notifications
                    int notifications = 0;

                    if (mu != null)
                    {
                        // log off users who are offline

                        UserAccounts uasOffline = new UserAccounts();
                        uasOffline.GetWhoIsOffline(true);

                        UserAccount offlineUser = null;

                        foreach (UserAccount uaoff1 in uasOffline)
                        {
                            ChatRoomUser cru = new ChatRoomUser();
                            cru.GetChatRoomUserByUserAccountID(uaoff1.UserAccountID);

                            if (cru.ChatRoomUserID > 0)
                            {
                                cru.DeleteChatRoomUser();
                            }

                            offlineUser = new UserAccount(uaoff1.UserAccountID);
                            offlineUser.RemoveCache();
                        }

                        userCountChat = ChatRoomUsers.GetChattingUserCount();

                        userMessages = BootBaronLib.AppSpec.DasKlub.BOL.DirectMessages.GetDirectMessagesToUserCount(mu);
                        unconfirmedUsers = BootBaronLib.AppSpec.DasKlub.BOL.UserConnections.GetCountUnconfirmedConnections(Convert.ToInt32(mu.ProviderUserKey));
                    }

                    // get users online
                    int onlineUsers = UserAccounts.GetOnlineUserCount();

                    if (mu != null)
                    {
                        notifications = StatusUpdateNotifications.GetStatusUpdateNotificationCountForUser(Convert.ToInt32(mu.ProviderUserKey));
                    }

                    string timedMessge = string.Format(
            @"{{""UserCountChat"": ""{0}"",
               ""UserMessages"": ""{1}"",
               ""OnlineUsers"": ""{2}"",
               ""Notifications"": ""{3}"",
               ""UnconfirmedUsers"": ""{4}""}}",userCountChat,userMessages,onlineUsers,notifications,unconfirmedUsers);

                    context.Response.Write(timedMessge);

                    #endregion
                    break;
                case SiteEnums.QueryStringNames.random:
                    #region random
                    if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]))
                    {
                        context.Response.Write(Video.GetRandomJSON(
                            context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]));
                    }
                    else
                    {
                        context.Response.Write(Video.GetRandomJSON());
                    }

                    #endregion
                    break;
                case SiteEnums.QueryStringNames.video_playlist:
                    #region video_playlist
                    if (!string.IsNullOrEmpty(
               context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]))
                    {
                        context.Response.Write(
                            PlaylistVideo.GetNextVideo(Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]),
                            context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]));
                    }
                    else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.begin_playlist.ToString()]))
                    {
                        context.Response.Write(
                          PlaylistVideo.GetFirstVideo(Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()])));
                    }
                    else
                    {
                        context.Response.Write(
                            PlaylistVideo.CurrentVideoInPlaylist(
                            Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()])
                            ));
                    }
                    #endregion
                    break;
                case SiteEnums.QueryStringNames.video:
                    #region video
                    Video vid = new Video("YT", context.Request.QueryString[SiteEnums.QueryStringNames.vid.ToString()]);

                    VideoLog.AddVideoLog(vid.VideoID, context.Request.UserHostAddress);

                    context.Response.Write(Video.GetVideoJSON(context.Request.QueryString[SiteEnums.QueryStringNames.vid.ToString()]));
                    #endregion
                    break;
                case SiteEnums.QueryStringNames.begindate:
                    #region begindate

                    //string[] dates = HttpUtility.UrlDecode(
                    //    context.Request.QueryString[SiteEnums.QueryStringNames.begindate.ToString()]
                    //    ).Split('G');

                    DateTime dtBegin = Convert.ToDateTime(context.Request.QueryString[SiteEnums.QueryStringNames.begindate.ToString()]);

                    dtBegin = new DateTime(dtBegin.Year, dtBegin.Month, 1);

                    DateTime dtEnd = dtBegin.AddMonths(1).AddDays(-1);
                    Events tds = new Events();

                    tds.GetEventsForLocation(
                          dtBegin, dtEnd,
                          context.Request.QueryString[SiteEnums.QueryStringNames.country_iso.ToString()],
                          context.Request.QueryString[SiteEnums.QueryStringNames.region.ToString()],
                          context.Request.QueryString[SiteEnums.QueryStringNames.city.ToString()]);

                    CalendarItems citms = GetCitms(tds, dtBegin, dtEnd, true);

                    //[ 100, 500, 300, 200, 400 ]
                    sb = new StringBuilder();

                    sb.Append("[");

                    int processed = 1;

                    foreach (CalendarItem ci1 in citms)
                    {
                        if (processed == citms.Count)
                        {
                            sb.Append(ci1.StartDate.Day);
                        }
                        else
                        {
                            sb.Append(ci1.StartDate.Day);
                            sb.Append(", ");
                        }

                        processed++;
                    }

                    sb.Append("]");

                    context.Response.Write(sb.ToString());
                    #endregion
                    break;
                case SiteEnums.QueryStringNames.playlist:
                    #region playlist

                    if (!string.IsNullOrEmpty(
                    context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]))
                    {
                        context.Response.Write(
                            PlaylistVideo.GetNextVideo(Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]),
                            context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]));
                    }
                    else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.begin_playlist.ToString()]))
                    {
                        context.Response.Write(
                          PlaylistVideo.GetFirstVideo(Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()])));
                    }
                    else
                    {
                        context.Response.Write(
                            PlaylistVideo.CurrentVideoInPlaylist(
                            Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()])
                            ));
                    }
                    #endregion
                    break;
                default:
                    // ?
                    break;

            }
        }
Ejemplo n.º 45
0
        public void ProcessRequest(HttpContext context)
        {
            if (string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.param_type.ToString()]))
                return;

            var ptyc = (SiteEnums.QueryStringNames) Enum.Parse(typeof (SiteEnums.QueryStringNames),
                context.Request.QueryString[SiteEnums.QueryStringNames.param_type.ToString()]);

            MembershipUser mu;

            switch (ptyc)
            {
                case SiteEnums.QueryStringNames.status_update:

                    #region status_update

                    string key = context.Request.QueryString[SiteEnums.QueryStringNames.status_update_id.ToString()];

                    if (string.IsNullOrEmpty(key))
                    {
                        key =
                            context.Request.QueryString[
                                SiteEnums.QueryStringNames.most_applauded_status_update_id.ToString()];
                    }

                    int statusUpdateID = Convert.ToInt32(key);

                    StatusUpdate statup;

                    if (
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_rsp.ToString()]))
                    {
                        mu = MembershipWrapper.GetUser();

                        if (mu == null) return;
                        var ack = new Acknowledgement
                        {
                            CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey),
                            UserAccountID = Convert.ToInt32(mu.ProviderUserKey),
                            AcknowledgementType = Convert.ToChar(
                                context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_rsp.ToString()]),
                            StatusUpdateID = statusUpdateID
                        };

                        statup = new StatusUpdate(statusUpdateID);

                        if (!Acknowledgement.IsUserAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey)))
                        {
                            ack.Create();

                            var sun = new StatusUpdateNotification();

                            if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString()))
                            {
                                sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID,
                                    SiteEnums.ResponseType.A);
                            }

                            if (Convert.ToInt32(mu.ProviderUserKey) != statup.UserAccountID)
                            {
                                sun.UserAccountID = statup.UserAccountID;

                                SiteEnums.ResponseType rspType;

                                if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString()))
                                {
                                    rspType = SiteEnums.ResponseType.A;
                                    sun.ResponseType = Convert.ToChar(rspType.ToString());
                                }
                                else
                                {
                                    rspType = SiteEnums.ResponseType.B;
                                    sun.ResponseType = Convert.ToChar(rspType.ToString());
                                }

                                sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey);

                                if (sun.StatusUpdateNotificationID == 0)
                                {
                                    sun.IsRead = false;
                                    sun.Create();
                                }
                                else
                                {
                                    sun.IsRead = false;
                                    sun.Update();
                                }

                                SendNotificationEmail(statup.UserAccountID, Convert.ToInt32(mu.ProviderUserKey), rspType,
                                    sun.StatusUpdateID);
                            }

                            context.Response.Write(string.Format(@"{{""StatusAcks"": ""{0}""}}",
                                HttpUtility.HtmlEncode(statup.StatusAcknowledgements)));
                        }
                        else
                        {
                            // reverse

                            ack.GetAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey));

                            ack.Delete();

                            // TODO: DELETE NOTIFICATION

                            context.Response.Write(string.Format(@"{{""StatusAcks"": ""{0}""}}",
                                HttpUtility.HtmlEncode(statup.StatusAcknowledgements)));
                        }
                    }
                    else if (
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[
                                SiteEnums.QueryStringNames.stat_update_comment_rsp.ToString()]))
                    {
                        mu = MembershipWrapper.GetUser();

                        if (mu == null) return;
                        var ack = new StatusCommentAcknowledgement
                        {
                            CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey),
                            UserAccountID = Convert.ToInt32(mu.ProviderUserKey),
                            AcknowledgementType = Convert.ToChar(
                                context.Request.QueryString[
                                    SiteEnums.QueryStringNames.stat_update_comment_rsp.ToString()]),
                            StatusCommentID = statusUpdateID
                        };

                        var statcomup = new StatusComment(statusUpdateID);

                        statup = new StatusUpdate(statcomup.StatusUpdateID);

                        if (!StatusCommentAcknowledgement.IsUserCommentAcknowledgement(statcomup.StatusCommentID,
                            Convert.ToInt32(
                                mu.ProviderUserKey)))
                        {
                            ack.Create();

                            var sun = new StatusUpdateNotification();

                            sun.GetStatusUpdateNotificationForUserStatus(statcomup.UserAccountID,
                                statcomup.StatusUpdateID,
                                ack.AcknowledgementType ==
                                Convert.ToChar(
                                    SiteEnums.ResponseType.A.ToString())
                                    ? SiteEnums.ResponseType.A
                                    : SiteEnums.ResponseType.B);

                            if (Convert.ToInt32(mu.ProviderUserKey) != statcomup.UserAccountID)
                            {
                                sun.UserAccountID = statcomup.UserAccountID;

                                SiteEnums.ResponseType rspType;

                                if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString()))
                                {
                                    rspType = SiteEnums.ResponseType.A;
                                    sun.ResponseType = Convert.ToChar(rspType.ToString());
                                }
                                else
                                {
                                    rspType = SiteEnums.ResponseType.B;
                                    sun.ResponseType = Convert.ToChar(rspType.ToString());
                                }

                                if (sun.StatusUpdateNotificationID == 0)
                                {
                                    sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                    sun.IsRead = false;
                                    sun.Create();
                                }
                                else
                                {
                                    sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                    sun.IsRead = false;
                                    sun.Update();
                                }

                                SendNotificationEmail(statup.UserAccountID, Convert.ToInt32(mu.ProviderUserKey), rspType,
                                    sun.StatusUpdateID);
                            }

                            context.Response.Write(string.Format(@"{{""StatusAcks"": ""{0}""}}", HttpUtility.HtmlEncode(
                                statcomup.StatusCommentAcknowledgementsOptions)));
                        }
                        else
                        {
                            // reverse

                            ack.GetCommentAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey));

                            ack.Delete();
                            // TODO: DELETE NOTIFICATION

                            context.Response.Write(string.Format(@"{{""StatusAcks"": ""{0}""}}", HttpUtility.HtmlEncode(
                                statcomup.StatusCommentAcknowledgementsOptions)));
                        }
                    }
                    else if (
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]) &&
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()])
                        )
                    {
                        mu = MembershipWrapper.GetUser();

                        if (mu == null) return;

                        var statCom = new StatusComment
                        {
                            CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey),
                            Message = HttpUtility.HtmlEncode(
                                context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]),
                            StatusUpdateID = statusUpdateID,
                            UserAccountID = Convert.ToInt32(mu.ProviderUserKey)
                        };

                        // TODO: CHECK IF THERE IS A RECENT MESSAGE THAT IS THE SAME
                        if (statCom.StatusCommentID != 0) return;
                        //BUG: THERE IS AN EVENT HANDLER THAT HAS QUEUED UP TOO MANY
                        var suLast = new StatusUpdate();
                        suLast.GetMostRecentUserStatus(Convert.ToInt32(mu.ProviderUserKey));

                        if (suLast.Message.Trim() != statCom.Message.Trim() ||
                            (suLast.Message.Trim() == statCom.Message.Trim() &&
                             suLast.StatusUpdateID != statCom.StatusUpdateID))
                        {
                            statCom.Create();
                        }

                        statup = new StatusUpdate(statusUpdateID);

                        // create a status update notification for the post maker and all commenters
                        StatusUpdateNotification sun;

                        if (Convert.ToInt32(mu.ProviderUserKey) != statup.UserAccountID)
                        {
                            sun = new StatusUpdateNotification();

                            sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID,
                                statusUpdateID,
                                SiteEnums.ResponseType.C);

                            if (sun.StatusUpdateNotificationID == 0)
                            {
                                sun.ResponseType = Convert.ToChar(SiteEnums.ResponseType.C.ToString());
                                sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                sun.IsRead = false;
                                sun.StatusUpdateID = statup.StatusUpdateID;
                                sun.UserAccountID = statup.UserAccountID;
                                sun.Create();
                            }
                            else
                            {
                                sun.IsRead = false;
                                sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                                sun.Update();
                            }

                            SendNotificationEmail(statup.UserAccountID, Convert.ToInt32(mu.ProviderUserKey),
                                SiteEnums.ResponseType.C, sun.StatusUpdateID);
                        }

                        var statComs = new StatusComments();

                        statComs.GetAllStatusCommentsForUpdate(statusUpdateID);

                        foreach (StatusComment sc1 in statComs)
                        {
                            sun = new StatusUpdateNotification();

                            sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID,
                                statusUpdateID,
                                SiteEnums.ResponseType.C);

                            if (Convert.ToInt32(mu.ProviderUserKey) == sc1.UserAccountID ||
                                Convert.ToInt32(mu.ProviderUserKey) == statup.UserAccountID) continue;

                            if (sun.StatusUpdateNotificationID == 0)
                            {
                                sun.IsRead = false;
                                sun.StatusUpdateID = statusUpdateID;
                                sun.UserAccountID = sc1.UserAccountID;
                                sun.Create();
                            }
                            else
                            {
                                sun.IsRead = false;
                                sun.Update();
                            }
                        }
                        context.Response.Write(@"{""StatusAcks"": """ + @"""}");
                    }
                    else if (
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()]) &&
                        context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()] == "P"
                        )
                    {
                        // delete post
                        statup = new StatusUpdate(statusUpdateID);

                        StatusUpdateNotifications.DeleteNotificationsForStatusUpdate(statup.StatusUpdateID);
                        Acknowledgements.DeleteStatusAcknowledgements(statup.StatusUpdateID);

                        var statComs = new StatusComments();
                        statComs.GetAllStatusCommentsForUpdate(statup.StatusUpdateID);

                        foreach (StatusComment sc1 in statComs)
                        {
                            StatusCommentAcknowledgements.DeleteStatusCommentAcknowledgements(
                                sc1.StatusCommentID);
                        }
                        StatusComments.DeleteStatusComments(statup.StatusUpdateID);

                        statup.Delete();

                        if (statup.PhotoItemID != null)
                        {
                            var pitm = new PhotoItem(Convert.ToInt32(statup.PhotoItemID));

                            var s3 = new S3Service
                            {
                                AccessKeyID = AmazonCloudConfigs.AmazonAccessKey,
                                SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey
                            };

                            if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw))
                            {
                                s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw);
                            }

                            if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard))
                            {
                                s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard);
                            }

                            if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb))
                            {
                                s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb);
                            }

                            pitm.Delete();
                        }
                        context.Response.Write(@"{""StatusAcks"": """ + @"""}");
                    }
                    else if (
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()]) &&
                        context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()] ==
                        "C"
                        )
                    {
                        // delete comment

                        var statCom = new StatusComment(
                            Convert.ToInt32(
                                context.Request.QueryString[
                                    SiteEnums.QueryStringNames.status_com_id.ToString()]));

                        StatusCommentAcknowledgements.DeleteStatusCommentAcknowledgements(
                            statCom.StatusCommentID);

                        statCom.Delete();

                        context.Response.Write(string.Format(@"{{""StatusUpdateID"": ""{0}""}}", statCom.StatusUpdateID));
                    }
                    else if (!string.IsNullOrEmpty(
                        context.Request.QueryString[SiteEnums.QueryStringNames.all_comments.ToString()]))
                    {
                        mu = MembershipWrapper.GetUser();

                        if (mu == null) return;

                        var preFilter = new StatusComments();

                        preFilter.GetAllStatusCommentsForUpdate(statusUpdateID);

                        var statComs = new StatusComments();
                        statComs.AddRange(
                            preFilter.Where(
                                su1 =>
                                    !BlockedUser.IsBlockingUser(Convert.ToInt32(mu.ProviderUserKey), su1.UserAccountID)));

                        statComs.IncludeStartAndEndTags = true;

                        var sb = new StringBuilder(100);

                        sb.Append(statComs.ToUnorderdList);

                        context.Response.Write(string.Format(@"{{""StatusComs"": ""{0}""}}",
                            HttpUtility.HtmlEncode(sb.ToString())));
                    }
                    else if (!string.IsNullOrEmpty(
                        context.Request.QueryString[SiteEnums.QueryStringNames.comment_page.ToString()]))
                    {
                        int pcount =
                            Convert.ToInt32(
                                context.Request.QueryString[
                                    SiteEnums.QueryStringNames.comment_page.ToString()]);

                        var statups = new StatusUpdates();

                        pcount = pcount + 10;

                        var preFilter = new StatusUpdates();

                        preFilter.GetStatusUpdatesPageWise(pcount, 1);

                        mu = MembershipWrapper.GetUser();

                        statups.AddRange(
                            preFilter.Where(
                                su1 =>
                                    mu != null &&
                                    !BlockedUser.IsBlockingUser(Convert.ToInt32(mu.ProviderUserKey), su1.UserAccountID)));

                        statups.IncludeStartAndEndTags = false;

                        context.Response.Write(string.Format(@"{{""StatusUpdates"": ""{0}""}}",
                            HttpUtility.HtmlEncode(statups.ToUnorderdList)));
                    }

                    #endregion

                    break;
                case SiteEnums.QueryStringNames.begin_playlist:

                    #region begin_playlist

                    context.Response.Write(
                        PlaylistVideo.GetFirstVideo(Convert.ToInt32(context.Request.QueryString[
                            SiteEnums.QueryStringNames.playlist.ToString()])));

                    #endregion

                    break;
                case SiteEnums.QueryStringNames.menu:

                    #region menu

                    mu = MembershipWrapper.GetUser();

                    int userCountChat = 0;
                    int userMessages = 0;
                    int unconfirmedUsers = 0;
                    int notifications = 0;

                    if (mu != null)
                    {
                        // log off users who are offline

                        var uasOffline = new UserAccounts();
                        uasOffline.GetWhoIsOffline(true);

                        foreach (UserAccount uaoff1 in uasOffline)
                        {
                            var cru = new ChatRoomUser();
                            cru.GetChatRoomUserByUserAccountID(uaoff1.UserAccountID);

                            if (cru.ChatRoomUserID > 0)
                            {
                                cru.DeleteChatRoomUser();
                            }

                            var offlineUser = new UserAccount(uaoff1.UserAccountID);
                            offlineUser.RemoveCache();
                        }

                        userCountChat = ChatRoomUsers.GetChattingUserCount();

                        userMessages = DirectMessages.GetDirectMessagesToUserCount(mu);
                        unconfirmedUsers =
                            UserConnections.GetCountUnconfirmedConnections(Convert.ToInt32(mu.ProviderUserKey));
                    }

                    // get users online
                    int onlineUsers = UserAccounts.GetOnlineUserCount();

                    if (mu != null)
                    {
                        notifications =
                            StatusUpdateNotifications.GetStatusUpdateNotificationCountForUser(
                                Convert.ToInt32(mu.ProviderUserKey));
                    }

                    string timedMessge = string.Format(
                        @"{{""UserCountChat"": ""{0}"",
               ""UserMessages"": ""{1}"",
               ""OnlineUsers"": ""{2}"",
               ""Notifications"": ""{3}"",
               ""UnconfirmedUsers"": ""{4}""}}", userCountChat, userMessages, onlineUsers, notifications,
                        unconfirmedUsers);

                    context.Response.Write(timedMessge);

                    #endregion

                    break;
                case SiteEnums.QueryStringNames.random:

                    #region random

                    if (
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]))
                    {
                        context.Response.Write(Video.GetRandomJSON(
                            context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]));
                    }
                    else
                    {
                        context.Response.Write(Video.GetRandomJSON());
                    }

                    #endregion

                    break;
                case SiteEnums.QueryStringNames.video_playlist:

                    #region video_playlist

                    if (!string.IsNullOrEmpty(
                        context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]))
                    {
                        context.Response.Write(
                            PlaylistVideo.GetNextVideo(
                                Convert.ToInt32(
                                    context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]),
                                context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]));
                    }
                    else if (
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.begin_playlist.ToString()]))
                    {
                        context.Response.Write(
                            PlaylistVideo.GetFirstVideo(
                                Convert.ToInt32(
                                    context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()])));
                    }
                    else
                    {
                        context.Response.Write(
                            PlaylistVideo.CurrentVideoInPlaylist(
                                Convert.ToInt32(
                                    context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()])
                                ));
                    }

                    #endregion

                    break;
                case SiteEnums.QueryStringNames.video:

                    #region video

                    var vid = new Video("YT", context.Request.QueryString[SiteEnums.QueryStringNames.vid.ToString()]);

                    VideoLog.AddVideoLog(vid.VideoID, context.Request.UserHostAddress);

                    context.Response.Write(
                        Video.GetVideoJSON(context.Request.QueryString[SiteEnums.QueryStringNames.vid.ToString()]));

                    #endregion

                    break;

                case SiteEnums.QueryStringNames.playlist:

                    #region playlist

                    if (!string.IsNullOrEmpty(
                        context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]))
                    {
                        context.Response.Write(
                            PlaylistVideo.GetNextVideo(
                                Convert.ToInt32(
                                    context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]),
                                context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()]));
                    }
                    else if (
                        !string.IsNullOrEmpty(
                            context.Request.QueryString[SiteEnums.QueryStringNames.begin_playlist.ToString()]))
                    {
                        context.Response.Write(
                            PlaylistVideo.GetFirstVideo(
                                Convert.ToInt32(
                                    context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()])));
                    }
                    else
                    {
                        context.Response.Write(
                            PlaylistVideo.CurrentVideoInPlaylist(
                                Convert.ToInt32(
                                    context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()])
                                ));
                    }

                    #endregion

                    break;
            }
        }
Ejemplo n.º 46
0
        public ActionResult Delete(int photoItemID)
        {
            mu = Membership.GetUser();

            pitm = new PhotoItem(photoItemID);

            if (pitm.CreatedByUserID == Convert.ToInt32(mu.ProviderUserKey))
            {
                S3Service s3 = new S3Service();

                s3.AccessKeyID = AmazonCloudConfigs.AmazonAccessKey;
                s3.SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey;

                pitm.Delete();

                if (!string.IsNullOrEmpty(pitm.FilePathStandard))
                {
                    // delete the existing photos
                    try
                    {
                        if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName,  pitm.FilePathStandard))
                        {
                            s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard);
                        }

                        if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName,  pitm.FilePathRaw))
                        {
                            s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw);
                        }

                        if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName,  pitm.FilePathThumb))
                        {
                            s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb);
                        }

                    }
                    catch
                    {
                        // whatever
                    }
                }
            }

            return RedirectToAction("Index");
        }
        private void DeleteFTPPhoto(string folder, PhotoItem p)
        {
            string basePath = "Images/Gallery";
            string ftpUserName = ConfigurationManager.AppSettings["ftpUsername"].ToString();
            string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"].ToString();
            string hostName = ConfigurationManager.AppSettings["hostName"].ToString();
            string fileUrl = string.Format("ftp://{0}:{5}@{4}/webroot/{1}/{2}/{3}", ftpUserName, basePath, folder, p.Name, hostName, ftpPassword);
            try
            {
                //Set up the ftp client
                FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(fileUrl);
                ftpClient.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
                ftpClient.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;

                Master.AddSuccessMessage("A photo was successfully deleted.");
            }
            catch (Exception)
            {
                Master.AddErrorMessage("There was an error deleting a photo");
            }
        }
Ejemplo n.º 48
0
 private void setPhotosFromJsonArr(JsonArray photos)
 {
     this._photos = new Collection<PhotoItem>();
     foreach (var pl in photos)
     {
         JsonObject photo = pl.GetObject();
         PhotoItem p = new PhotoItem();
         if (photo.ContainsKey(STR_CAPTION))
             p.Caption = photo.GetNamedString(STR_CAPTION);
         if (photo.ContainsKey(STR_ALT_SIZES))
         {
             JsonObject first = photo.GetNamedArray(STR_ALT_SIZES).First().GetObject();
             if (first.ContainsKey(STR_URL))
                 p.Url = first.GetNamedString(STR_URL);
             if (first.ContainsKey(STR_WIDTH))
                 p.Width = (int)first.GetNamedNumber(STR_WIDTH);
             if (first.ContainsKey(STR_HEIGHT))
                 p.Height = (int)first.GetNamedNumber(STR_HEIGHT);
         }
         this._photos.Add(p);
     }
 }