Beispiel #1
0
        public async Task <IActionResult> UploadAttachmentsAsyncActionResult(List <IFormFile> attachments)
        {
            var rootPath = $"{this._hostingEnvironment.WebRootPath}";

            var relativePath = "/attachments/blog";

            var fullPath = $"{rootPath}{relativePath}";

            var results = new Collection <Models.Attachment>();

            foreach (var attachment in attachments)
            {
                var fileName = this.EnsureCorrectFilename(ContentDispositionHeaderValue.Parse(attachment.ContentDisposition).FileName.Trim('"'));

                var fullFilePath = Path.Combine(fullPath, fileName);

                if (attachment.Length <= 0)
                {
                    continue;
                }

                using (var stream = new FileStream(fullFilePath, FileMode.Create))
                {
                    await attachment.CopyToAsync(stream);
                }

                var newAttachement = new Models.Attachment
                {
                    Id   = Guid.NewGuid(),
                    Name = fileName,
                    Url  = $"{relativePath}/{fileName}",
                    Size = attachment.Length
                };

                results.Add(newAttachement);
            }

            return(this.Json(new { attachments = results }));
        }
Beispiel #2
0
        public async Task <Models.Attachment> InsertUpdateAsync(Models.Attachment model)
        {
            var id = await InsertUpdateInternal(
                model.Id,
                model.Name,
                model.ContentBlob,
                model.ContentType,
                model.ContentLength,
                model.ContentGuid,
                model.ContentCheckSum,
                model.TotalViews,
                model.CreatedUserId,
                model.CreatedDate,
                model.ModifiedUserId,
                model.ModifiedDate);

            if (id > 0)
            {
                return(await SelectByIdAsync(id));
            }

            return(null);
        }
 public void Update(UpdateAttachmentInput input)
 {
     Models.Attachment output = Mapper.Map <UpdateAttachmentInput, Models.Attachment>(input);
     _attachmentManager.Update(output);
 }
 public async Task Create(CreateAttachmentInput input)
 {
     Models.Attachment output = Mapper.Map <CreateAttachmentInput, Models.Attachment>(input);
     await _attachmentManager.Create(output);
 }
Beispiel #5
0
        public void GeneralUpload(int userId)
        {
            Models.ComboResponse _response = new Models.ComboResponse();
            _response.bool_result = true;
            _response.ErrorCode = 0;
            _response.ErrorMsg = "";

            try
            {
                if (HttpContext.Current.Request.Files.Count != 0)
                {
                    var ext = Path.GetExtension(HttpContext.Current.Request.Files[0].FileName);
                    var fileName = Path.GetFileName(HttpContext.Current.Request.Files[0].FileName);

                    if (HttpContext.Current.Request.Files[0].FileName.LastIndexOf("\\") != -1)
                    {
                        fileName = HttpContext.Current.Request.Files[0].FileName.Remove(0, HttpContext.Current.Request.Files[0].FileName.LastIndexOf("\\")).ToLower();
                    }

                    DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/userfiles/" + userId.ToString()));
                    if (!dir.Exists)
                        dir.Create();

                    string FilePath = "/userfiles/" + userId.ToString() + fileName + ext;

                    string location = HttpContext.Current.Server.MapPath("~/" + FilePath);
                    HttpContext.Current.Request.Files[0].SaveAs(location);

                    BLL.Attachment newfile = new BLL.Attachment();
                    newfile.AddNew();
                    newfile.Path = FilePath;
                    newfile.Save();

                    Models.Attachment responseText = new Models.Attachment();
                    responseText.AttachmentID = newfile.AttachmentID;
                    responseText.Path = newfile.Path;

                    _response.Entity = responseText;
                    SetContentResult(_response);
                }
                else
                {
                    _response.bool_result = false;
                    _response.ErrorCode = 21;
                    _response.ErrorMsg = "No file found.";
                }
            }
            catch (Exception ex)
            {
                _response.bool_result = false;
                _response.ErrorCode = 20;
                _response.ErrorMsg = "Error while uploading file.";
            }

            SetContentResult(_response);
        }
