public ActionResult Create(Product product, HttpPostedFileBase file)
        {
            long?UserID = Convert.ToInt64(User.Identity.Name);

            if (ModelState.IsValid)
            {
                string pic = "";
                if (file != null)
                {
                    if (file.ContentLength != 0)
                    {
                        pic = System.IO.Path.GetFileName(file.FileName);
                        pic = Guid.NewGuid() + "_" + pic;
                        string path = System.IO.Path.Combine(Server.MapPath("~/Content/upload/" + UserID + "/Commerce"), pic);
                        // file is uploaded
                        file.SaveAs(path);
                        //   product.ProductImage = "Content/upload/" + UserID + "/Commerce/" + pic;
                        product.ProductImage = "/xImage/" + UserID + "/Commerce/" + pic;
                        UserUsage userUsage = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                        userUsage.UsedStorage += Mathmatics.ConvertBytesToMegabytes(file.ContentLength);
                        db.SaveChanges();
                    }
                }

                product.UserID = UserID;
                db.Products.Add(product);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CatagoryID = new SelectList(db.ProductCatagories.Where(x => x.UserID == UserID), "Id", "CatagoryName");
            return(View(product));
        }
예제 #2
0
 public ActionResult DeleteFile(int?Id)
 {
     using (var tran = db.Database.BeginTransaction())
     {
         try
         {
             string         filePath = null;
             long?          UserID   = Convert.ToInt64(User.Identity.Name);
             FileCollection fileCol  = db.FileCollections.FirstOrDefault(x => x.Id == Id && x.UserID == UserID);
             filePath = Server.MapPath("~/" + fileCol.FilePath);
             db.FileCollections.Remove(fileCol);
             db.SaveChanges();
             if (!string.IsNullOrEmpty(filePath))
             {
                 if (System.IO.File.Exists(filePath))
                 {
                     long length = new System.IO.FileInfo(filePath).Length;
                     System.IO.File.Delete(filePath);
                     UserUsage userUsage = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                     userUsage.UsedStorage = userUsage.UsedStorage - Mathmatics.ConvertBytesToMegabytes(length);
                     db.SaveChanges();
                 }
             }
             tran.Commit();
         }
         catch (Exception er)
         {
             tran.Rollback();
         }
     }
     return(RedirectToAction("UploadImage"));
 }
예제 #3
0
        public ActionResult UploadImage(HttpPostedFileBase file)
        {
            string pic    = "";
            var    UserID = Convert.ToInt64(User.Identity.Name);

            using (var trans = db.Database.BeginTransaction())
            {
                try
                {
                    if (file != null)
                    {
                        if (file.ContentLength != 0)
                        {
                            FileCollection fileCol = new FileCollection();
                            if (!System.IO.Directory.Exists(Server.MapPath("~/Content/upload")))
                            {
                                System.IO.Directory.CreateDirectory(Server.MapPath("~/Content/upload"));
                            }
                            pic = System.IO.Path.GetFileName(file.FileName);
                            string picExtention = System.IO.Path.GetExtension(pic);
                            pic = Guid.NewGuid() + "_a" + picExtention;
                            string path = System.IO.Path.Combine(Server.MapPath("~/Content/upload/" + UserID), pic);
                            // file uploading
                            file.SaveAs(path);
                            // string filePath = "http://" + Request.ServerVariables["HTTP_HOST"] + "/Content/filecollection/" + pic;
                            string filePath = "Content/upload/" + UserID + "/" + pic;
                            fileCol.FilePath = filePath;
                            fileCol.UserID   = UserID;
                            db.FileCollections.Add(fileCol);
                            db.SaveChanges();
                            UserUsage userUsage = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                            userUsage.UsedStorage += Mathmatics.ConvertBytesToMegabytes(file.ContentLength);
                            db.SaveChanges();
                            trans.Commit();
                            TempData["Msg"] = "<h2 class='text-center' style='display: block; color: green'>File has been uploaded</h2><p><b>Link to Copy:  </b> " + filePath + "</p>";
                            return(RedirectToAction("UploadImage"));
                        }
                        else
                        {
                            TempData["Msg"] = "<h2 class='text-center' style='display: block; color: green'>File not uploaded.  Please try agian</h2>";
                            return(RedirectToAction("UploadImage"));
                        }
                    }
                }
                catch (Exception er)
                {
                    trans.Rollback();
                }
            }
            TempData["Msg"] = "<h2 class='text-center' style='display: block; color: green'>There is an error please try again.</h2>";
            return(RedirectToAction("UploadImage"));
        }
예제 #4
0
        public object Get(UserGetUsageRequestTep request)
        {
            List <KeyValuePair <string, string> > result = new List <KeyValuePair <string, string> >();

            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/user/{{id}}/usage GET id='{0}'", request.Id));
                var       user = (request.Id != 0 ? User.FromId(context, request.Id) : User.FromUsername(context, request.Identifier));
                UserUsage usu  = new UserUsage(context, user.Id);

                //global usage
                result.Add(new KeyValuePair <string, string>("overall", "" + usu.GetScore()));

                //data package usage
                List <Type> types = new List <Type>();
                types.Add(typeof(DataPackage));
                types.Add(typeof(RemoteResource));
                types.Add(typeof(RemoteResourceSet));
                result.Add(new KeyValuePair <string, string>("data/package", "" + usu.GetScore(types)));

                //wps job usage
                types = new List <Type>();
                types.Add(typeof(WpsJob));
                result.Add(new KeyValuePair <string, string>("job/wps", "" + usu.GetScore(types)));

                //wps service usage
                types = new List <Type>();
                types.Add(typeof(Terradue.Portal.Service));
                types.Add(typeof(WpsProcessOffering));
                result.Add(new KeyValuePair <string, string>("service/wps", "" + usu.GetScore(types)));

                context.LogDebug(this, string.Format("Get User '{0}' usage", User.FromId(context, usu.UserId).Username));

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
        public ActionResult Edit(User user, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                using (var trasn = db.Database.BeginTransaction())
                {
                    try
                    {
                        long?  UserID     = Convert.ToInt64(User.Identity.Name);
                        User   detail     = db.Users.Find(UserID);
                        string OldPicPath = detail.ProfilePic;
                        string pic        = "";
                        if (file != null)
                        {
                            if (file.ContentLength != 0)
                            {
                                pic = System.IO.Path.GetFileName(file.FileName);
                                pic = Guid.NewGuid() + "_" + pic;
                                string path = System.IO.Path.Combine(Server.MapPath("~/Content/upload/" + UserID), pic);
                                // file is uploaded
                                file.SaveAs(path);
                                detail.ProfilePic = "Content/upload/" + UserID + "/" + pic;
                                UserUsage userUsage = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                                userUsage.UsedStorage += Mathmatics.ConvertBytesToMegabytes(file.ContentLength);
                                db.SaveChanges();
                            }
                        }

                        detail.FirstName  = user.FirstName;
                        detail.LastName   = user.LastName;
                        detail.Email      = user.Email;
                        detail.Address    = user.Address;
                        detail.CellNumber = user.CellNumber;
                        detail.Password   = user.Password;

                        db.SaveChanges();
                        Session["UserProfilePath"] = detail.ProfilePic;
                        Session["UserFirstName"]   = !string.IsNullOrEmpty(detail.FirstName) ? detail.FirstName.ToUpper() : "Hi!";

                        if (!string.IsNullOrEmpty(OldPicPath))
                        {
                            string fileToDelete = Server.MapPath("~/" + OldPicPath);
                            if (!string.IsNullOrEmpty(fileToDelete))
                            {
                                if (System.IO.File.Exists(fileToDelete))
                                {
                                    long length = new System.IO.FileInfo(fileToDelete).Length;
                                    System.IO.File.Delete(fileToDelete);
                                    UserUsage PriHistory = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                                    PriHistory.UsedStorage = PriHistory.UsedStorage - Mathmatics.ConvertBytesToMegabytes(length);
                                    db.SaveChanges();
                                }
                            }
                        }
                        trasn.Commit();
                        return(RedirectToAction("Index"));
                    }
                    catch (Exception er)
                    {
                        trasn.Rollback();
                    }
                }
            }
            return(View(user));
        }
예제 #6
0
        public async Task <ActionResult> Edit(ShopUser shopUser, HttpPostedFileBase file)
        {
            using (var Tran = db.Database.BeginTransaction())
            {
                try
                {
                    // validate current sub domain
                    domainIndentifier = new DomainIdentifier(Request.Url.Host, Request.ServerVariables["SERVER_NAME"]);
                    var User = domainIndentifier.GetUserRelatedDomain();
                    UserID                   = User != null ? User.Id : 0;
                    ViewBag.UserID           = UserID;
                    Session["CurrentUserID"] = UserID;

                    //// check user is login or not
                    if (string.IsNullOrEmpty(Convert.ToString(Session["WebloggedUserID"])))
                    {
                        return(Redirect("/Account/Login"));
                    }

                    // bussiness logic
                    long ShopUserID = Convert.ToInt64(Session["WebloggedUserID"]);
                    ViewBag.ShopUserID = ShopUserID;

                    if (ModelState.IsValid)
                    {
                        ShopUser Customer = db.ShopUsers.FirstOrDefault(x => x.Id == ShopUserID);
                        if (!System.IO.Directory.Exists(Server.MapPath("~/Content/upload/" + UserID + "/Commerce")))
                        {
                            System.IO.Directory.CreateDirectory(Server.MapPath("~/Content/upload/" + UserID + "/ShopUsers"));
                        }

                        if (file != null)
                        {
                            if (file.ContentLength > 0)
                            {
                                string FileExtention = Path.GetExtension(file.FileName);
                                string FileName      = Guid.NewGuid().ToString() + DateTime.Now.ToString("yyyydd") + ShopUserID + FileExtention;
                                string FileSavePath  = System.IO.Path.Combine(Server.MapPath("~/Content/upload/" + UserID + "/ShopUsers"), FileName);
                                file.SaveAs(FileSavePath);
                                Customer.ProfileImagePath = "Content/upload/" + UserID + "/ShopUsers" + FileName;
                            }
                        }
                        int    IsSavedIntoStorageTable = 0;
                        string PreProfilePath          = Customer.ProfileImagePath;
                        Customer.CurrentAddress   = shopUser.CurrentAddress;
                        Customer.DisplayName      = shopUser.DisplayName;
                        Customer.Email            = shopUser.Email;
                        Customer.FirstName        = shopUser.FirstName;
                        Customer.LastName         = shopUser.LastName;
                        Customer.Mobile           = shopUser.Mobile;
                        Customer.Password         = shopUser.Password;
                        Customer.PermanentAddress = shopUser.PermanentAddress;
                        Customer.Phone            = shopUser.Phone;
                        Customer.SecPhone         = shopUser.SecPhone;
                        int isSavedIntoShopUser = await db.SaveChangesAsync();      // Insert Data

                        if (!string.IsNullOrEmpty(PreProfilePath))
                        {
                            string fileToDelete = Server.MapPath("~/" + PreProfilePath);
                            if (!string.IsNullOrEmpty(fileToDelete))
                            {
                                if (System.IO.File.Exists(fileToDelete))
                                {
                                    long      length     = new System.IO.FileInfo(fileToDelete).Length;
                                    UserUsage PriHistory = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                                    PriHistory.UsedStorage  = PriHistory.UsedStorage - Mathmatics.ConvertBytesToMegabytes(length);
                                    IsSavedIntoStorageTable = db.SaveChanges();                           // Insert Data
                                    System.IO.File.Delete(fileToDelete);
                                }
                            }
                        }
                        if (isSavedIntoShopUser > 0 && IsSavedIntoStorageTable > 0)
                        {
                            Tran.Commit();
                            return(RedirectToAction("Detail"));
                        }
                        return(View(shopUser));
                    }
                }
                catch (Exception er)
                {
                    Tran.Rollback();
                }
                return(View(shopUser));
            }
        }
예제 #7
0
        public ActionResult Edit(SiteSetting siteSetting, HttpPostedFileBase file)
        {
            using (var Transaction = db.Database.BeginTransaction())
            {
                long?UserID  = Convert.ToInt64(User.Identity.Name);
                var  setting = db.SiteSettings.FirstOrDefault(x => x.UserID == UserID);

                try
                {
                    if (ModelState.IsValid)
                    {
                        string OldLogoPath = setting.Logo;
                        string pic         = "";
                        if (file != null)
                        {
                            if (file.ContentLength != 0)
                            {
                                pic = System.IO.Path.GetFileName(file.FileName);
                                pic = Guid.NewGuid() + "_" + pic;
                                string path = System.IO.Path.Combine(Server.MapPath("~/Content/upload/" + UserID), pic);
                                // file is uploaded
                                file.SaveAs(path);
                                setting.Logo = "Content/upload/" + UserID + "/" + pic;
                                UserUsage userUsage = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                                userUsage.UsedStorage += Mathmatics.ConvertBytesToMegabytes(file.ContentLength);
                                db.SaveChanges();
                            }
                        }

                        setting.Email           = siteSetting.Email;
                        setting.OfficeAddress   = siteSetting.OfficeAddress;
                        setting.Phone           = siteSetting.Phone;
                        setting.SmtpEmail       = siteSetting.SmtpEmail;
                        setting.SmtpIsEnableSSL = siteSetting.SmtpIsEnableSSL;
                        setting.SmtpPassword    = siteSetting.SmtpPassword;
                        setting.SmtpPort        = siteSetting.SmtpPort;
                        setting.SmtpServer      = siteSetting.SmtpServer;

                        db.SaveChanges();

                        if (!string.IsNullOrEmpty(OldLogoPath))
                        {
                            string fileToDelete = Server.MapPath("~/" + OldLogoPath);
                            if (!string.IsNullOrEmpty(fileToDelete))
                            {
                                if (System.IO.File.Exists(fileToDelete))
                                {
                                    long      length     = new System.IO.FileInfo(fileToDelete).Length;
                                    UserUsage PriHistory = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                                    PriHistory.UsedStorage = PriHistory.UsedStorage - Mathmatics.ConvertBytesToMegabytes(length);
                                    db.SaveChanges();
                                    System.IO.File.Delete(fileToDelete);
                                }
                            }
                        }

                        Transaction.Commit();
                        return(RedirectToAction("Index"));
                    }
                }
                catch (Exception er)
                {
                    Transaction.Rollback();
                }
                return(View(setting));
            }
        }
예제 #8
0
        public List <Ingredient> GetRecipe(long id)
        {
            //HttpRequest currentRequest = HttpContext.Request.;
            //HttpRequest currentRequest = HttpContext.Current.Request;
            //String clientIP = currentRequest.ServerVariables["REMOTE_ADDR"];
            String ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress;

            UserUsage myUser = new UserUsage {
                dateTimeUpdate = DateTime.Now, CocktailId = id, Address = ipAddress
            };
            List <Ingredient> MyIngredients = new List <Ingredient>();
            var Mliquor     = (from c in db.CocktailLiquors where c.CocktailId == id select new { c.Amount, c.Liquor.Name, c.Id, c.CocktailId }).ToList();
            var MnoAlcohols = (from b in db.CocktailNoAlcohols where b.CocktailId == id select new { b.Amount, b.NoAlcohol.Name, b.Id, b.CocktailId }).ToList();
            var Mcordials   = (from a in db.CocktailCordials where a.CocktailId == id select new { a.Amount, a.Cordial.Name, a.Id, a.CocktailId }).ToList();
            //var Mgarnishes = db.Garnishes.Select(g => g.CockTails.Select(co => co.CocktailId == id)).ToList();
            //var Mgarnishes = (from d in db.Garnishes select d.CockTails.Select(s=>s.CocktailId==id)).ToList();
            //var Mgarnishes = (from d in db.Garnishes.ToList() let Amount =(float)1.0 where d.CockTails.Where == id select new {d.Name,d. }).ToList();
            var Mgarnishes = (from d in db.Garnishes from e in d.CockTails where e.CocktailId == id select new { d.Name, d.Id, id }).ToList();
            var Mprocesses = (from d in db.Processes from e in d.CockTails where e.CocktailId == id select new { d.Name, d.Id, id }).ToList();

            var Mglass    = (from gl in db.CockTails where gl.CocktailId == id select gl.Glass).Single();
            var Mcategory = (from ct in db.CockTails where ct.CocktailId == id select ct.Category).Single();

            //var Mprocess = (from p in db.CockTails where p.CocktailId == id select p.Process).Single();

            foreach (var ing in Mliquor)
            {
                MyIngredients.Add(new Ingredient {
                    CocktailId = (int)ing.CocktailId, Id = ing.Id, Type = "L", Amount = ing.Amount, Name = ing.Name
                });
            }
            foreach (var ing in MnoAlcohols)
            {
                MyIngredients.Add(new Ingredient {
                    CocktailId = (int)ing.CocktailId, Id = ing.Id, Type = "N", Amount = ing.Amount, Name = ing.Name
                });
            }
            foreach (var ing in Mcordials)
            {
                MyIngredients.Add(new Ingredient {
                    CocktailId = (int)ing.CocktailId, Id = ing.Id, Type = "C", Amount = ing.Amount, Name = ing.Name
                });
            }
            foreach (var ing in Mgarnishes)
            {
                //    MyIngredients.Add(new Ingredient { CocktailId = (int)ing.CocktailId, Id = ing.Id, Type = "G", Amount = 1, Name = ing.Name });
                MyIngredients.Add(new Ingredient {
                    CocktailId = (int)id, Id = ing.Id, Type = "G", Amount = 1, Name = ing.Name
                });
            }
            foreach (var ing in Mprocesses)
            {
                //    MyIngredients.Add(new Ingredient { CocktailId = (int)ing.CocktailId, Id = ing.Id, Type = "G", Amount = 1, Name = ing.Name });
                MyIngredients.Add(new Ingredient {
                    CocktailId = (int)id, Id = ing.Id, Type = "P", Amount = 1, Name = ing.Name
                });
            }

            MyIngredients.Add(new Ingredient {
                CocktailId = (int)id, Id = id, Type = "S", Amount = 1, Name = Mglass.Name
            });                                                                                                              // Here is adding a glass
            //MyIngredients.Add(new Ingredient { CocktailId = (int)id, Id = id, Type = "R", Amount = 1, Name = Mcategory.Name }); // Here is adding a the category
            //MyIngredients.Add(new Ingredient { CocktailId = (int)id, Id = id, Type = "P", Amount = 1, Name = Mprocess.Name });
            db.UserUsages.Add(myUser);
            db.SaveChanges();
            return(MyIngredients);
        }
예제 #9
0
        public void Post(UserUsage usage)
        {
            var repo = new UsageRepository();

            repo.Save(new UsageRow(usage));
        }
        public ActionResult Edit(Product productModel, HttpPostedFileBase file)
        {
            long?UserID  = Convert.ToInt64(User.Identity.Name);
            var  product = db.Products.FirstOrDefault(x => x.UserID == UserID && x.Id == productModel.Id);

            using (var Tran = db.Database.BeginTransaction())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        string oldImage = product.ProductImage;
                        string pic      = "";
                        if (file != null)
                        {
                            if (file.ContentLength != 0)
                            {
                                pic = System.IO.Path.GetFileName(file.FileName);
                                pic = Guid.NewGuid() + "_" + pic;
                                string path = System.IO.Path.Combine(Server.MapPath("~/Content/upload/" + UserID + "/Commerce"), pic);
                                // file is uploaded
                                file.SaveAs(path);
                                // product.ProductImage = "Content/upload/" + UserID + "/Commerce/" + pic;
                                product.ProductImage = "/xImage/" + UserID + "/Commerce/" + pic;
                                UserUsage userUsage = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                                userUsage.UsedStorage += Mathmatics.ConvertBytesToMegabytes(file.ContentLength);
                                db.SaveChanges();
                            }
                        }

                        product.UserID          = UserID;
                        product.Name            = productModel.Name;
                        product.Description     = productModel.Description;
                        product.Discount        = productModel.Discount;
                        product.Price           = productModel.Price;
                        productModel.CatagoryID = productModel.CatagoryID;

                        db.SaveChanges();

                        if (!string.IsNullOrEmpty(oldImage))
                        {
                            string fileToDelete = Server.MapPath("~/" + oldImage);
                            if (!string.IsNullOrEmpty(fileToDelete))
                            {
                                if (System.IO.File.Exists(fileToDelete))
                                {
                                    long      length     = new System.IO.FileInfo(fileToDelete).Length;
                                    UserUsage PriHistory = db.UserUsages.FirstOrDefault(x => x.UserID == UserID);
                                    PriHistory.UsedStorage = PriHistory.UsedStorage - Mathmatics.ConvertBytesToMegabytes(length);
                                    db.SaveChanges();
                                    System.IO.File.Delete(fileToDelete);
                                }
                            }
                        }

                        return(RedirectToAction("Index"));
                    }
                    Tran.Commit();
                    ViewBag.CatagoryID = new SelectList(db.ProductCatagories.Where(x => x.UserID == UserID), "Id", "CatagoryName");
                }
                catch (Exception er)
                {
                    Tran.Rollback();
                }
            }
            return(View(product));
        }
