//public static void set(string File,string FileName)
        //{
        //    // 初始化OssClient
        //    var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
        //    //try
        //    //{
        //    //    string fileToUpload = "d:\\Desktop\\Myhome_prj\\Myhome_prj\\Myhome\\UploadImgs\\201707155302688_1.jpg";
        //    //    client.PutObject("myhome20170320", "tupian/女帝.jpg", fileToUpload);
        //    //    Console.WriteLine("图片上传成功!");
        //    //}
        //    //catch (Exception ex)
        //    //{
        //    //    Console.WriteLine("Put object failed, {0}", ex.Message);
        //    //}

        //       System.IO.FileStream fs = new FileStream(File, FileMode.Open);

        //        var metadata = new ObjectMetadata();
        //        metadata.UserMetadata.Add("name", "my-data");
        //        metadata.ContentLength = fs.Length;
        //        client.PutObject("myhome20170320", "tupian/"+FileName, fs, metadata);
        //        Console.WriteLine("Put object succeeded");

        //        Entity.Album a = new Entity.Album();
        //        a.AlnumName = FileName;
        //        a.AlnumUrl = "http://myhome20170320.oss-cn-shanghai.aliyuncs.com/tupian/" +FileName;
        //        DALAlbum.upPhoto(a);
        //}


        public static HttpResult set(string File, string FileName)
        {
            ZoneID zoneId = ZoneID.CN_South;

            Qiniu.Common.Config.SetZone(zoneId, true);
            // 初始化OssClient
            //var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            ////try
            //{
            //    string fileToUpload = "d:\\Desktop\\Myhome_prj\\Myhome_prj\\Myhome\\UploadImgs\\201707155302688_1.jpg";
            //    client.PutObject("myhome20170320", "tupian/女帝.jpg", fileToUpload);
            //    Console.WriteLine("图片上传成功!");
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("Put object failed, {0}", ex.Message);
            //}

            /// <summary>
            /// 简单上传-上传小文件
            /// </summary>

            // 生成(上传)凭证时需要使用此Mac
            // 这个示例单独使用了一个Settings类,其中包含AccessKey和SecretKey
            // 实际应用中,请自行设置您的AccessKey和SecretKey
            Mac    mac       = new Mac(accessKeyId, accessKeySecret);
            string bucket    = "myhome1314";
            string saveKey   = FileName;
            string localFile = File;
            // 上传策略,参见
            // https://developer.qiniu.com/kodo/manual/put-policy
            PutPolicy putPolicy = new PutPolicy();

            // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY"
            // putPolicy.Scope = bucket + ":" + saveKey;
            putPolicy.Scope = bucket;
            // 上传策略有效期(对应于生成的凭证的有效期)
            putPolicy.SetExpires(3600);
            // 上传到云端多少天后自动删除该文件,如果不设置(即保持默认默认)则不删除
            putPolicy.DeleteAfterDays = 1;
            // 生成上传凭证,参见
            // https://developer.qiniu.com/kodo/manual/upload-token
            string        jstr   = putPolicy.ToJsonString();
            string        token  = Auth.CreateUploadToken(mac, jstr);
            UploadManager um     = new UploadManager();
            HttpResult    result = um.UploadFile(localFile, saveKey, token);

            if (result.Text != "{\"error\":\"no such bucket\"}")
            {
                Entity.Album a = new Entity.Album();
                a.AlnumName = FileName;
                a.AlnumUrl  = "http://osmfge71u.bkt.clouddn.com/" + FileName;
                DALAlbum.upPhoto(a);
            }
            return(result);
        }
        //[Authorize(Policy = GlobalConstants.PolicyOperationAuthorization)]
        public async Task <IActionResult> Post([FromBody] Entity.Album album)
        {
            // POST api/albums/post
            if (album == null)
            {
                throw new ArgumentNullException(nameof(album));
            }

            try
            {
                var alb = Factory.LoadAlbumInstance(new AlbumLoadOptions(album.Id)
                {
                    IsWritable = true
                });

                if ((await _authorizationService.AuthorizeAsync(User, alb, Operations.EditAlbum)).Succeeded)
                {
                    await _albumController.UpdateAlbum(album);

                    return(Ok($"Album {alb.Id} saved..."));
                }
                else
                {
                    throw new GallerySecurityException($"You do not have permission '{Operations.EditAlbum.RequestedPermission}' for album ID {album.Id}.");
                }
            }
            catch (InvalidAlbumException)
            {
                return(NotFound($"Could not find album with ID {album.Id}."));
            }
            catch (GallerySecurityException ex)
            {
                AppEventController.LogError(ex);

                return(Forbid());
            }
            catch (NotSupportedException ex)
            {
                return(StatusCode(500, $"Business Rule Violation: {_exController.GetExString(ex)}"));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex, album?.GalleryId);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
        public IQueryable <Entity.GalleryItem> Sort(Entity.Album album, bool persistToAlbum)
        {
            try
            {
                if (persistToAlbum)
                {
                    // Change the sort of an existing album for all users.
                    if (album.Id <= 0)
                    {
                        throw new ArgumentException("An album ID must be specified when calling the AlbumsController.Sort() Web.API method with the persistToAlbum parameter set to true.");
                    }

                    AlbumController.Sort(album.Id, album.SortById, album.SortUp);

                    return(GalleryObjectController.ToGalleryItems(AlbumController.LoadAlbumInstance(album.Id).GetChildGalleryObjects().ToSortedList()).AsQueryable());
                }
                else
                {
                    return(GalleryObjectController.SortGalleryItems(album));
                }
            }
            catch (InvalidAlbumException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent($"Could not find album with ID {album.Id}. It may have been deleted by another user."),
                    ReasonPhrase = "Album Not Found"
                });
            }
            catch (GallerySecurityException ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        /// <summary>
        /// Persists the <paramref name="album" /> to the data store. Only the following properties are persisted:
        /// <see cref="Entity.Album.SortById" />, <see cref="Entity.Album.SortUp" />, <see cref="Entity.Album.IsPrivate" />
        /// </summary>
        /// <param name="album">The album to persist.</param>
        /// <exception cref="System.Web.Http.HttpResponseException">Thrown when the album isn't found in the data store,
        /// the current user doesn't have permission to edit the album, or some other error occurs.
        /// </exception>
        public void Post(Entity.Album album)
        {
            // POST api/albums/post
            try
            {
                AlbumController.UpdateAlbum(album);
            }
            catch (InvalidAlbumException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent(String.Format("Could not find album with ID = {0}", album.Id)),
                    ReasonPhrase = "Album Not Found"
                });
            }
            catch (GallerySecurityException ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)
                {
                    Content      = new StringContent(ex.Message),
                    ReasonPhrase = "Cannot Save Album"
                });
            }
            catch (NotSupportedException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = new StringContent(ex.Message),
                    ReasonPhrase = "Business Rule Violation"
                });
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex, album.GalleryId);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public ActionResult Put(Entity.Album album)
        {
            try
            {
                AlbumController.CreateAlbum(album);

                return(new ActionResult
                {
                    Status = ActionResultStatus.Success.ToString(),
                    Title = $"Successfully created album {album.Title}",
                    Message = string.Empty,
                    ActionTarget = album
                });
            }
            catch (InvalidAlbumException ex)
            {
                return(new ActionResult()
                {
                    Status = ActionResultStatus.Error.ToString(),
                    Title = "Cannot Create Album",
                    Message = ex.Message
                });
            }
            catch (GallerySecurityException ex)
            {
                AppEventController.LogError(ex);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex, album.GalleryId);

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content      = Utils.GetExStringContent(ex),
                    ReasonPhrase = "Server Error"
                });
            }
        }
        public async Task <IActionResult> Sort(Entity.Album album, bool persistToAlbum)
        {
            try
            {
                if (persistToAlbum)
                {
                    // Change the sort of an existing album for all users.
                    if (album.Id <= 0)
                    {
                        throw new ArgumentException("An album ID must be specified when calling the AlbumsController.Sort() Web.API method with the persistToAlbum parameter set to true.");
                    }

                    await _albumController.Sort(album.Id, album.SortById, album.SortUp);

                    return(new JsonResult(_galleryObjectController.ToGalleryItems(_albumController.LoadAlbumInstance(album.Id).GetChildGalleryObjects().ToSortedList())));
                }
                else
                {
                    return(new JsonResult(_galleryObjectController.SortGalleryItems(album)));
                }
            }
            catch (InvalidAlbumException)
            {
                return(NotFound($"Could not find album with ID {album.Id}. It may have been deleted by another user."));
            }
            catch (GallerySecurityException ex)
            {
                AppEventController.LogError(ex);

                return(Forbid());
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
        public async Task <IActionResult> Put(Entity.Album album)
        {
            try
            {
                await _albumController.CreateAlbum(album);

                return(new JsonResult(new Business.ActionResult
                {
                    Status = ActionResultStatus.Success.ToString(),
                    Title = $"Successfully created album {album.Title}",
                    Message = string.Empty,
                    ActionTarget = album
                }));
            }
            catch (InvalidAlbumException ex)
            {
                return(new JsonResult(new Business.ActionResult()
                {
                    Status = ActionResultStatus.Error.ToString(),
                    Title = "Cannot Create Album",
                    Message = ex.Message
                }));
            }
            catch (GallerySecurityException ex)
            {
                AppEventController.LogError(ex);

                return(Forbid());
            }
            catch (Exception ex)
            {
                AppEventController.LogError(ex, album.GalleryId);

                return(StatusCode(500, _exController.GetExString(ex)));
            }
        }
        /// <summary>
        /// Gets a data entity containing album information for the specified <paramref name="album" />. Returns an object with empty
        /// properties if the user does not have permission to view the specified album. The instance can be JSON-parsed and sent to the
        /// browser.
        /// </summary>
        /// <param name="album">The album to convert to an instance of <see cref="GalleryServerPro.Web.Entity.Album" />.</param>
        /// <param name="perms">The permissions the current user has for the album.</param>
        /// <param name="options">Specifies options for configuring the return data. To use default
        /// settings, specify an empty instance with properties left at default values.</param>
        /// <returns>
        /// Returns an <see cref="GalleryServerPro.Web.Entity.Album" /> object containing information about the requested album.
        /// </returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="album" /> is null.</exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static Entity.Album ToAlbumEntity(IAlbum album, Entity.Permissions perms, Entity.GalleryDataLoadOptions options)
        {
            if (album == null)
                throw new ArgumentNullException("album");

            var albumEntity = new Entity.Album();

            albumEntity.Id = album.Id;
            albumEntity.GalleryId = album.GalleryId;
            albumEntity.Title = album.Title;
            albumEntity.Caption = album.Caption;
            albumEntity.Owner = (perms.AdministerGallery ? album.OwnerUserName : null);
            albumEntity.InheritedOwners = (perms.AdministerGallery ? String.Join(", ", album.InheritedOwners) : null);
            albumEntity.DateStart = album.DateStart;
            albumEntity.DateEnd = album.DateEnd;
            albumEntity.IsPrivate = album.IsPrivate;
            albumEntity.VirtualType = (int)album.VirtualAlbumType;
            albumEntity.RssUrl = GetRssUrl(album);
            albumEntity.Permissions = perms;
            albumEntity.MetaItems = GalleryObjectController.ToMetaItems(album.MetadataItems.GetVisibleItems(), album);
            albumEntity.NumAlbums = album.GetChildGalleryObjects(GalleryObjectType.Album, !Utils.IsAuthenticated).Count;

            // Optionally load gallery items
            if (options.LoadGalleryItems)
            {
                var albumSortDef = ProfileController.GetProfile().AlbumProfiles.Find(album.Id);

                IList<IGalleryObject> items;
                if (albumSortDef != null)
                {
                    items = album
                        .GetChildGalleryObjects(options.Filter, !Utils.IsAuthenticated)
                        .ToSortedList(albumSortDef.SortByMetaName, albumSortDef.SortAscending, album.GalleryId);

                    albumEntity.SortById = (int)albumSortDef.SortByMetaName;
                    albumEntity.SortUp = albumSortDef.SortAscending;
                }
                else
                {
                    if (album.IsVirtualAlbum)
                    {
                        items = album.GetChildGalleryObjects(options.Filter, !Utils.IsAuthenticated).ToSortedList(album.SortByMetaName, album.SortAscending, album.GalleryId);
                    }
                    else
                    {
                        // Real (non-virtual) albums are already sorted on their Seq property, so return items based on that.
                        items = album.GetChildGalleryObjects(options.Filter, !Utils.IsAuthenticated).ToSortedList();
                    }

                    albumEntity.SortById = (int)album.SortByMetaName;
                    albumEntity.SortUp = album.SortAscending;
                }

                if (options.NumGalleryItemsToRetrieve > 0)
                    items = items.Skip(options.NumGalleryItemsToSkip).Take(options.NumGalleryItemsToRetrieve).ToList();

                albumEntity.GalleryItems = GalleryObjectController.ToGalleryItems(items);
                albumEntity.NumGalleryItems = albumEntity.GalleryItems.Length;
            }
            else
            {
                albumEntity.NumGalleryItems = album.GetChildGalleryObjects(options.Filter, !Utils.IsAuthenticated).Count;
            }

            // Optionally load media items
            if (options.LoadMediaItems)
            {
                IList<IGalleryObject> items;

                if (album.IsVirtualAlbum)
                {
                    items = album.GetChildGalleryObjects(GalleryObjectType.MediaObject, !Utils.IsAuthenticated).ToSortedList(album.SortByMetaName, album.SortAscending, album.GalleryId);
                }
                else
                {
                    // Real (non-virtual) albums are already sorted on their Seq property, so return items based on that.
                    items = album.GetChildGalleryObjects(GalleryObjectType.MediaObject, !Utils.IsAuthenticated).ToSortedList();
                }

                //IList<IGalleryObject> items = album.GetChildGalleryObjects(GalleryObjectType.MediaObject, !Utils.IsAuthenticated).ToSortedList();
                albumEntity.NumMediaItems = items.Count;
                albumEntity.MediaItems = GalleryObjectController.ToMediaItems(items);
            }
            else
            {
                albumEntity.NumMediaItems = album.GetChildGalleryObjects(GalleryObjectType.MediaObject, !Utils.IsAuthenticated).Count;
            }

            return albumEntity;
        }