Beispiel #6
0
        public void Process(Dictionary <string, object> parameters)
        {
            Message       message       = null;
            List <string> botParameters = null;
            Stats         stats         = null;
            SlackClient   slackClient   = null;
            TimerPipeline timerPipeline = null;
            string        userName      = null;
            string        userId        = null;

            foreach (var item in parameters)
            {
                switch (item.Key)
                {
                case "stats": stats = (Stats)item.Value; break;

                case "userName": userName = (string)item.Value; break;

                case "userId": userId = (string)item.Value; break;

                case "message": message = (Message)item.Value; break;

                case "parameters": botParameters = (List <string>)item.Value; break;

                case "_timerPipeline": timerPipeline = (TimerPipeline)item.Value; break;

                case "_slackClient": slackClient = (SlackClient)item.Value; break;

                default:
                    break;
                }
            }

            if (botParameters[1] == "stayhydrated" && botParameters[2] == "subscribe" && botParameters.Count == 4)
            {
                foreach (var item in timerPipeline._pipelineElemets)
                {
                    if (item.GetType() == typeof(StayHydratedTimerMiddleware))
                    {
                        if (!item.SubscribersList.Exists(obj => obj.UserId == userId))
                        {
                            Pair newPair = new Pair
                            {
                                UserId           = userId,
                                SubscriptionDate = DateTime.Now,
                                LastReminded     = DateTime.Now,
                                Interval         = Int32.Parse(botParameters[3]),
                                UserName         = userName
                            };
                            item.SubscribersList.Add(newPair);

                            Models.Attachment attachment = new Models.Attachment
                            {
                                Color = "#04DF00",
                                Text  = "You are added to subscription list of Stay Hydrated. You will be notified every " + Int32.Parse(botParameters[3]) +
                                        " minute(s) to drink water. Wish you a nice day.",
                                Footer = "BordaBot",
                                Ts     = Extension.ToProperTimeStamp(DateTime.Now)
                            };
                            string attachments = "[" + JsonConvert.SerializeObject(attachment) + "]";
                            slackClient.PostMessage(message.Channel, "@" + userName + ":", false, attachments);
                        }
                        else
                        {
                            slackClient.PostMessage(message.Channel, "@" + userName + ", you have already subscribed for this service.");
                        }
                    }
                }
            }
            else if (botParameters[1] == "stayhydrated" && botParameters[2] == "unsubscribe")
            {
                foreach (var item in timerPipeline._pipelineElemets)
                {
                    if (item.GetType() == typeof(StayHydratedTimerMiddleware))
                    {
                        if (item.SubscribersList.Exists(obj => obj.UserId == userId))
                        {
                            item.SubscribersList.RemoveAll(obj => obj.UserId == userId);

                            Models.Attachment attachment = new Models.Attachment
                            {
                                Color  = "danger",
                                Text   = "You are removed from subscription list of Stay Hydrated.",
                                Footer = "BordaBot",
                                Ts     = Extension.ToProperTimeStamp(DateTime.Now)
                            };
                            string attachments = "[" + JsonConvert.SerializeObject(attachment) + "]";
                            slackClient.PostMessage(message.Channel, "@" + userName + ":", false, attachments);
                        }
                        else
                        {
                            slackClient.PostMessage(message.Channel, "@" + userName + ", you are not subscribed for this service.");
                        }
                    }
                }
            }
        }
        public ActionResult Edit(FileSelectionViewModel model, IEnumerable <HttpPostedFileBase> files)
        {
            if (ModelState.IsValid)
            {
                db.Entry(model.idea).State = EntityState.Modified;

                var currentIdea = db.Ideas.FirstOrDefault(p => p.ID == model.idea.ID);

                var ideas = db.Ideas.Where(IDEA => IDEA.title == model.idea.title && IDEA.ID != model.idea.ID).ToList();

                if (ideas.Count > 0)
                {
                    return(View(model));
                }

                // If the Idea is already in the "Submitted" state, another email will not be sent.
                bool alreadySubmitted = false;
                if (currentIdea.statusCode == "Submitted")
                {
                    alreadySubmitted = true;
                }
                currentIdea.title        = model.idea.title;
                currentIdea.body         = model.idea.body;
                currentIdea.statusCode   = "Submitted";
                currentIdea.denialReason = model.idea.denialReason;
                currentIdea.mod_date     = DateTime.Now;
                currentIdea.email        = model.idea.email;

                if (files != null)
                {
                    var appSettings = ConfigurationManager.AppSettings;

                    // store path to server location of the attachment storage
                    var connectionInfo = appSettings["serverPath"];

                    // combine the server location and the name of the new folder to be created
                    var storagePath = string.Format(@"{0}{1}_{2}", connectionInfo, model.idea.ID, model.idea.title);
                    if (!Directory.Exists(storagePath))
                    {
                        DirectoryInfo di = Directory.CreateDirectory(storagePath);
                    }

                    //run each file through MetaScan and check for forbidden extensions
                    for (int i = 0; i < files.Count(); ++i)
                    {
                        if (files.ElementAt(i) != null && files.ElementAt(i).ContentLength > 0)
                        {
                            var file = files.ElementAt(i);
                            // store the name of the attachment

                            // place the file into a bytearray for MetaScan use
                            FileStream stream    = System.IO.File.OpenRead(Path.GetFullPath(file.FileName));
                            byte[]     fileBytes = new byte[stream.Length];

                            stream.Read(fileBytes, 0, fileBytes.Length);
                            stream.Close();

                            // make the file a bytearray and send to MetaScan here?
                            FileService.FileService sf = new FileService.FileService();

                            string ext = Path.GetExtension(file.FileName);

                            bool valrtn = sf.ScanByFileWithNameAndExtension(fileBytes, file.FileName, ext);

                            // If any file fails to load, reload the creation screen and inform the submitter of the need to scan the files.
                            if (!valrtn)
                            {
                                TempData["ScanFailure"] = "\n\nThe files failed to upload. " +
                                                          "Please scan them locally using McAffee before uploading them again." +
                                                          " Selected files have not been deleted.";

                                return(View(model));
                            }
                        }
                    }

                    // save the files to the specified folder and link them to the idea
                    for (int i = 0; i < files.Count(); ++i)
                    {
                        if (files.ElementAt(i) != null && files.ElementAt(i).ContentLength > 0)
                        {
                            var file           = files.ElementAt(i);
                            var attachmentName = Path.GetFileName(file.FileName);
                            var namepath       = string.Format("{0}\\{1}", storagePath, attachmentName);

                            // save the new Attachments to the Idea
                            var attachment = new Models.Attachment
                            {
                                storageLocation = string.Format("{0}\\", storagePath),
                                name            = attachmentName,
                                cre_date        = DateTime.Now,
                                deleteObj       = "false"
                            };

                            try
                            {
                                file.SaveAs(string.Format("{0}\\{1}", storagePath, attachmentName));
                            }
                            catch (Exception ex)
                            {
                                TempData["Message"] += String.Format("An error was caught: Error number: {0}, Message: {1}", ex.HResult, ex.Message);
                                return(View(model));
                            }

                            if (model.idea.attachments == null)
                            {
                                model.idea.attachments = new List <Models.Attachment>();
                            }

                            model.idea.attachments.Add(attachment);
                            db.Attachments.Add(attachment);
                        }
                    }
                }
                // save the new Attachments to the Idea
                try
                {
                    db.SaveChanges();
                }
                catch (SqlException ex)
                {
                    log.Error("An error has occured while accessing the database.", ex);
                    return(RedirectToAction("AnError", "Error"));
                }

                // get the ids of the items selected:
                var selectedIds = model.getSelectedIds();

                // Use the ids to retrieve the records for the selected people
                // from the database:
                var selectedAttachments = from x in db.Attachments
                                          where selectedIds.Contains(x.ID)
                                          select x;

                // Process according to your requirements:
                foreach (var attachment in selectedAttachments)
                {
                    // in here is where I will delete the attachments based on what was selected.
                    attachment.DeleteFile();
                    db.Attachments.Remove(attachment);
                }

                try
                {
                    db.SaveChanges();
                }
                catch (SqlException ex)
                {
                    log.Error("An error has occured while accessing the database.", ex);
                    return(RedirectToAction("AnError", "Error"));
                }

                if (!alreadySubmitted)
                {
                    // Compose an email to send to PPMO Group and return to index
                    List <string> emailInfo = new List <string> {
                        "2", model.idea.email, model.idea.title, model.idea.body, model.idea.cre_user, model.idea.ID.ToString()
                    };
                    TempData["EmailInfo"] = emailInfo;

                    return(RedirectToAction("AutoEmail", "Mails"));
                    // This is only for Josh and Alex since they don't have access to AD
                    //return RedirectToAction("Index", "Ideas");
                }
                TempData["Message"] = "Your idea has been successfully submitted.";
                return(RedirectToAction("Index", "Ideas"));
            }
            return(View(model));
        }
        public ActionResult Submit([Bind(Include = "ID,title,body,cre_date,cre_user,statusCode,denialReason, mod_date, email, commentsNumber")] Idea idea, IEnumerable <HttpPostedFileBase> files)
        {
            if (ModelState.IsValid)
            {
                idea.cre_user = "******";
                idea.cre_date = DateTime.Now;
                idea.mod_date = DateTime.Now;
                idea.email    = " [email protected]";
                var ideas = db.Ideas.Where(IDEA => IDEA.title == idea.title).ToList();

                if (ideas.Count > 0)
                {
                    TempData["FailureMessage"] = "Title must be a unique value";
                    return(View(idea));
                }

                if (files != null)
                {
                    var appSettings = ConfigurationManager.AppSettings;

                    // store path to server location of the attachment storage
                    var connectionInfo = appSettings["serverPath"];

                    // combine the server location and the name of the new folder to be created
                    var storagePath = string.Format(@"{0}{1}_{2}", connectionInfo, idea.ID, idea.title);

                    // create the folder for the idea's attachments
                    DirectoryInfo di = Directory.CreateDirectory(storagePath);

                    // run each file through MetaScan and check for forbidden extensions
                    for (int i = 0; i < files.Count(); ++i)
                    {
                        if (files.ElementAt(i) != null && files.ElementAt(i).ContentLength > 0)
                        {
                            var file = files.ElementAt(i);
                            // store the name of the attachment

                            // place the file into a bytearray for MetaScan use
                            FileStream stream    = System.IO.File.OpenRead(Path.GetFullPath(file.FileName));
                            byte[]     fileBytes = new byte[stream.Length];

                            stream.Read(fileBytes, 0, fileBytes.Length);
                            stream.Close();

                            // make the file a bytearray and send to MetaScan here?
                            FileService.FileService sf = new FileService.FileService();

                            string ext = Path.GetExtension(file.FileName);

                            bool valrtn = sf.ScanByFileWithNameAndExtension(fileBytes, file.FileName, ext);

                            // If any file fails to load, reload the creation screen and inform the submitter of the need to scan the files.
                            if (!valrtn)
                            {
                                TempData["FailureMessage"] += "\n\nThe files failed to upload. " +
                                                              "Please scan them locally using McAffee before uploading them again.";

                                return(View(idea));
                            }
                        }
                    }

                    db.Ideas.Add(idea);

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (SqlException ex)
                    {
                        log.Error("An error has occured while accessing the database.", ex);
                        return(RedirectToAction("AnError", "Error"));
                    }
                    catch (DbUpdateException ex)
                    {
                        log.Error("Some other error has occured.", ex);
                        return(RedirectToRoute("NewError"));
                    }

                    // save the files to the specified folder and link them to the idea
                    for (int i = 0; i < files.Count(); ++i)
                    {
                        if (files.ElementAt(i) != null && files.ElementAt(i).ContentLength > 0)
                        {
                            var file           = files.ElementAt(i);
                            var attachmentName = Path.GetFileName(file.FileName);
                            var namepath       = string.Format("{0}\\{1}", storagePath, attachmentName);

                            // save the new Attachments to the Idea
                            var attachment = new Models.Attachment
                            {
                                storageLocation = string.Format("{0}\\", storagePath),
                                name            = attachmentName,
                                cre_date        = DateTime.Now,
                                deleteObj       = "false"
                            };

                            try
                            {
                                file.SaveAs(string.Format("{0}\\{1}", storagePath, attachmentName));
                            }
                            catch (Exception ex)
                            {
                                log.Error("An error has occured while attempting to save a file.", ex);
                                return(RedirectToAction("AnError", "Error"));
                            }

                            if (idea.attachments == null)
                            {
                                idea.attachments = new List <Models.Attachment>();
                            }

                            db.Attachments.Add(attachment);

                            try
                            {
                                db.SaveChanges();
                            }
                            catch (SqlException ex)
                            {
                                log.Error("There was an issue saving changes to the database.", ex);
                                return(RedirectToAction("AnError", "Error"));
                            }
                        }
                    }
                }

                try
                {
                    db.SaveChanges();
                }
                catch (SqlException ex)
                {
                    log.Error("An error has occured while accessing the database.", ex);
                    return(RedirectToAction("AnError", "Error"));
                }
                catch (Exception ex)
                {
                    log.Error("some other error has occured", ex);
                    Response.RedirectToRoute("NewError");
                    //return RedirectToAction("AnError", "Error");
                }


                // Compose an email to send to PPMO Group
                List <string> emailInfo = new List <string> {
                    "1", idea.email, idea.title, idea.body, idea.cre_user, idea.ID.ToString()
                };
                TempData["EmailInfo"] = emailInfo;
                return(RedirectToAction("AutoEmail", "Mails"));

                // This is only for Josh and Alex since they don't have access to AD
                //return RedirectToAction("Index", "Ideas");
            }
            return(View(idea));
        }
        public void Process(Dictionary <string, object> parameters)
        {
            IsComplete = false;
            Message       message       = null;
            List <string> botParameters = null;
            Stats         stats         = null;
            SlackClient   slackClient   = null;
            string        userName      = null;

            foreach (var item in parameters)
            {
                switch (item.Key)
                {
                case "stats": stats = (Stats)item.Value; break;

                case "userName": userName = (string)item.Value; break;

                case "message": message = (Message)item.Value; break;

                case "parameters": botParameters = (List <string>)item.Value; break;

                case "_slackClient": slackClient = (SlackClient)item.Value; break;

                default:
                    break;
                }
            }

            if (botParameters.Count == 4 && botParameters[1] == "weather" && botParameters[2] == "now")
            {
                stats.MessageDelivered();

                Models.Attachment attachment = new Models.Attachment
                {
                    Footer = "BordaBot",
                    Ts     = Extension.ToProperTimeStamp(DateTime.Now)
                };

                RestClient  restClient  = new RestClient("https://api.openweathermap.org/data/2.5");
                RestRequest restRequest = new RestRequest("weather", Method.GET);
                restRequest.AddParameter("q", botParameters[3]);
                restRequest.AddParameter("units", "metric");
                restRequest.AddParameter("appid", ConfigurationManager.AppSettings["WeatherApiKey"]);
                var      response   = JsonConvert.DeserializeObject <WeatherData>(restClient.Execute(restRequest).Content);
                TextInfo textInfo   = new CultureInfo("en-US", false).TextInfo;
                var      querryName = char.ToUpper(botParameters[3][0]) + botParameters[3].Substring(1, botParameters[3].Length - 1);

                attachment.Color    = "#00CEE9";
                attachment.Text     = "Weather now in " + querryName + " is " + textInfo.ToTitleCase(response.Weather[0].Description);
                attachment.ThumbUrl = "http://openweathermap.org/img/w/" + response.Weather[0].Icon + ".png";

                Field temp = new Field {
                    Title = "Temperature", Value = response.Main.Temp + " ℃", Short = true
                };
                Field hum = new Field {
                    Title = "Humidity", Value = response.Main.Humidity + "%", Short = true
                };
                Field pres = new Field {
                    Title = "Pressure Level", Value = response.Main.Pressure + " hPa", Short = true
                };
                Field windsp = new Field {
                    Title = "Wind Speed", Value = response.Wind.Speed + " meter/sec", Short = true
                };

                attachment.Fields = new List <Field>
                {
                    temp, hum, pres, windsp
                };

                string attachments = "[" + JsonConvert.SerializeObject(attachment) + "]";

                slackClient.PostMessage(message.Channel, "@" + userName + ", here is the weather in " + querryName + ":", false, attachments);
            }

            else if (botParameters.Count == 4 && botParameters[1] == "weather" && botParameters[2] == "forecast")
            {
                stats.MessageDelivered();
                List <Models.Attachment> attachments = new List <Models.Attachment>();

                RestClient  restClient  = new RestClient("https://api.openweathermap.org/data/2.5");
                RestRequest restRequest = new RestRequest("forecast", Method.GET);
                restRequest.AddParameter("q", botParameters[3]);
                restRequest.AddParameter("units", "metric");
                restRequest.AddParameter("appid", ConfigurationManager.AppSettings["WeatherApiKey"]);
                var response   = JsonConvert.DeserializeObject <WeatherForecast>(restClient.Execute(restRequest).Content);
                var querryName = char.ToUpper(botParameters[3][0]) + botParameters[3].Substring(1, botParameters[3].Length - 1);

                foreach (var item in response.List)
                {
                    if (item.DtTxt.Hour == 12)
                    {
                        Models.Attachment attachment = new Models.Attachment();

                        TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;

                        attachment.Color = "#00CEE9";
                        attachment.Text  = "Weather in " + querryName + " on " + item.DtTxt.ToString("dd/MM/yyyy hh:mm") + " is "
                                           + textInfo.ToTitleCase(item.Weather[0].Description);
                        attachment.ThumbUrl = "http://openweathermap.org/img/w/" + item.Weather[0].Icon + ".png";

                        Field temp = new Field {
                            Title = "Temperature", Value = item.Main.Temp + " ℃", Short = true
                        };
                        Field hum = new Field {
                            Title = "Humidity", Value = item.Main.Humidity + "%", Short = true
                        };
                        Field pres = new Field {
                            Title = "Pressure Level", Value = item.Main.Pressure + " hPa", Short = true
                        };
                        Field windsp = new Field {
                            Title = "Wind Speed", Value = item.Wind.Speed + " meter/sec", Short = true
                        };

                        attachment.Fields = new List <Field>
                        {
                            temp, hum, pres, windsp
                        };
                        attachments.Add(attachment);
                    }
                }

                attachments.Last().Footer = "BordaBot";
                attachments.Last().Ts     = Extension.ToProperTimeStamp(DateTime.Now);

                string attachmentString = JsonConvert.SerializeObject(attachments);

                slackClient.PostMessage(message.Channel, "@" + userName + ", here is the weather forecast for 5 days in " + querryName
                                        + ":", false, attachmentString);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            bool isImage = false, isCover = false, isProfile = false;

            if (context.Request.Form["IsCover"] != null)
                isCover = Convert.ToBoolean(context.Request.Form["IsCover"].ToString());
            if (context.Request.Form["IsProfile"] != null)
                isProfile = Convert.ToBoolean(context.Request.Form["IsProfile"].ToString());

            int userid = Convert.ToInt32(context.Request.Form["UserId"].ToString());
            int typeid = Convert.ToInt32(context.Request.Form["Type"].ToString());  // 1 - image , 2- audio , 3 - video
            isImage = (typeid == 1);

            var ext = System.IO.Path.GetExtension(context.Request.Files[0].FileName);
            string fileName = Guid.NewGuid().ToString();

            DirectoryInfo dir = new DirectoryInfo(context.Server.MapPath("~/userfiles/" + userid.ToString()));
            if (!dir.Exists)
                dir.Create();

            string location = context.Server.MapPath("~/userfiles/"+ userid.ToString() + "/") + fileName + ext;
            string thumblocation = context.Server.MapPath("~/userfiles/" + userid.ToString() + "/thumb_") + fileName + ".jpg";
            context.Request.Files[0].SaveAs(location);

            BLL.Attachment newfile = new BLL.Attachment();
            newfile.AddNew();
            if (typeid == 3)
            {
                (new NReco.VideoConverter.FFMpegConverter()).GetVideoThumbnail(location, thumblocation);
                newfile.ThumbsPath = "/userfiles/" + userid.ToString() + "/thumb_" + fileName + ".jpg";
            }

            if (typeid == 2)
            {
                try
                {

                    //string wavfile = location.Replace(".amr", ".wav");
                    string newlocation = context.Server.MapPath("~/userfiles/" + userid.ToString() + "/") + fileName + ".mp3";
                    (new NReco.VideoConverter.FFMpegConverter()).ConvertMedia(location, newlocation, "mp3");
                    ext = ".mp3";
                }
                catch (Exception e)
                {
                }
            }

            newfile.Path = "/userfiles/"+ userid.ToString() + "/" + fileName + ext;
            newfile.AttachmentTypeID = typeid;

            newfile.Save();

            if (isCover || isProfile)
            {
                BLL.ComboUser user = new ComboUser();
                user.LoadByPrimaryKey(userid);
                if (isCover)
                    user.CoverImgID = newfile.AttachmentID;
                if (isProfile)
                    user.ProfileImgID = newfile.AttachmentID;
                user.Save();
            }

            Models.Attachment responseText = new Models.Attachment();
            responseText.AttachmentID = newfile.AttachmentID;
            responseText.Path = newfile.Path;
            if (newfile.AttachmentTypeID == 3)
                responseText.ThumbsPath = newfile.ThumbsPath;
            responseText.AttachmentTypeID = newfile.AttachmentTypeID;

            Models.ComboResponse _response = new Models.ComboResponse();
            _response.bool_result = true;
            _response.ErrorCode = 0;
            _response.ErrorMsg = "";
            _response.Entity = new Models.Attachment[] { responseText };
            SetContentResult(_response);
        }