예제 #11
0
        private decimal CalculateEmission(UserUsage usage, decimal oldEmission)
        {
            decimal finalEmission = 0;

            try
            {
                var rand         = new Random();
                var factor       = 0.0;
                var averageUsage = 0.0;

                switch (usage.Product.Trim().ToUpper())
                {
                case "BEDROOMS":
                    factor       = 0.27;
                    averageUsage = 4;
                    break;

                case "COMPUTER":
                    factor       = 0.19;
                    averageUsage = 4;
                    break;

                case "MOBILE PHONES":
                    factor       = 0.02;
                    averageUsage = 4;
                    break;

                case "TELEVISION":
                    factor       = 0.58;
                    averageUsage = 8;
                    break;

                case "MICROWAVE OVEN":
                    factor       = 0.945;
                    averageUsage = 1;
                    break;

                case "OVEN":
                    factor       = 1.56;
                    averageUsage = 1;
                    break;

                case "AIRCONDITIONER":
                    factor       = 1.25;
                    averageUsage = 2.5;
                    break;

                case "HEATER":
                    factor       = 1.11;
                    averageUsage = 2.5;
                    break;

                case "REFRIGERATOR":
                    factor       = 0.42;
                    averageUsage = 24;
                    break;

                case "FREEZER":
                    factor       = 0.56;
                    averageUsage = 24;
                    break;

                case "DISHWASHER":
                    factor       = 1.07;
                    averageUsage = 1.5;
                    break;

                case "DRYER":
                    factor       = 2.50;
                    averageUsage = 1;
                    break;

                case "WASHING MACHINE":
                    factor       = 0.63;
                    averageUsage = 1;
                    break;

                case "LIGHT BULB":
                    factor       = 0.08;
                    averageUsage = 12;
                    break;
                }

                usage.Emission = (decimal)(usage.Quantity * factor * averageUsage * 365);

                // update user emission
                var username = Context.User.Identity.GetUserId();
                var user     = _connections.Get(username);
                if (user != null)
                {
                    user.Emission -= oldEmission;
                    user.Emission += usage.Emission;
                    finalEmission  = user.Emission;
                    _connections.Update(user);
                }
            }
            catch
            {
            }

            return(finalEmission);
        }
