public ServiceResult Update(TMG.Attribute s)
        {
            if (s == null)
            {
                return(ServiceResponse.Error("Invalid TMG.Attribute sent to server."));
            }

            AttributeManager AttributeManager = new AttributeManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
            var res = AttributeManager.Get(s.UUID);

            if (res.Code != 200)
            {
                return(res);
            }
            var dbS = (TMG.Attribute)res.Result;

            if (dbS.DateCreated == DateTime.MinValue)
            {
                dbS.DateCreated = DateTime.Now;
            }

            dbS.Deleted       = s.Deleted;
            dbS.Name          = s.Name;
            dbS.Status        = s.Status;
            dbS.SortOrder     = s.SortOrder;
            dbS.Image         = s.Image;
            dbS.ReferenceType = s.ReferenceType;
            dbS.ReferenceUUID = s.ReferenceUUID;
            dbS.Value         = s.Value;
            dbS.ValueType     = s.ValueType;
            dbS.SafeName      = s.SafeName;
            dbS.Deleted       = s.Deleted;
            dbS.Active        = s.Active;
            return(AttributeManager.Update(dbS));
        }
        public ServiceResult Insert(TMG.Attribute n)
        {
            if (CurrentUser == null)
            {
                return(ServiceResponse.Error("You must be logged in to access this function."));
            }

            if (string.IsNullOrWhiteSpace(n.AccountUUID) || n.AccountUUID == SystemFlag.Default.Account)
            {
                n.AccountUUID = CurrentUser.AccountUUID;
            }

            if (string.IsNullOrWhiteSpace(n.CreatedBy))
            {
                n.CreatedBy = CurrentUser.UUID;
            }

            if (n.DateCreated == DateTime.MinValue)
            {
                n.DateCreated = DateTime.Now;
            }

            AttributeManager AttributeManager = new AttributeManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

            return(AttributeManager.Insert(n));
        }
        public ServiceResult GetBy(string uuid)
        {
            if (string.IsNullOrWhiteSpace(uuid))
            {
                return(ServiceResponse.Error("You must provide a UUID for the Attribute."));
            }

            if (CurrentUser == null)
            {
                return(ServiceResponse.Error("You must be logged in to access this function."));
            }

            AttributeManager AttributeManager = new AttributeManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

            var res = AttributeManager.Get(uuid);

            if (res.Code != 200)
            {
                return(res);
            }
            TMG.Attribute attribute = (TMG.Attribute)res.Result;

            if (CurrentUser.AccountUUID != attribute.AccountUUID)
            {
                return(ServiceResponse.Error("You are not authorized to access this functionality."));
            }

            return(ServiceResponse.OK("", attribute));
        }
        public async Task <ServiceResult> PostFile(string UUID, string type)
        //public ServiceResult PostFile(string UUID, string type)
        {
            var fileResult = new FileEx();

            fileResult.Default = false;
            string pathToImage = "";
            string root        = "";

            string basePath = "/Content/Uploads/" + this.CurrentUser.UUID;

            if (type.EqualsIgnoreCase("user") || type.EqualsIgnoreCase("profile") || type.EqualsIgnoreCase("profilemember"))
            {
                basePath = "/Content/Protected/" + this.CurrentUser.UUID;
            }

            try
            {
                if (this.CurrentUser == null)
                {
                    return(ServiceResponse.Error("You must be logged in to upload."));
                }

                #region non async

                //var httpRequest = HttpContext.Current.Request;
                //if (httpRequest.Files.Count < 1)
                //{
                //    return ServiceResponse.Error("Bad request");
                //}

                //foreach (string file in httpRequest.Files)
                //{
                //    var postedFile = httpRequest.Files[file];
                //    var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                //    postedFile.SaveAs(filePath);

                //}

                //return ServiceResponse.OK();

                #endregion non async

                HttpRequestMessage request = this.Request;
                if (!request.Content.IsMimeMultipartContent())
                {
                    return(ServiceResponse.Error("Unsupported media type."));
                }

                root = System.Web.HttpContext.Current.Server.MapPath("~" + basePath);

                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }

                var provider = new MultipartFormDataStreamProvider(root);

                //  foreach (MultipartFileData file in provider.FileData)
                //{
                //    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                //    Trace.WriteLine("Server file path: " + file.LocalFileName);

                //    //AppManager app = new AppManager(Globals.DBConnectionKey, "web", this.GetAuthToken(Request));
                //    //string fileName = file.Headers.ContentDisposition.FileName;

                //    //// Clean the file name..
                //    //foreach (var c in Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(c, ' '); }

                //    //if (string.IsNullOrWhiteSpace(fileName))
                //    //    continue;

                //    //fileName = fileName.ToUpper();

                //}
                //return ServiceResponse.OK();

                ServiceResult res = await request.Content.ReadAsMultipartAsync(provider).
                                    ContinueWith <ServiceResult>(o =>
                {
                    if (o.IsFaulted || o.IsCanceled)
                    {
                        _logger.InsertError("o.IsFaulted:" + o.IsFaulted, "AttributesController", "PostFile");
                        _logger.InsertError("o.IsCanceled:" + o.IsCanceled, "AttributesController", "PostFile");
                        _logger.InsertError("o.Exception:" + JsonConvert.SerializeObject(o), "AttributesController", "PostFile");

                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    }
                    string fileName   = "";
                    List <string> kvp = o.Result.Contents.First().Headers.First(w => w.Key == "Content-Disposition").Value.ToList()[0].Split(';').ToList();
                    foreach (string value in kvp)
                    {
                        if (value.Trim().StartsWith("filename"))
                        {
                            String[] tmp = value.Split('=');
                            fileName     = DateTime.UtcNow.ToString("yyyyMMdd_hhmmss") + tmp[1].Trim().Replace("\"", "");
                        }

                        if (value.Contains("defaultImage"))        //value.Trim().StartsWith("name"))
                        {
                            fileResult.Default = true;
                        }
                    }
                    // this is the file name on the server where the file was saved
                    string file             = provider.FileData.First().LocalFileName;
                    string originalFilename = Path.GetFileName(file);
                    string destFile         = file.Replace(originalFilename, fileName);
                    try
                    {
                        if (File.Exists(destFile))
                        {
                            File.Delete(destFile);
                        }
                    }
                    catch
                    {     //file may still be locked so don't worry about it.
                    }

                    try
                    {
                        string extension = Path.GetExtension(destFile)?.ToUpper();
                        if (!string.IsNullOrWhiteSpace(extension))
                        {
                            extension = extension.Replace(".", "");
                        }

                        var image = System.Drawing.Image.FromFile(file);
                        using (var resized = ImageEx.ResizeImage(image, 640, 640))
                        {
                            switch (extension)
                            {
                            case "PNG":
                                resized.Save(destFile, ImageFormat.Png);
                                break;

                            case "GIF":
                                resized.Save(destFile, ImageFormat.Gif);
                                break;

                            case "JPEG":
                            case "JPG":
                                resized.Save(destFile, ImageFormat.Jpeg);
                                break;

                            default:
                                ImageEx.SaveJpeg(destFile, resized, 90);
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.Assert(false, ex.Message);
                    }

                    //try
                    //{
                    //    File.Move(file, destFile);
                    //}
                    //catch { }//ditto from above catch

                    file = destFile;

                    string thumbFile = ImageEx.CreateThumbnailImage(file, 64);
                    string ImageUrl  = fileName;
                    string fullUrl   = this.Request.RequestUri.Scheme + "://" + this.Request.RequestUri.Authority + basePath + "/"; // "/Content/Uploads/" + this.CurrentUser.UUID + "/";
                    pathToImage      = fullUrl + thumbFile;                                                                         // ImageUrl;

                    if (fileResult.Default)
                    {
                        this.UpdateImageURL(UUID, type, pathToImage);    //Now update the database.
                    }
                    else
                    {
                        //add other images to attributes

                        AttributeManager atm = new AttributeManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

                        var attribute = new TMG.Attribute()
                        {
                            ReferenceUUID = UUID,
                            ReferenceType = type,
                            Value         = thumbFile,
                            Image         = thumbFile,
                            ValueType     = "ImagePath",
                            Name          = fileResult.Name,
                            AccountUUID   = this.CurrentUser.AccountUUID,
                            DateCreated   = DateTime.UtcNow,
                            CreatedBy     = CurrentUser.UUID,
                            RoleOperation = ">=",
                            RoleWeight    = RoleFlags.MemberRoleWeights.Member,
                            Private       = false,
                            NSFW          = -1
                        };
                        atm.Insert(attribute);
                    }

                    fileResult.UUID       = UUID;
                    fileResult.UUIDType   = type;
                    fileResult.Status     = "saved";
                    fileResult.Image      = fullUrl + ImageUrl;
                    fileResult.ImageThumb = fullUrl + ImageEx.GetThumbFileName(destFile);     //todo check this
                    fileResult.Name       = fileName;

                    return(ServiceResponse.OK(fileName + " uploaded.", fileResult));
                }
                                                                 );

                return(res);
            }
            catch (Exception ex)
            {
                _logger.InsertError("root folder:" + root, "AttributesController", "PostFile");
                _logger.InsertError(ex.DeserializeException(false), "AttributesController", "PostFile");
                return(ServiceResponse.Error("Upload failed."));
            }
        }