예제 #12
0
        public void AddUsage(string product, int quantity)
        {
            try
            {
                decimal finalEmission = 0;
                var     username      = Context.User.Identity.GetUserId();
                var     ctx           = ApplicationDbContext.Create();
                var     usage         =
                    ctx.UserUsages.FirstOrDefault(
                        u =>
                        u.Username.Equals(username, StringComparison.InvariantCultureIgnoreCase) &&
                        u.Product.Equals(product, StringComparison.InvariantCultureIgnoreCase));

                if (usage == null)
                {
                    usage = new UserUsage
                    {
                        Username = username,
                        Emission = 0,
                        Product  = product,
                        Quantity = quantity
                    };

                    finalEmission = CalculateEmission(usage, 0);

                    ctx.UserUsages.Add(usage);
                }
                else
                {
                    if (quantity <= 0)
                    {
                        finalEmission = RemoveUsage(usage.Id);
                    }
                    else
                    {
                        var oldEmission = usage.Emission;
                        usage.Quantity = quantity;
                        finalEmission  = CalculateEmission(usage, oldEmission);
                    }
                }

                var appUser =
                    ctx.Users
                    .FirstOrDefault(u => u.Id.ToString().Equals(username, StringComparison.InvariantCultureIgnoreCase));

                if (appUser != null)
                {
                    appUser.Emission = finalEmission;
                }

                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                GetMyUsage();
                UserListChanged();
            }
        }