public Quota GetQuota(double capital, double rate, int term) { var total = ((capital * (1 + rate)) / term); var quota = new Quota(); quota.Capital = capital/term; quota.RateAmount = quota.Capital*rate; return quota; }
/// <summary> /// There are no comments for Quota in the schema. /// </summary> public void AddToQuota(Quota quota) { base.AddObject("Quota", quota); }
/// <summary> /// Creates a new user quota. When creating a quota, the Type and Limit /// fields are required. The Units and Usage fields are ignored. /// </summary> /// <param name="userId"></param> /// <param name="newQuota"></param> /// <returns></returns> public Quota CreateUserQuota(string userId, Quota newQuota) { // POST throw new NotImplementedException(); }
/// <summary> ///Le système doit permettre d’enregistrer une visite et de facturer le client /// en créant le client s'il n'exite pas /// en créant la provenance , la transaction et la liste des matieres de la visite /// et la fait la mise a jour des quota /// </summary> /// <param name="visite"></param> /// <returns></returns> public Visite CreateVisite(Visite visite) { using (var transaction = _context.Database.BeginTransaction()) { try { /// le client s'il n'exite pas visite.DateCreation = DateTime.Now; bool Iscommerce = string.IsNullOrEmpty(visite.Client.NomCommerce); if ((visite.IClient == 0) || (!_context.Client.Any(c => c.IdClient == visite.IClient))) { /// Creation du Client et entreprise visite.Client.IdClient = 0; visite.Client.DateCreation = DateTime.Now; _context.Client.Add(visite.Client); _context.SaveChanges(); } else { visite.Client = null; } /// Creation de l'adresse et Quota if (!string.IsNullOrEmpty(visite.Provenance.IdCivique)) { /// Verifit si l'adresse existe var adresse = _context.Adresse.FirstOrDefault(a => a.IdCivique == visite.Provenance.IdCivique); if (adresse == null) { var _adresse = new Adresse { IdCivique = visite.Provenance.IdCivique, Nom = visite.Provenance.Adresse }; _context.Adresse.Add(_adresse); _context.SaveChanges(); /// Quota var dtdebut = new DateTime(DateTime.Now.Year, 1, 1); var dtdefin = new DateTime(DateTime.Now.Year, 12, 31); var quotaStandard = _context.Quota_Standard.First(); var _quota = new Quota { IdCivique = visite.Provenance.IdCivique, DateDebut = dtdebut, DateFin = dtdefin, Quantite_Disponible = quotaStandard.Quantite, Quantite_Initiale = quotaStandard.Quantite, Quantite_Commerce = quotaStandard.Quantite_Commerce }; _context.Quota.Add(_quota); _context.SaveChanges(); visite.Provenance.Quantite_Disponible = string.IsNullOrWhiteSpace(visite.Client.NomCommerce) ?_quota.Quantite_Disponible: _quota.Quantite_Commerce; } } // Creation de la Provenance /// Verification des Quota /// Si une adresse officielle n’existe pas dans les bases de données de la ville visite.Provenance.Quantite_Initiale = visite.Provenance.Quantite_Disponible; if (string.IsNullOrEmpty(visite.Provenance.IdCivique)) { /// si le client ne montre pas une preuve de résidence if (visite.Provenance.Quantite_Disponible > 0) { if (visite.Provenance.Quantite_Disponible > visite.Transaction.Volume) { visite.Provenance.Quantite_Disponible -= (long)visite.Transaction.Volume; visite.Transaction.Quantite_Utilisee = (long)visite.Transaction.Volume; visite.Transaction.Volume = 0; } else { visite.Transaction.Volume -= visite.Provenance.Quantite_Disponible; visite.Provenance.Quantite_Disponible = 0; visite.Transaction.Quantite_Utilisee = (long)visite.Transaction.Volume; } } } else { if (visite.Provenance.Quantite_Disponible > visite.Transaction.Volume) { visite.Provenance.Quantite_Disponible -= (long)visite.Transaction.Volume; } else { visite.Provenance.Quantite_Disponible = 0; } } _context.Provenance.Add(visite.Provenance); _context.SaveChanges(); /// Verification des Quota Cas Adressse Officielle if (!string.IsNullOrEmpty(visite.Provenance.IdCivique)) { var _quota = _context.Quota.FirstOrDefault(p => p.IdCivique == visite.Provenance.IdCivique); if (_quota != null && _quota.DateFin >= DateTime.Now.Date) { long _qauntiteUtilise = 0; /// Calcul du Volume facturable if (!string.IsNullOrWhiteSpace(visite.Client.NomCommerce)) { if (_quota.Quantite_Commerce > visite.Transaction.Volume) { _quota.Quantite_Commerce -= (long)visite.Transaction.Volume; _qauntiteUtilise = (long)visite.Transaction.Volume; visite.Transaction.Volume = 0; } else { visite.Transaction.Volume -= _quota.Quantite_Commerce; _qauntiteUtilise = (long)visite.Transaction.Volume; _quota.Quantite_Commerce = 0; } } else { if (_quota.Quantite_Disponible > visite.Transaction.Volume) { _quota.Quantite_Disponible -= (long)visite.Transaction.Volume; _qauntiteUtilise = (long)visite.Transaction.Volume; visite.Transaction.Volume = 0; } else { visite.Transaction.Volume -= _quota.Quantite_Disponible; _qauntiteUtilise = (long)visite.Transaction.Volume; _quota.Quantite_Disponible = 0; } } visite.Transaction.Quantite_Utilisee = _qauntiteUtilise; _context.SaveChanges(); /// Enregistrement de l'historique des quota var historiqueQuota = new Historique_Quota { DateHistorique = DateTime.Now, DateDebut = _quota.DateDebut, DateFin = _quota.DateFin, IdCivique = _quota.IdCivique, IdQuota = _quota.IdQuota, Quantite_Utilisee = _qauntiteUtilise, Quantite_Initiale = visite.Provenance.Quantite_Initiale }; _context.Historique_Quota.Add(historiqueQuota); _context.SaveChanges(); } } /// Facturation Chargement de la tarification var tarif = _context.Tarification.First(); visite.Transaction.Total = Iscommerce ? visite.Transaction.Volume * tarif.Prix : visite.Transaction.Volume * tarif.Prix_Commerce; /// On ne facture pas lorsqu'il s'agit d'une nouvelle adresse visite.Transaction.Total = string.IsNullOrEmpty(visite.Provenance.IdCivique) ? 0 : visite.Transaction.Total; // Creation de la visite , Transaction et des Matiere de la visite visite.IClient = visite.Client == null ? visite.IClient : visite.Client.IdClient; visite.IdProvenance = visite.Provenance.IdProvenance; visite.Ecocentre = null; visite.Transaction.ModePaiement = null; _context.Visite.Add(visite); visite.Transaction.IdVisite = visite.IdVisite; _context.Transaction.Add(visite.Transaction); _context.SaveChanges(); transaction.CommitAsync(); } catch (Exception ex) { transaction.RollbackAsync(); throw ex; } } return(GetVisite(visite.IdVisite)); }
public void AssignQuota(int id) { TrainAssignQuotaViewData viewData = new TrainAssignQuotaViewData(); Classes classes = (from c in CQGJ.Classes where c.ClassID == id select c).First(); viewData.Quotas = (from q in CQGJ.Quota where q.Classes.ClassID == id select q).ToList(); Plan plan = (from c in CQGJ.Classes from p in CQGJ.Plan where c.ClassID == id where c.Plan == p select p).First(); viewData.PlanID = plan.PlanID; List<CQGJ.passport.b01> orgList = cqgjPassport.GetOrglistByType(1).ToList(); List<CQGJ.passport.b01> orgList2 = cqgjPassport.GetOrglistByType(2).ToList(); List<CQGJ.passport.b01> orgList4 = cqgjPassport.GetOrglistByType(4).ToList(); foreach (CQGJ.passport.b01 b in orgList2) { orgList.Add(b); } foreach (CQGJ.passport.b01 b in orgList4) { orgList.Add(b); } if (viewData.Quotas.Count <= 0) { foreach (CQGJ.passport.b01 b in orgList) { Quota quota = new Quota(); quota.Classes = classes; Org org = (from o in CQGJ.Org where o.OrgCode == b.b0111 select o).First(); quota.Org = org; quota.Number = 0; quota.SignupNumber = 0; CQGJ.AddToQuota(quota); CQGJ.SaveChanges(); } viewData.Quotas = (from q in CQGJ.Quota where q.Classes.ClassID == id select q).ToList(); } //如果名额不为零就保存修改 bool f = false; foreach (Quota quota in viewData.Quotas) { if (GetInt(quota.QuotaID.ToString()) != 0) { quota.Number = GetInt(quota.QuotaID.ToString()); f = true; } } //保存成功后跳转到计划班级列表 if (f == true) { classes.Status = (int)ClassStatus.Signup; CQGJ.SaveChanges(); RedirectToAction("editplan/" + plan.PlanID + "/1"); //后面之所以要加/1是因为要跳转到第1页 } viewData.PlanClassID = id; RenderView("AssignQuota", viewData); }
public void ProcessRequest(HttpContext context) { string reply_str = ""; var db = new EchoContext(); SmsRegistrationLog sms_log = new SmsRegistrationLog(); string sms_log_result = ""; try { string keyword = context.Request.Form["keyword"] == null ? string.Empty : context.Request.Form["keyword"]; string content = context.Request.Form["content"] == null ? string.Empty : context.Request.Form["content"]; string mobile_no = context.Request.Form["mobile_no"] == null ? string.Empty : context.Request.Form["mobile_no"]; //string msg = context.Request.Form["msg"] == null ? string.Empty : context.Request.Form["msg"]; sms_log.Mobile_Number = mobile_no; sms_log.RQ_Msg = "-"; sms_log.RQ_Keyword = keyword; sms_log.RQ_Content = content; int result = CustomValidate.ValidateNumber(mobile_no); bool flag = true; if (result != 1 && result != 4) { flag = false; if (result == 2 || result == 3 || result == 5) { reply_str = System.Configuration.ConfigurationManager.AppSettings["EXIST_NUMBER"]; sms_log_result = "Existing number"; } if (result == 6) { reply_str = System.Configuration.ConfigurationManager.AppSettings["NO_ACCTACTIVATION"]; sms_log_result = "Maintenance Period"; } } if (flag) { if (IsValid(keyword, content)) { string[] content_arrs = content.Split(' '); string gender = content_arrs[0]; string dob = content_arrs[1]; string[] result_sp = new string[2]; byte day = Convert.ToByte(dob.Substring(0, 2)); byte month = Convert.ToByte(dob.Substring(2, 2)); int year = Convert.ToInt16(dob.Substring(4, 4)); year = year - 543; #region transaction var transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; transactionOptions.Timeout = TransactionManager.MaximumTimeout; Account account = new Account(); DateTime timestamp = DateTime.Now; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { var db_transaction = new EchoContext(); account.Gender_Cd = gender.ToUpper(); account.Day_Of_Birth = day; account.Month_Of_Birth = month; account.Year_Of_Birth = year; account.Channel_Cd = "SMS"; account.Created_By = System.Configuration.ConfigurationManager.AppSettings["CREATED_BY_SMS"]; account.Updated_By = System.Configuration.ConfigurationManager.AppSettings["CREATED_BY_SMS"]; account.First_Mobile_Number = mobile_no; account.Created_Dttm = timestamp; account.Updated_Dttm = timestamp; account.Registration_Dttm = timestamp; var today = DateTime.Now.Date; Quota q = db_transaction.Quotas.Where(x => x.Quota_Type_Cd.Equals("B")).Where(x => x.Quota_Cd.Equals("Q0001")).SingleOrDefault(); #region account quota used cur AccountQuotaUsedCur aquc = new AccountQuotaUsedCur(); aquc.Date = today.Date; aquc.Account = account; aquc.Quota_Freq_Used_Val = 0; aquc.Quota_Avail_Flag = true; aquc.Quota_Dur_Val = Convert.ToByte(q.Quota_Dur_Val); aquc.Quota_Freq_Val = Convert.ToByte(q.Quota_Freq_Val); db_transaction.AccountQuotaUsedCurs.Add(aquc); #endregion #region account mobile AccountMobile am = new AccountMobile(); am.Account = account; am.Mobile_Number = mobile_no; am.Primary_Flag = true; am.Status_Cd = "AC"; am.Updated_By = System.Configuration.ConfigurationManager.AppSettings["CREATED_BY_SMS"]; am.Created_By = System.Configuration.ConfigurationManager.AppSettings["CREATED_BY_SMS"]; db_transaction.AccountMobiles.Add(am); #endregion #region account interest AccountInterest ai = new AccountInterest(); ai.Account = account; db_transaction.AccountInterests.Add(ai); #endregion #region account quota AccountQuota aq = new AccountQuota(); aq.Account = account; aq.Quota_Cd = q.Quota_Cd; db_transaction.AccountQuotas.Add(aq); #endregion #region update account activation and set status_cd SqlParameter output = new SqlParameter("acstatus", SqlDbType.Int); output.Direction = ParameterDirection.Output; SqlParameter date = new SqlParameter("today", SqlDbType.Date); date.Value = DateTime.Now; SqlParameter no_acct_total = new SqlParameter("no_acct_limit_total", SqlDbType.Int); int no_acct_limit_total = 0; AdminConfiguration admin_config = db_transaction.AdminConfigurations.SingleOrDefault(); if (admin_config != null) { no_acct_limit_total = admin_config.No_Activation_Limit_Total; } no_acct_total.Value = no_acct_limit_total; string sql_string = "declare @tbt table (acstatus int)" + "UPDATE Account_Activation " + "SET No_Activation = CASE WHEN (No_Activation + 1 > No_Max_Activation or (No_Activation_Acc + 1 > @no_acct_limit_total)) THEN No_Activation ELSE No_Activation + 1 END, " + "No_Activation_Acc = CASE WHEN (No_Activation + 1 > No_Max_Activation or (No_Activation_Acc + 1 > @no_acct_limit_total)) THEN No_Activation_Acc ELSE No_Activation_Acc + 1 END, " + "No_Activation_Pending = CASE WHEN (No_Activation + 1 > No_Max_Activation or (No_Activation_Acc + 1 > @no_acct_limit_total)) THEN No_Activation_Pending + 1 ELSE No_Activation_Pending END, " + "Updated_By = 'WEBSITE', " + "Updated_Dttm = GETDATE() " + "OUTPUT CASE WHEN (deleted.No_Activation + 1 > deleted.No_Max_Activation or deleted.No_Activation_Acc + 1 > @no_acct_limit_total) THEN 1 ELSE 0 END " + " into @tbt " + "WHERE [Date] = @today " + "select @acstatus = acstatus from @tbt"; db_transaction.Database.ExecuteSqlCommand(sql_string, no_acct_total, date, output); int sql_result = Convert.ToInt16(output.Value); if (sql_result == 0) { account.Status_Cd = FreebieStatus.AccountActivated(); account.Activation_Dttm = timestamp; reply_str = System.Configuration.ConfigurationManager.AppSettings["ACD"]; sms_log_result = "Register success"; string q_str = (Convert.ToByte(q.Quota_Freq_Val) * Convert.ToByte(q.Quota_Dur_Val) * 30).ToString(); reply_str = reply_str.Replace("{count}", q.Quota_Freq_Val.ToString()); reply_str = reply_str.Replace("{mins}", q.Quota_Dur_Val.ToString()); reply_str = reply_str.Replace("{num}", q_str); } else { account.Status_Cd = FreebieStatus.AccountPending(); reply_str = System.Configuration.ConfigurationManager.AppSettings["AP"]; sms_log_result = "Register Pending"; } #endregion account.First_Quota_Cd = q.Quota_Cd; account.First_Quota_Dur_Val = q.Quota_Dur_Val; account.First_Quota_Freq_Val = q.Quota_Freq_Val; account.Dummy_Flag = "0"; db_transaction.Accounts.Add(account); db_transaction.SaveChanges(); scope.Complete(); } #endregion #region call_sp result_sp = CallSP.SP_Insert_Interact_Profile(account.Account_Id); if (!result_sp[0].Equals("0")) { using (var new_db = new EchoContext()) { SqlParameter date = new SqlParameter("today", SqlDbType.Date); date.Value = DateTime.Now; Account remove_ac = new_db.Accounts.SingleOrDefault(x => x.Account_Id == account.Account_Id); if (remove_ac != null) { if (remove_ac.Status_Cd.Equals(FreebieStatus.AccountActivated())) { string sql_string = "UPDATE Account_Activation " + "SET No_Activation = CASE WHEN (No_Activation - 1 < 0 ) THEN 0 ELSE No_Activation - 1 END, " + "No_Activation_Acc = CASE WHEN (No_Activation_Acc - 1 < 0 ) THEN 0 ELSE No_Activation_Acc - 1 END, " + "Updated_By = 'WEBSITE', " + "Updated_Dttm = GETDATE() " + "WHERE [Date] = @today "; new_db.Database.ExecuteSqlCommand(sql_string, date); } else { if (remove_ac.Status_Cd.Equals(FreebieStatus.AccountPending())) { string sql_string = "UPDATE Account_Activation " + "SET No_Activation_Pending = CASE WHEN (No_Activation_Pending - 1 < 0 ) THEN 0 ELSE No_Activation_Pending - 1 END, " + "Updated_By = 'WEBSITE', " + "Updated_Dttm = GETDATE() " + "WHERE [Date] = @today "; new_db.Database.ExecuteSqlCommand(sql_string, date); } } AccountQuotaUsedCur remove_aquc = new_db.AccountQuotaUsedCurs.SingleOrDefault(x => x.Account_Id == account.Account_Id); if (remove_aquc != null) { new_db.AccountQuotaUsedCurs.Remove(remove_aquc); } new_db.Accounts.Remove(remove_ac); new_db.SaveChanges(); } } reply_str = System.Configuration.ConfigurationManager.AppSettings["NO_ACCTACTIVATION"]; } else { FreebieEvent.AccountCreateEvent(account, account.First_Mobile_Number, Permission.f_cust_regis_page_id); } #endregion } else { reply_str = System.Configuration.ConfigurationManager.AppSettings["WRONG_FORMAT"]; sms_log_result = "Wrong input Format"; } } } catch (Exception err) { reply_str = System.Configuration.ConfigurationManager.AppSettings["NO_ACCTACTIVATION"]; sms_log_result = "System Error"; FreebieEvent.AddCustomError(err.Message, Permission.f_cust_regis_page_id); } Encoding encoding = Encoding.GetEncoding("tis-620"); string xml_str = GetReplyXML(reply_str, encoding); sms_log.Result = sms_log_result; db.SmsRegistrationLogs.Add(sms_log); db.SaveChanges(); context.Response.ContentType = "text/xml"; context.Response.ContentEncoding = encoding; context.Response.Write(xml_str); }
/// <summary> /// Добавить новую квоту /// </summary> public void AddNewQuota(Quota quota) { var connection = _context.Database.GetDbConnection() as SqlConnection; CreateNewQuota(quota, connection); //Add(quota) }
public int Add(Quota quota) { _tradingContext.Quote.Add(quota); return(_tradingContext.SaveChanges()); }
public void EditQuota(Quota quota) { MRQuotas.EditQuota(quota); }
public void AddQuota(Quota quota) { MRQuotas.AddQuota(quota); }
public void Remove(Quota quota) { _context.Quotas.Remove(quota); }
public void Add(Quota quota) { _context.Quotas.Add(quota); }
protected override void Seed(METU.VRS.Services.DatabaseContext context) { //UserRole UserRole authenticated_user = new UserRole() { UID = "authenticated_user", Description = "Authenticated User" }; UserRole approval_user = new UserRole() { UID = "approval_user", Description = "Approval User" }; UserRole delivery_user = new UserRole() { UID = "delivery_user", Description = "Delivery User" }; UserRole security_officer = new UserRole() { UID = "security_officer", Description = "Security Officer" }; UserRole admin = new UserRole() { UID = "admin", Description = "System Admin" }; context.UserRoles.AddOrUpdate(a => a.UID, new UserRole[] { authenticated_user, approval_user, delivery_user, security_officer, admin }); //UserCategory UserCategory student = new UserCategory() { UID = "student", Description = "Student" }; UserCategory academic = new UserCategory() { UID = "academic", Description = "Academic" }; UserCategory administrative = new UserCategory() { UID = "administrative", Description = "Administrative" }; UserCategory affiliate = new UserCategory() { UID = "affiliate", Description = "Affiliate" }; UserCategory alumni = new UserCategory() { UID = "alumni", Description = "Alumni" }; context.UserCategories.AddOrUpdate(a => a.UID, new UserCategory[] { student, academic, administrative, affiliate, alumni }); //BranchAffiliate BranchAffiliate II = new BranchAffiliate() { UID = "II", Name = "Graduate School of Informatics", Type = BranchAffiliateTypes.GraduateSchool }; BranchAffiliate MUH = new BranchAffiliate() { UID = "MUH", Name = "Faculty of Engineering", Type = BranchAffiliateTypes.Faculty }; BranchAffiliate FEAS = new BranchAffiliate() { UID = "FEAS", Name = "Faculty of Economic and Administrative Sciences", Type = BranchAffiliateTypes.Faculty }; BranchAffiliate IAM = new BranchAffiliate() { UID = "IAM", Name = "Graduate School of Applied Mathematics", Type = BranchAffiliateTypes.GraduateSchool }; BranchAffiliate IHM = new BranchAffiliate() { UID = "IHM", Name = "Office of Domestic Services", Type = BranchAffiliateTypes.AdministrativeUnit }; BranchAffiliate OIDB = new BranchAffiliate() { UID = "OIDB", Name = "Directorate of Student Affairs", Type = BranchAffiliateTypes.AdministrativeUnit }; BranchAffiliate ISBANK = new BranchAffiliate() { UID = "ISBANK", Name = "Türkiye İş Bankası", Type = BranchAffiliateTypes.Affiliate }; BranchAffiliate BURGERKING = new BranchAffiliate() { UID = "BURGERKING", Name = "BurgerKing", Type = BranchAffiliateTypes.Affiliate }; BranchAffiliate ASELSAN = new BranchAffiliate() { UID = "ASELSAN", Name = "ASELSAN", Type = BranchAffiliateTypes.Affiliate }; BranchAffiliate CATI = new BranchAffiliate() { UID = "CATI", Name = "Çatı Cafe", Type = BranchAffiliateTypes.Affiliate }; context.BranchsAffiliates.AddOrUpdate(a => a.UID, new BranchAffiliate[] { II, MUH, FEAS, IAM, IHM, OIDB, ISBANK, BURGERKING, ASELSAN, CATI }); //User User e100 = new User() { UID = "e100", Name = "Test Student1", Category = student, Division = II, Roles = new UserRole[] { authenticated_user } }; User e101 = new User() { UID = "e101", Name = "Test Student2", Category = student, Division = MUH, Roles = new UserRole[] { authenticated_user } }; User e102 = new User() { UID = "e102", Name = "Test Student3", Category = student, Division = FEAS, Roles = new UserRole[] { authenticated_user } }; User e103 = new User() { UID = "e103", Name = "Test Student4", Category = student, Division = IAM, Roles = new UserRole[] { authenticated_user } }; User e200 = new User() { UID = "e200", Name = "Test Student11", Category = student, Division = II, Roles = new UserRole[] { authenticated_user } }; User e201 = new User() { UID = "e201", Name = "Test Student12", Category = student, Division = MUH, Roles = new UserRole[] { authenticated_user } }; User e202 = new User() { UID = "e202", Name = "Test Student13", Category = student, Division = FEAS, Roles = new UserRole[] { authenticated_user } }; User e203 = new User() { UID = "e203", Name = "Test Student14", Category = student, Division = IAM, Roles = new UserRole[] { authenticated_user } }; User a100 = new User() { UID = "a100", Name = "Test Academic1", Category = academic, Division = II, Roles = new UserRole[] { authenticated_user } }; User a101 = new User() { UID = "a101", Name = "Test Academic2", Category = academic, Division = MUH, Roles = new UserRole[] { authenticated_user } }; User a102 = new User() { UID = "a102", Name = "Test Academic3", Category = academic, Division = FEAS, Roles = new UserRole[] { authenticated_user } }; User a103 = new User() { UID = "a103", Name = "Test Academic4", Category = academic, Division = IAM, Roles = new UserRole[] { authenticated_user } }; User o100 = new User() { UID = "o100", Name = "Test Officer1", Category = administrative, Division = OIDB, Roles = new UserRole[] { authenticated_user } }; User o101 = new User() { UID = "o101", Name = "Test Approval Officer", Category = administrative, Division = II, Roles = new UserRole[] { authenticated_user, approval_user } }; User o102 = new User() { UID = "o102", Name = "Test Delivery Officer", Category = administrative, Division = IHM, Roles = new UserRole[] { authenticated_user, delivery_user } }; User o103 = new User() { UID = "o103", Name = "Test Security Officer", Category = administrative, Division = IHM, Roles = new UserRole[] { authenticated_user, security_officer } }; User isbank = new User() { UID = "isbank", Name = "Test Affiliate1", Category = affiliate, Division = ISBANK, Roles = new UserRole[] { authenticated_user } }; User burgerking = new User() { UID = "burgerking", Name = "Test Affiliate2", Category = affiliate, Division = BURGERKING, Roles = new UserRole[] { authenticated_user } }; User aselsan = new User() { UID = "aselsan", Name = "Test Affiliate3", Category = affiliate, Division = ASELSAN, Roles = new UserRole[] { authenticated_user } }; User cati = new User() { UID = "cati", Name = "Test Affiliate4", Category = affiliate, Division = CATI, Roles = new UserRole[] { authenticated_user } }; context.Users.AddOrUpdate(a => a.UID, new User[] { e100, e101, e102, e103, e200, e201, e202, e203, a100, a101, a102, a103, o100, o101, o102, o103, isbank, burgerking, aselsan, cati }); //StickerTerm StickerTerm longterm = new StickerTerm() { Type = TermTypes.LongTerm, StartDate = new DateTime(2018, 1, 1), EndDate = new DateTime(2099, 1, 1) }; StickerTerm calenderyear2018 = new StickerTerm() { Type = TermTypes.CalendarYear, StartDate = new DateTime(2018, 1, 1), EndDate = new DateTime(2019, 1, 1) }; StickerTerm calenderyear2019 = new StickerTerm() { Type = TermTypes.CalendarYear, StartDate = new DateTime(2019, 1, 1), EndDate = new DateTime(2020, 1, 1) }; StickerTerm academicyear2017 = new StickerTerm() { Type = TermTypes.AcademicYear, StartDate = new DateTime(2017, 10, 1), EndDate = new DateTime(2018, 10, 1) }; StickerTerm academicyear2018 = new StickerTerm() { Type = TermTypes.AcademicYear, StartDate = new DateTime(2018, 10, 1), EndDate = new DateTime(2019, 10, 1) }; context.StickerTerms.AddOrUpdate(a => new { a.Type, a.StartDate, a.EndDate }, new StickerTerm[] { longterm, calenderyear2018, academicyear2018, calenderyear2019 }); //StickerType StickerType st1 = new StickerType() { Class = StickerClasses.Staff, Color = "Red", Description = "Academican Sticker", TermType = TermTypes.LongTerm, UserCategory = academic }; StickerType st2 = new StickerType() { Class = StickerClasses.Staff, Color = "Green", Description = "Administrative Attendant Sticker", TermType = TermTypes.LongTerm, UserCategory = administrative }; StickerType st3 = new StickerType() { Class = StickerClasses.Foundation, Color = "Black", Description = "METU Foundation Member Sticker", TermType = TermTypes.LongTerm, UserCategory = administrative }; StickerType st4 = new StickerType() { Class = StickerClasses.Visitor, Color = "Blue", Description = "Visitor Sticker", TermType = TermTypes.CalendarYear, UserCategory = administrative }; StickerType st5 = new StickerType() { Class = StickerClasses.Visitor, Color = "Blue", Description = "Campus Services Sticker", TermType = TermTypes.CalendarYear, UserCategory = affiliate }; StickerType st6 = new StickerType() { Class = StickerClasses.Visitor, Color = "Blue", Description = "Visiting Researcher Sticker", TermType = TermTypes.AcademicYear, UserCategory = academic }; StickerType st7 = new StickerType() { Class = StickerClasses.Visitor, Color = "Blue", Description = "Sport Club Trainer", TermType = TermTypes.CalendarYear, UserCategory = administrative }; StickerType st8 = new StickerType() { Class = StickerClasses.Visitor, Color = "Blue", Description = "Sport Club Member", TermType = TermTypes.CalendarYear, UserCategory = administrative }; StickerType st9 = new StickerType() { Class = StickerClasses.Visitor, Color = "Blue", Description = "Lodgement Sticker", TermType = TermTypes.CalendarYear, UserCategory = administrative }; StickerType st10 = new StickerType() { Class = StickerClasses.Alumni, Color = "Gray", Description = "Alumni Sticker", TermType = TermTypes.CalendarYear, UserCategory = alumni }; StickerType st11 = new StickerType() { Class = StickerClasses.Technopolis, Color = "Orange", Description = "Technopolis Sticker", TermType = TermTypes.CalendarYear, UserCategory = affiliate }; StickerType st12 = new StickerType() { Class = StickerClasses.Student, Color = "Yellow", Description = "Unlimited Student Sticker", TermType = TermTypes.AcademicYear, UserCategory = student }; StickerType st13 = new StickerType() { Class = StickerClasses.Student, Color = "Brown", Description = "Limited Student Sticker", TermType = TermTypes.AcademicYear, UserCategory = student }; StickerType st14 = new StickerType() { Class = StickerClasses.StudentParent, Color = "Purple", Description = "College Student Parent Sticker", TermType = TermTypes.AcademicYear, UserCategory = affiliate }; StickerType st15 = new StickerType() { Class = StickerClasses.StudentParent, Color = "Purple", Description = "Kindergarten Student Parent Sticker", TermType = TermTypes.AcademicYear, UserCategory = affiliate }; context.StickerTypes.AddOrUpdate(a => a.Description, new StickerType[] { st1, st2, st3, st4, st5, st6, st7, st8, st9, st10, st11, st12, st13, st14, st15 }); //Quota Quota q1 = new Quota() { UID = "q1", Term = longterm, Division = null, StickerFee = 40, TotalQuota = -1, Type = st1 }; Quota q2 = new Quota() { UID = "q2", Term = longterm, Division = null, StickerFee = 40, TotalQuota = -1, Type = st2 }; Quota q3 = new Quota() { UID = "q3", Term = longterm, Division = null, StickerFee = 60, TotalQuota = -1, Type = st3 }; Quota q4 = new Quota() { UID = "q4", Term = calenderyear2019, Division = null, StickerFee = 700, TotalQuota = 100, Type = st4 }; Quota q5 = new Quota() { UID = "q5", Term = calenderyear2019, Division = null, StickerFee = 60, TotalQuota = 100, Type = st5 }; Quota q6 = new Quota() { UID = "q6", Term = academicyear2018, Division = null, StickerFee = 60, TotalQuota = 100, Type = st6 }; Quota q7 = new Quota() { UID = "q7", Term = calenderyear2019, Division = null, StickerFee = 700, TotalQuota = 100, Type = st7 }; Quota q8 = new Quota() { UID = "q8", Term = calenderyear2019, Division = null, StickerFee = 60, TotalQuota = 100, Type = st8 }; Quota q9 = new Quota() { UID = "q9", Term = calenderyear2019, Division = null, StickerFee = 60, TotalQuota = 1000, Type = st9 }; Quota q10 = new Quota() { UID = "q10", Term = calenderyear2019, Division = null, StickerFee = 700, TotalQuota = -1, Type = st10 }; Quota q11 = new Quota() { UID = "q11", Term = calenderyear2019, Division = null, StickerFee = 600, TotalQuota = 5000, Type = st11 }; Quota q12 = new Quota() { UID = "q12", Term = academicyear2018, Division = II, StickerFee = 500, TotalQuota = 1, Type = st12 }; Quota q13 = new Quota() { UID = "q13", Term = academicyear2018, Division = II, StickerFee = 100, TotalQuota = 100, Type = st13 }; Quota q14 = new Quota() { UID = "q14", Term = academicyear2018, Division = null, StickerFee = 300, TotalQuota = 500, Type = st14 }; Quota q15 = new Quota() { UID = "q15", Term = academicyear2018, Division = null, StickerFee = 60, TotalQuota = 500, Type = st15 }; Quota q16 = new Quota() { UID = "q16", Term = academicyear2018, Division = FEAS, StickerFee = 500, TotalQuota = 1, Type = st12 }; Quota q17 = new Quota() { UID = "q17", Term = academicyear2018, Division = FEAS, StickerFee = 100, TotalQuota = 100, Type = st13 }; Quota q18 = new Quota() { UID = "q18", Term = academicyear2018, Division = IAM, StickerFee = 500, TotalQuota = 1, Type = st12 }; Quota q19 = new Quota() { UID = "q19", Term = academicyear2018, Division = IAM, StickerFee = 100, TotalQuota = 100, Type = st13 }; Quota q20 = new Quota() { UID = "q20", Term = academicyear2018, Division = MUH, StickerFee = 500, TotalQuota = 2, Type = st12 }; Quota q21 = new Quota() { UID = "q21", Term = academicyear2018, Division = MUH, StickerFee = 100, TotalQuota = 100, Type = st13 }; Quota q22 = new Quota() { UID = "q22", Term = academicyear2017, Division = IAM, StickerFee = 300, TotalQuota = 2, Type = st12 }; context.Quotas.AddOrUpdate(a => a.UID, new Quota[] { q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20, q21, q22 }); Vehicle ve100 = new Vehicle { OwnerName = e100.Name, PlateNumber = "06AA100", RegistrationNumber = "AA100000", Type = VehicleType.Car }; Vehicle ve200 = new Vehicle { OwnerName = e200.Name, PlateNumber = "06AA200", RegistrationNumber = "AA200000", Type = VehicleType.Car }; Vehicle ve101 = new Vehicle { OwnerName = e101.Name, PlateNumber = "06AA101", RegistrationNumber = "AA101000", Type = VehicleType.Car }; Vehicle ve201 = new Vehicle { OwnerName = e201.Name, PlateNumber = "06AA201", RegistrationNumber = "AA201000", Type = VehicleType.Car }; Vehicle ve102 = new Vehicle { OwnerName = e102.Name, PlateNumber = "06AA102", RegistrationNumber = "AA102000", Type = VehicleType.Car }; Vehicle ve202 = new Vehicle { OwnerName = e202.Name, PlateNumber = "06AA202", RegistrationNumber = "AA202000", Type = VehicleType.Car }; Vehicle ve103 = new Vehicle { OwnerName = e102.Name, PlateNumber = "06AA103", RegistrationNumber = "AA103000", Type = VehicleType.Car }; Vehicle ve203 = new Vehicle { OwnerName = e202.Name, PlateNumber = "06AA203", RegistrationNumber = "AA203000", Type = VehicleType.Car }; Vehicle vevisitor1 = new Vehicle { OwnerName = "Test Visitor1", PlateNumber = "06BB100", RegistrationNumber = "BB100000", Type = VehicleType.Car }; Vehicle vevisitor2 = new Vehicle { OwnerName = "Test Visitor2", PlateNumber = "06BB200", RegistrationNumber = "BB200000", Type = VehicleType.Van }; context.Vehicles.AddOrUpdate(v => v.ID, new Vehicle[] { ve100, ve200, ve101, ve201, ve102, ve202, ve103, ve203 }); context.Visitors.AddOrUpdate(v => v.UID, new Visitor[] { new Visitor { CreateDate = DateTime.Now, Description = "Testing Purpose", Email = "*****@*****.**", LastModified = DateTime.Now, Name = "John Doe", Status = VisitorStatus.WaitingForApproval, User = e101, Vehicle = vevisitor1, VisitDate = DateTime.Today, UID = "TEST1" }, new Visitor { CreateDate = DateTime.Now, Description = "Testing Purpose", Email = "*****@*****.**", LastModified = DateTime.Now, Name = "Jane Doe", Status = VisitorStatus.WaitingForArrival, User = e101, Vehicle = vevisitor2, VisitDate = DateTime.Today, UID = "TEST2", ApproveDate = DateTime.Now } }); context.StickerApplications.AddOrUpdate(a => a.ID, new StickerApplication[] { new StickerApplication() { User = e100, CreateDate = DateTime.Now, LastModified = DateTime.Now, Owner = new ApplicationOwner() { Name = e100.Name }, Quota = q12, Status = StickerApplicationStatus.WaitingForApproval, Vehicle = ve100 }, new StickerApplication() { User = e200, CreateDate = DateTime.Now, LastModified = DateTime.Now, Owner = new ApplicationOwner() { Name = e200.Name }, Quota = q12, Status = StickerApplicationStatus.WaitingForApproval, Vehicle = ve200 }, new StickerApplication() { User = e101, CreateDate = DateTime.Now, LastModified = DateTime.Now, ApproveDate = DateTime.Now, Owner = new ApplicationOwner() { Name = e101.Name }, Quota = q20, Status = StickerApplicationStatus.WaitingForPayment, Vehicle = ve101 }, new StickerApplication() { User = e201, CreateDate = DateTime.Now, LastModified = DateTime.Now, ApproveDate = DateTime.Now, Owner = new ApplicationOwner() { Name = e201.Name }, Quota = q20, Status = StickerApplicationStatus.WaitingForPayment, Vehicle = ve201 }, new StickerApplication() { User = e102, Payment = new Payment { Amount = q16.StickerFee, TransactionDate = DateTime.Now, TransactionNumber = "TEST1234" }, CreateDate = DateTime.Now, LastModified = DateTime.Now, ApproveDate = DateTime.Now, Owner = new ApplicationOwner() { Name = e102.Name }, Quota = q16, Status = StickerApplicationStatus.WaitingForDelivery, Vehicle = ve102 }, new StickerApplication() { User = e202, Payment = new Payment { Amount = q17.StickerFee, TransactionDate = DateTime.Now, TransactionNumber = "TEST5678" }, CreateDate = DateTime.Now, LastModified = DateTime.Now, ApproveDate = DateTime.Now, Owner = new ApplicationOwner() { Name = e202.Name }, Quota = q17, Status = StickerApplicationStatus.WaitingForDelivery, Vehicle = ve202 }, new StickerApplication() { User = e103, Payment = new Payment { Amount = q22.StickerFee, TransactionDate = DateTime.Now, TransactionNumber = "TEST1234" }, Sticker = new Sticker { SerialNumber = 12345 }, CreateDate = DateTime.Now, LastModified = DateTime.Now, ApproveDate = q22.Term.StartDate, DeliveryDate = q22.Term.StartDate, Owner = new ApplicationOwner() { Name = e103.Name }, Quota = q22, Status = StickerApplicationStatus.Active, Vehicle = ve103 }, new StickerApplication() { User = e203, Payment = new Payment { Amount = q22.StickerFee, TransactionDate = DateTime.Now, TransactionNumber = "TEST5678" }, Sticker = new Sticker { SerialNumber = 23456 }, CreateDate = DateTime.Now, LastModified = DateTime.Now, ApproveDate = q22.Term.StartDate, DeliveryDate = q22.Term.StartDate, Owner = new ApplicationOwner() { Name = e203.Name }, Quota = q22, Status = StickerApplicationStatus.Active, Vehicle = ve203 } }); }
public int Update(Quota quotaEsistente) { _tradingContext.Update(quotaEsistente); return(_tradingContext.SaveChanges()); }
public void Edit(Quota m) { context.Entry(m).State = System.Data.Entity.EntityState.Modified; }
/// <summary> /// Create or update a quota. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='resourceName'> /// Name of the resource. /// </param> /// <param name='quota'> /// New network quota to create. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <Quota> CreateOrUpdateAsync(this IQuotasOperations operations, string location, string resourceName, Quota quota, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(location, resourceName, quota, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
private License CreateTypicalSDKLicense() { License license = new License(); license.Created = LIC_CREATED; license.Status = LIC_STATUS; license.PaidUntil = LIC_PAIDUNTIL; Transaction transaction = new Transaction(); transaction.Created = LIC_TRANS_CREATED; CreditCard creditCard = new CreditCard(); creditCard.Cvv = LIC_TRANS_CC_CVV; creditCard.Type = LIC_TRANS_CC_TYPE; creditCard.Name = LIC_TRANS_CC_NAME; creditCard.Number = LIC_TRANS_CC_NUM; CcExpiration ccExpiration = new CcExpiration(); ccExpiration.Month = LIC_TRANS_CC_EXP_MONTH; ccExpiration.Year = LIC_TRANS_CC_EXP_YEAR; creditCard.Expiration = ccExpiration; transaction.CreditCard = creditCard; Price price = new Price(); price.Amount = LIC_TRANS_PRICE_AMOUNT; Currency currency = new Currency(); currency.Data = LIC_TRANS_PRICE_CURR_DATA; currency.Name = LIC_TRANS_PRICE_CURR_NAME; currency.Id = LIC_TRANS_PRICE_CURR_ID; price.Currency = currency; transaction.Price = price; license.AddTransaction(transaction); Plan plan = new Plan(); plan.Contract = LIC_PLAN_CONTRACT; plan.Group = LIC_PLAN_GRP; plan.Original = LIC_PLAN_ORI; plan.Description = LIC_PLAN_DES; plan.Data = LIC_PLAN_DATA; plan.Cycle = LIC_PLAN_CYC; plan.Id = LIC_PLAN_ID; plan.Features = LIC_PLAN_FEAT; plan.Name = LIC_PLAN_NAME; CycleCount cycleCount = new CycleCount(); cycleCount.Cycle = LIC_PLAN_CYC_CYCLE; cycleCount.Count = LIC_PLAN_CYC_COUNT; plan.FreeCycles = cycleCount; Quota quota = new Quota(); quota.Target = LIC_PLAN_QUOTA_TARGET; quota.Limit = LIC_PLAN_QUOTA_LIMIT; quota.Cycle = LIC_PLAN_QUOTA_CYCLE; quota.Scope = LIC_PLAN_QUOTA_SCOPE; plan.AddQuota(quota); Price price1 = new Price(); price1.Amount = LIC_PLAN_PRICE_AMOUNT; Currency currency1 = new Currency(); currency1.Id = LIC_PLAN_PRICE_CURR_ID; currency1.Name = LIC_PLAN_PRICE_CURR_NAME; currency1.Data = LIC_PLAN_PRICE_CURR_DATA; price1.Currency = currency1; plan.Price = price1; license.Plan = plan; return(license); }
static void UntaggedQuota (ImapEngine engine, ImapCommand ic, int index) { var format = string.Format (ImapEngine.GenericUntaggedResponseSyntaxErrorFormat, "QUOTA", "{0}"); var quotaRoot = ReadStringToken (engine, format, ic.CancellationToken); var ctx = (QuotaContext) ic.UserData; var quota = new Quota (); var token = engine.ReadToken (ic.CancellationToken); if (token.Type != ImapTokenType.OpenParen) throw ImapEngine.UnexpectedToken (format, token); while (token.Type != ImapTokenType.CloseParen) { uint used, limit; string resource; token = engine.ReadToken (ic.CancellationToken); if (token.Type != ImapTokenType.Atom) throw ImapEngine.UnexpectedToken (format, token); resource = (string) token.Value; token = engine.ReadToken (ic.CancellationToken); if (token.Type != ImapTokenType.Atom || !uint.TryParse ((string) token.Value, out used)) throw ImapEngine.UnexpectedToken (format, token); token = engine.ReadToken (ic.CancellationToken); if (token.Type != ImapTokenType.Atom || !uint.TryParse ((string) token.Value, out limit)) throw ImapEngine.UnexpectedToken (format, token); switch (resource.ToUpperInvariant ()) { case "MESSAGE": quota.CurrentMessageCount = used; quota.MessageLimit = limit; break; case "STORAGE": quota.CurrentStorageSize = used; quota.StorageLimit = limit; break; } token = engine.PeekToken (ic.CancellationToken); } // read the closing paren engine.ReadToken (ic.CancellationToken); ctx.Quotas[quotaRoot] = quota; }
public bool PermiteAdicionar(Quota quota, Usuario usuario) { return(quota.Data >= DateTime.Today && usuario.Perfis.Contains(Enumeradores.Perfil.AgendadorDeCargas)); }
/// <summary> /// Удалить квоту /// </summary> public void Remove(Quota quota) { _context.Remove(quota); _context.SaveChanges(); }
public void ConsultaPrevistoRealizadoRetornaOsValoresAgrupadosCorretamente() { //cria duas quotas, dois fornecedores. Os fornecedores tem agendamentos nas duas quotas. //Apenas uma das quotas de cada fornecedor está realizada. RemoveQueries.RemoverQuotasCadastradas(); Fornecedor fornecedor1 = DefaultObjects.ObtemFornecedorPadrao(); Fornecedor fornecedor2 = DefaultObjects.ObtemFornecedorPadrao(); var quota1 = new Quota(Enumeradores.MaterialDeCarga.Farelo, fornecedor1, "1000", DateTime.Today.AddDays(1), 100); var quota2 = new Quota(Enumeradores.MaterialDeCarga.Farelo, fornecedor1, "1000", DateTime.Today.AddDays(2), 200); var quota3 = new Quota(Enumeradores.MaterialDeCarga.Farelo, fornecedor2, "1000", DateTime.Today.AddDays(1), 150); var quota4 = new Quota(Enumeradores.MaterialDeCarga.Farelo, fornecedor2, "1000", DateTime.Today.AddDays(2), 250); DefaultPersistedObjects.PersistirQuota(quota1); DefaultPersistedObjects.PersistirQuota(quota2); DefaultPersistedObjects.PersistirQuota(quota3); DefaultPersistedObjects.PersistirQuota(quota4); AgendamentoDeCarregamento agendamento1 = quota1.InformarAgendamento(new AgendamentoDeCarregamentoCadastroVm { Placa = "IOQ3434", Peso = 30 }); AgendamentoDeCarregamento agendamento2 = quota4.InformarAgendamento(new AgendamentoDeCarregamentoCadastroVm { Placa = "IOQ3435", Peso = 250 }); DefaultPersistedObjects.PersistirQuota(quota1); DefaultPersistedObjects.PersistirQuota(quota4); quota1.RealizarAgendamento(agendamento1.Id); quota4.RealizarAgendamento(agendamento2.Id); DefaultPersistedObjects.PersistirQuota(quota1); DefaultPersistedObjects.PersistirQuota(quota4); var consultaQuotaRelatorio = ObjectFactory.GetInstance <IConsultaQuotaRelatorio>(); IList <QuotaPlanejadoRealizadoVm> quotas = consultaQuotaRelatorio.PlanejadoRealizado( new RelatorioAgendamentoFiltroVm { CodigoTerminal = "1000" }); Assert.AreEqual(2, quotas.Count); QuotaPlanejadoRealizadoVm planejadoRealizadoFornecedor1 = quotas .First(x => x.NomeDoFornecedor == fornecedor1.Codigo + " - " + fornecedor1.Nome); Assert.AreEqual(fornecedor1.Codigo + " - " + fornecedor1.Nome, planejadoRealizadoFornecedor1.NomeDoFornecedor); Assert.AreEqual("1000", planejadoRealizadoFornecedor1.CodigoTerminal); Assert.AreEqual(quota1.FluxoDeCarga.Descricao(), planejadoRealizadoFornecedor1.FluxoDeCarga); Assert.AreEqual(300, planejadoRealizadoFornecedor1.Quota); Assert.AreEqual(30, planejadoRealizadoFornecedor1.PesoRealizado); QuotaPlanejadoRealizadoVm planejadoRealizadoFornecedor2 = quotas .First(x => x.NomeDoFornecedor == fornecedor2.Codigo + " - " + fornecedor2.Nome); Assert.AreEqual(fornecedor2.Codigo + " - " + fornecedor2.Nome, planejadoRealizadoFornecedor2.NomeDoFornecedor); Assert.AreEqual("1000", planejadoRealizadoFornecedor2.CodigoTerminal); Assert.AreEqual(quota1.FluxoDeCarga.Descricao(), planejadoRealizadoFornecedor2.FluxoDeCarga); Assert.AreEqual(400, planejadoRealizadoFornecedor2.Quota); Assert.AreEqual(250, planejadoRealizadoFornecedor2.PesoRealizado); }
/// <summary> /// Creates or Updates a Compute Quota. /// </summary> /// <remarks> /// Creates or Updates a Compute Quota with the provided quota parameters. /// </remarks> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='quotaName'> /// Name of the quota. /// </param> /// <param name='newQuota'> /// New quota to create. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <Quota> > CreateOrUpdateWithHttpMessagesAsync(string location, string quotaName, Quota newQuota, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (quotaName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "quotaName"); } if (newQuota == null) { throw new ValidationException(ValidationRules.CannotBeNull, "newQuota"); } if (newQuota != null) { newQuota.Validate(); } string apiVersion = "2018-02-09"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("quotaName", quotaName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("newQuota", newQuota); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute.Admin/locations/{location}/quotas/{quotaName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{quotaName}", System.Uri.EscapeDataString(quotaName)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (newQuota != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(newQuota, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <Quota>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Quota>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void Salvar(DateTime data, IList <QuotaSalvarVm> quotasSalvarVm) { try { _unitOfWork.BeginTransaction(); //consulta as quotas que estão salvas na data IList <Quota> quotasSalvas = _quotas.FiltraPorData(data).List(); #region Remover Quotas IList <Quota> quotasParaRemover = quotasSalvas .Where(qs => quotasSalvarVm.All(qc => qc.Data != qs.Data || qc.CodigoTerminal != qs.CodigoTerminal || qc.CodigoMaterial != (int)qs.Material || qc.CodigoFornecedor != qs.Fornecedor.Codigo)).ToList(); foreach (var quota in quotasParaRemover) { if (quota.Agendamentos.Any()) { throw new ExcluirQuotaComAgendamentoException(quota.Fornecedor.Nome); } _quotas.Delete(quota); } #endregion #region Atualizar Quotas IList <Quota> quotasParaAtualizar = quotasSalvas .Where(qs => quotasSalvarVm.Any(qc => qc.Data == qs.Data && qc.CodigoTerminal == qs.CodigoTerminal && qc.CodigoMaterial == (int)qs.Material && qc.CodigoFornecedor == qs.Fornecedor.Codigo)).ToList(); foreach (var quota in quotasParaAtualizar) { //obtem view model corresponde a entidade que quero atualizar QuotaSalvarVm quotaSalvarVm = quotasSalvarVm.First(qa => qa.Data == quota.Data && qa.CodigoTerminal == quota.CodigoTerminal && qa.CodigoMaterial == (int)quota.Material && qa.CodigoFornecedor == quota.Fornecedor.Codigo); //único campo que pode ser atualizado é o campo de peso quota.AlterarPeso(quotaSalvarVm.Peso); _quotas.Save(quota); } #endregion #region Adicionar Quotas IList <QuotaSalvarVm> quotasParaAdicionar = quotasSalvarVm.Where(qc => quotasSalvas.All(qs => qc.Data != qs.Data || qc.CodigoTerminal != qs.CodigoTerminal || qc.CodigoMaterial != (int)qs.Material || qc.CodigoFornecedor != qs.Fornecedor.Codigo)).ToList(); foreach (var quotaSalvarVm in quotasParaAdicionar) { string[] codigoDosNovosFornecedores = quotasParaAdicionar.Select(x => x.CodigoFornecedor).Distinct().ToArray(); IList <Fornecedor> fornecedores = _fornecedores.BuscaListaPorCodigo(codigoDosNovosFornecedores).List(); var materialDeCarga = (Enumeradores.MaterialDeCarga) Enum.Parse(typeof(Enumeradores.MaterialDeCarga), Convert.ToString(quotaSalvarVm.CodigoMaterial)); Fornecedor fornecedor = fornecedores.First(x => x.Codigo == quotaSalvarVm.CodigoFornecedor); var quota = new Quota(materialDeCarga, fornecedor, quotaSalvarVm.CodigoTerminal, quotaSalvarVm.Data, quotaSalvarVm.Peso); _quotas.Save(quota); } #endregion _unitOfWork.Commit(); } catch (Exception) { _unitOfWork.RollBack(); throw; } }
public AgendamentoDeCarga Construir(Quota quota, string placa) { return(new AgendamentoDeCarregamento(quota, placa, _peso)); }
public void GetStockTest() { // 尾部 00 和 '"' 之间不确定地会出现一个 ',' 需要正则兼容 string response = @"var hq_str_sh600086=""东方金钰,4.380,4.510,4.490,4.570,4.320,4.480,4.490,49796325,220884386.000,210200,4.480,665700,4.470,203900,4.460,346700,4.450,400100,4.440,8700,4.490,48900,4.500,99619,4.510,41400,4.520,67300,4.530,2019-06-27,11:30:00,00,"";"; var match = SinaStockSpider.SHSZ_QuotaRegex.Match(response); Assert.IsTrue(match.Success); Quota quota = SinaStockSpider.ConvertToSHSZQuota(match); Assert.AreEqual("东方金钰", quota.Name); Assert.AreEqual(4.380, quota.OpeningPriceToday); Assert.AreEqual(4.510, quota.ClosingPriceYesterday); Assert.AreEqual(4.490, quota.CurrentPrice); Assert.AreEqual(4.570, quota.DayHighPrice); Assert.AreEqual(4.320, quota.DayLowPrice); Assert.AreEqual(4.480, quota.BiddingPrice); Assert.AreEqual(4.490, quota.AuctionPrice); Assert.AreEqual(49796325, quota.Count); Assert.AreEqual(220884386.000, quota.Amount); Assert.AreEqual(210200, quota.BuyStrand1); Assert.AreEqual(665700, quota.BuyStrand2); Assert.AreEqual(203900, quota.BuyStrand3); Assert.AreEqual(346700, quota.BuyStrand4); Assert.AreEqual(400100, quota.BuyStrand5); Assert.AreEqual(4.480, quota.BuyPrice1); Assert.AreEqual(4.470, quota.BuyPrice2); Assert.AreEqual(4.460, quota.BuyPrice3); Assert.AreEqual(4.450, quota.BuyPrice4); Assert.AreEqual(4.440, quota.BuyPrice5); Assert.AreEqual(8700, quota.SellStrand1); Assert.AreEqual(48900, quota.SellStrand2); Assert.AreEqual(99619, quota.SellStrand3); Assert.AreEqual(41400, quota.SellStrand4); Assert.AreEqual(67300, quota.SellStrand5); Assert.AreEqual(4.490, quota.SellPrice1); Assert.AreEqual(4.500, quota.SellPrice2); Assert.AreEqual(4.510, quota.SellPrice3); Assert.AreEqual(4.520, quota.SellPrice4); Assert.AreEqual(4.530, quota.SellPrice5); Assert.AreEqual(new DateTime(2019, 6, 27, 11, 30, 00), quota.UpdateTime); response = @"var hq_str_hk01072=""DONGFANG ELEC,东方电气,4.790,4.800,4.970,4.770,4.930,-0.130,-2.708,4.920,4.930,4971969,1017200,11.682,0.000,7.700,3.810,2019/07/12,16:08"";"; match = SinaStockSpider.HK_QuotaRegex.Match(response); Assert.IsTrue(match.Success); quota = SinaStockSpider.ConvertToHKQuota(match); Assert.AreEqual("东方电气", quota.Name); Assert.AreEqual(4.790, quota.OpeningPriceToday); Assert.AreEqual(4.800, quota.ClosingPriceYesterday); Assert.AreEqual(4.970, quota.DayHighPrice); Assert.AreEqual(4.770, quota.DayLowPrice); Assert.AreEqual(4.930, quota.CurrentPrice); Assert.AreEqual(4971969, quota.Amount); Assert.AreEqual(1017200, quota.Count); Assert.AreEqual(new DateTime(2019, 07, 12, 16, 08, 0), quota.UpdateTime); }
private Account CreateTypicalSDKAccount() { Account account = new Account(); account.Name = ACC_NAME; account.Id = ACC_ID; account.Owner = ACC_OWNER; account.LogoUrl = ACC_LOGOURL; account.Data = ACC_DATA; account.Created = ACC_CREATED; account.Updated = ACC_UPDATED; Company company = new Company(); company.Id = ACC_CO_ID; company.Name = ACC_CO_NAME; company.Data = ACC_CO_DATA; Address address = new Address(); address.Address1 = ACC_CO_ADDR_ADDR1; address.Address2 = ACC_CO_ADDR_ADDR2; address.City = ACC_CO_ADDR_CITY; address.Country = ACC_CO_ADDR_COUNTRY; address.State = ACC_CO_ADDR_STATE; address.ZipCode = ACC_CO_ADDR_ZIP; company.Address = address; account.Company = company; CustomField customField = new CustomField(); customField.Id = ACC_FIELD_ID; customField.Required = ACC_FIELD_IS_REQUIRED; customField.Value = ACC_FIELD_DEF_VLE; Translation translation = new Translation(); translation.Language = ACC_FIELD_TRANSL_LANG; customField.AddTranslations(new List <Translation> { translation }); account.AddCustomField(customField); License license = new License(); license.Created = ACC_LIC_CREATED; license.Status = ACC_LIC_STATUS; license.PaidUntil = ACC_LIC_PAIDUNTIL; Transaction transaction = new Transaction(); transaction.Created = ACC_LIC_TRANS_CREATED; CreditCard creditCard = new CreditCard(); creditCard.Cvv = ACC_LIC_TRANS_CC_CVV; creditCard.Type = ACC_LIC_TRANS_CC_TYPE; creditCard.Name = ACC_LIC_TRANS_CC_NAME; creditCard.Number = ACC_LIC_TRANS_CC_NUM; CcExpiration ccExpiration = new CcExpiration(); ccExpiration.Month = ACC_LIC_TRANS_CC_EXP_MONTH; ccExpiration.Year = ACC_LIC_TRANS_CC_EXP_YEAR; creditCard.Expiration = ccExpiration; transaction.CreditCard = creditCard; Price price = new Price(); price.Amount = ACC_LIC_TRANS_PRICE_AMOUNT; Currency currency = new Currency(); currency.Data = ACC_LIC_TRANS_PRICE_CURR_DATA; currency.Name = ACC_LIC_TRANS_PRICE_CURR_NAME; currency.Id = ACC_LIC_TRANS_PRICE_CURR_ID; price.Currency = currency; transaction.Price = price; license.AddTransaction(transaction); Plan plan = new Plan(); plan.Contract = ACC_LIC_PLAN_CONTRACT; plan.Group = ACC_LIC_PLAN_GRP; plan.Original = ACC_LIC_PLAN_ORI; plan.Description = ACC_LIC_PLAN_DES; plan.Data = ACC_LIC_PLAN_DATA; plan.Cycle = ACC_LIC_PLAN_CYC; plan.Id = ACC_LIC_PLAN_ID; plan.Features = ACC_LIC_PLAN_FEAT; plan.Name = ACC_LIC_PLAN_NAME; CycleCount cycleCount = new CycleCount(); cycleCount.Cycle = ACC_LIC_PLAN_CYC_CYCLE; cycleCount.Count = ACC_LIC_PLAN_CYC_COUNT; plan.FreeCycles = cycleCount; Quota quota = new Quota(); quota.Target = ACC_LIC_PLAN_QUOTA_TARGET; quota.Limit = ACC_LIC_PLAN_QUOTA_LIMIT; quota.Cycle = ACC_LIC_PLAN_QUOTA_CYCLE; quota.Scope = ACC_LIC_PLAN_QUOTA_SCOPE; plan.AddQuota(quota); Price price1 = new Price(); price1.Amount = ACC_LIC_PLAN_PRICE_AMOUNT; Currency currency1 = new Currency(); currency1.Id = ACC_LIC_PLAN_PRICE_CURR_ID; currency1.Name = ACC_LIC_PLAN_PRICE_CURR_NAME; currency1.Data = ACC_LIC_PLAN_PRICE_CURR_DATA; price1.Currency = currency1; plan.Price = price1; license.Plan = plan; account.AddLicense(license); AccountProviders accountProviders = new AccountProviders(); Provider provider = new Provider(); provider.Id = ACC_PROV_DOC_ID; provider.Name = ACC_PROV_DOC_NAME; provider.Data = ACC_PROV_DOC_DATA; provider.Provides = ACC_PROV_DOC_PROVIDES; accountProviders.AddDocument(provider); Provider provider1 = new Provider(); provider1.Id = ACC_PROV_USR_ID; provider1.Name = ACC_PROV_USR_NAME; provider1.Data = ACC_PROV_USR_DATA; provider1.Provides = ACC_PROV_USR_PROVIDES; accountProviders.AddUser(provider1); account.Providers = accountProviders; return(account); }
public ActionResult ViewAccProfile() { int account_id = Convert.ToInt32(Session["Account_Id"].ToString()); var account = db.Accounts.SingleOrDefault(x => x.Account_Id == account_id); if (account == null) { return(HttpNotFound()); } var account_interest = db.AccountInterests.Where(x => x.Account_Id.Equals(account.Account_Id)).SingleOrDefault(); if (account_interest == null) { account_interest = new AccountInterest(); } List <string> interest_arrs = load_interest(account_interest); ViewBag.InterestSelected = interest_arrs; AccountQuota account_quota = db.AccountQuotas.SingleOrDefault(x => x.Account_Id == account_id); Quota quota = new Quota(); if (account_quota == null) { account_quota = new AccountQuota(); } else { quota = account_quota.Quota; } string district = ""; if (!string.IsNullOrWhiteSpace(account.AreaCode)) { Zipcode zipcode = db.Zipcodes.SingleOrDefault(x => x.AreaCode.Equals(account.AreaCode)); if (zipcode != null) { district = zipcode.District; } } ViewBag.Quota_Freq_Val = Convert.ToInt16(quota.Quota_Freq_Val); ViewBag.Quota_Dur_Val = Convert.ToInt16(quota.Quota_Dur_Val); if (quota.Quota_Cd != null) { if (quota.Quota_Cd.Equals("Q0001")) { ViewBag.Score = 3; } else { if (quota.Quota_Cd.Equals("Q0002")) { ViewBag.Score = 6; } else { if (quota.Quota_Cd.Equals("Q0003")) { ViewBag.Score = 8; } else { ViewBag.Score = 0; } } } } ViewBag.District = district; Hashtable quotas = new Hashtable(); quotas["low"] = new Hashtable(); quotas["medium"] = new Hashtable(); quotas["high"] = new Hashtable(); IEnumerable <Quota> base_quotas = db.Quotas.Where(x => x.Quota_Type_Cd.Equals("B")).OrderBy(x => x.Quota_Cd); int q_count = 1; foreach (var q in base_quotas) { switch (q_count) { case 1: quotas["low"] = q; break; case 2: quotas["medium"] = q; break; case 3: quotas["high"] = q; break; default: break; } q_count += 1; } ViewBag.Quotas = quotas; init_dropdown(account); ViewBag.ViewProfile = "true"; return(View(account)); }
/// <summary> /// Create a new Quota object. /// </summary> /// <param name="quotaID">Initial value of QuotaID.</param> public static Quota CreateQuota(int quotaID) { Quota quota = new Quota(); quota.QuotaID = quotaID; return quota; }
public ActionResult UpdateAccProfile() { int account_id = Convert.ToInt32(Session["Account_Id"].ToString()); var account = db.Accounts.SingleOrDefault(x => x.Account_Id == account_id); if (account == null) { return(HttpNotFound()); } var account_interest = db.AccountInterests.Where(x => x.Account_Id.Equals(account.Account_Id)).SingleOrDefault(); if (account_interest == null) { account_interest = new AccountInterest(); } AccountQuota account_quota = db.AccountQuotas.SingleOrDefault(x => x.Account_Id == account_id); Quota quota = new Quota(); if (account_quota == null) { account_quota = new AccountQuota(); } else { quota = account_quota.Quota; } ViewBag.Quota_Freq_Val = Convert.ToInt16(quota.Quota_Freq_Val); ViewBag.Quota_Dur_Val = Convert.ToInt16(quota.Quota_Dur_Val); Hashtable quotas = new Hashtable(); quotas["low"] = new Hashtable(); quotas["medium"] = new Hashtable(); quotas["high"] = new Hashtable(); IEnumerable <Quota> base_quotas = db.Quotas.Where(x => x.Quota_Type_Cd.Equals("B")).OrderBy(x => x.Quota_Cd); int q_count = 1; foreach (var q in base_quotas) { switch (q_count) { case 1: quotas["low"] = q; break; case 2: quotas["medium"] = q; break; case 3: quotas["high"] = q; break; default: break; } q_count += 1; } ViewBag.Quotas = quotas; List <string> interest_arrs = load_interest(account_interest); ViewBag.InterestSelected = interest_arrs; init_dropdown(account); ViewBag.ViewProfile = "true"; return(View(account)); }
public void Add(Quota m) { context.Quotas.Add(m); context.SaveChanges(); }
public ActionResult UpdateAccProfile(Account account) { var selected_interests = Request.Form["selectedInterests"]; var agree_flag = Request.Form["Agree"]; ViewBag.NotAgree = ""; ViewBag.ViewProfile = "true"; int account_id = Convert.ToInt32(Session["Account_Id"].ToString()); account = db.Accounts.SingleOrDefault(x => x.Account_Id == account_id); AccountQuota account_quota = db.AccountQuotas.SingleOrDefault(x => x.Account_Id == account_id); Quota quota = new Quota(); if (account_quota == null) { account_quota = new AccountQuota(); } else { quota = account_quota.Quota; } ViewBag.Quota_Freq_Val = Convert.ToInt16(quota.Quota_Freq_Val); ViewBag.Quota_Dur_Val = Convert.ToInt16(quota.Quota_Dur_Val); Hashtable quotas = new Hashtable(); quotas["low"] = new Hashtable(); quotas["medium"] = new Hashtable(); quotas["high"] = new Hashtable(); IEnumerable <Quota> base_quotas = db.Quotas.Where(x => x.Quota_Type_Cd.Equals("B")).OrderBy(x => x.Quota_Cd); int q_count = 1; foreach (var q in base_quotas) { switch (q_count) { case 1: quotas["low"] = q; break; case 2: quotas["medium"] = q; break; case 3: quotas["high"] = q; break; default: break; } q_count += 1; } ViewBag.Quotas = quotas; string old_idcard = account.Identification_Number == null ? string.Empty : account.Identification_Number.Trim(); //Account old_account = account; if (account == null) { return(HttpNotFound()); } if (ModelState.ContainsKey("User_Name")) { ModelState["User_Name"].Errors.Clear(); } if (ModelState.ContainsKey("User_Name")) { ModelState["Password"].Errors.Clear(); } var form_vals = Request.Form; if (string.IsNullOrWhiteSpace(form_vals["First_Name"])) { ModelState.AddModelError("First_Name", System.Configuration.ConfigurationManager.AppSettings["Account003"]); } if (string.IsNullOrWhiteSpace(form_vals["Last_Name"])) { ModelState.AddModelError("Last_Name", System.Configuration.ConfigurationManager.AppSettings["Account004"]); } if (string.IsNullOrWhiteSpace(form_vals["Income_Range_Cd"])) { ModelState.AddModelError("Income_Range_Cd", System.Configuration.ConfigurationManager.AppSettings["Account025"]); } if (CustomValidate.ValidateZipcode(form_vals["ZipCode"]) != 1) { ModelState.AddModelError("ZipCode", System.Configuration.ConfigurationManager.AppSettings["Account023"]); } account.First_Name = form_vals["First_Name"]; account.Last_Name = form_vals["Last_Name"]; if (string.IsNullOrEmpty(form_vals["Day_Of_Birth"])) { account.Day_Of_Birth = null; } else { account.Day_Of_Birth = Convert.ToByte(form_vals["Day_Of_Birth"]); } if (string.IsNullOrEmpty(form_vals["Month_Of_Birth"])) { account.Month_Of_Birth = null; } else { account.Month_Of_Birth = Convert.ToByte(form_vals["Month_Of_Birth"]); } if (string.IsNullOrEmpty(form_vals["Year_Of_Birth"])) { account.Year_Of_Birth = null; } else { account.Year_Of_Birth = Convert.ToInt16(form_vals["Year_Of_Birth"]); } account.Gender_Cd = form_vals["Gender_Cd"]; account.Marital_Status_Cd = form_vals["Marital_Status_Cd"]; bool no_child = true; if (!string.IsNullOrEmpty(form_vals["Children_Flag"])) { if (form_vals["Children_Flag"].Equals("Y")) { account.Children_Flag = "Y"; no_child = false; } else { account.Children_Flag = "N"; } } if (no_child || string.IsNullOrEmpty(form_vals["Year_Of_Birth_Child1"])) { account.Year_Of_Birth_Child1 = null; } else { account.Year_Of_Birth_Child1 = Convert.ToInt16(form_vals["Year_Of_Birth_Child1"]); } if (no_child || string.IsNullOrEmpty(form_vals["Year_Of_Birth_Child2"])) { account.Year_Of_Birth_Child2 = null; } else { account.Year_Of_Birth_Child2 = Convert.ToInt16(form_vals["Year_Of_Birth_Child2"]); } if (no_child || string.IsNullOrEmpty(form_vals["Year_Of_Birth_Child3"])) { account.Year_Of_Birth_Child3 = null; } else { account.Year_Of_Birth_Child3 = Convert.ToInt16(form_vals["Year_Of_Birth_Child3"]); } account.Income_Range_Cd = form_vals["Income_Range_Cd"]; account.Occupation_Cd = form_vals["Occupation_Cd"]; account.Education_Cd = form_vals["Education_Cd"]; account.Identification_Number = form_vals["Identification_Number"]; string idcard = form_vals["Identification_Number"] == null ? string.Empty : form_vals["Identification_Number"].Trim(); if (!string.IsNullOrEmpty(idcard)) { switch (CustomValidate.ValidateIndentification(idcard)) { case 0: ModelState.AddModelError("Identification_Number", System.Configuration.ConfigurationManager.AppSettings["Account007"]); break; case 2: ModelState.AddModelError("Identification_Number", System.Configuration.ConfigurationManager.AppSettings["Account007"]); break; case 3: ModelState.AddModelError("Identification_Number", System.Configuration.ConfigurationManager.AppSettings["Account008"]); break; default: break; } } if (!string.IsNullOrEmpty(account.Children_Flag)) { if (account.Children_Flag.Equals("Y")) { if (account.Year_Of_Birth_Child1 == null) { ModelState.AddModelError("Year_Of_Birth_Child1", System.Configuration.ConfigurationManager.AppSettings["Account021"]); } } } if (account.Day_Of_Birth == null || account.Month_Of_Birth == null || account.Year_Of_Birth == null) { ModelState.AddModelError("Day_Of_Birth", System.Configuration.ConfigurationManager.AppSettings["Account020"]); } if (account.Month_Of_Birth == 2) { if (account.Day_Of_Birth > 29) { ModelState.AddModelError("Day_Of_Birth", System.Configuration.ConfigurationManager.AppSettings["Account019"]); } else { if (!(account.Year_Of_Birth % 400 == 0 || (account.Year_Of_Birth % 100 != 0 && account.Year_Of_Birth % 4 == 0))) { if (account.Day_Of_Birth == 29) { ModelState.AddModelError("Day_Of_Birth", System.Configuration.ConfigurationManager.AppSettings["Account019"]); } } } } if (agree_flag == "true") { try { if (ModelState.IsValid) { account.Updated_Dttm = DateTime.Now; UpdateModel(account); string[] interests = new string[] { }; var aci = db.AccountInterests.Where(x => x.Account_Id.Equals(account.Account_Id)).SingleOrDefault(); bool flag = false; if (aci == null) { aci = new AccountInterest(); aci.Account_Id = account.Account_Id; flag = true; } if (selected_interests != null) { interests = selected_interests.Split(','); } aci.I01_Food_Dining = interests.Contains("I01"); aci.I02_Night_Life = interests.Contains("I02"); aci.I03_Entertainment = interests.Contains("I03"); aci.I04_Music_Movie = interests.Contains("I04"); aci.I05_Sports_Fitness = interests.Contains("I05"); aci.I06_Shopping_Fashion = interests.Contains("I06"); aci.I07_Health_Beauty = interests.Contains("I07"); aci.I08_Travel = interests.Contains("I08"); aci.I09_Pets = interests.Contains("I09"); aci.I10_Kids_Children = interests.Contains("I10"); aci.I11_Home_Living = interests.Contains("I11"); aci.I12_Finance_Investment = interests.Contains("I12"); aci.I13_Technology_Gadget = interests.Contains("I13"); aci.I14_Auto = interests.Contains("I14"); if (flag) { db.AccountInterests.Add(aci); } else { db.Entry(aci).State = EntityState.Modified; } Quota select_quota = QuotaCalculation.Calculate(account, selected_interests); AccountQuota aq = db.AccountQuotas.SingleOrDefault(x => x.Account_Id.Equals(account_id)); if (aq != null) { db.AccountQuotas.Remove(aq); db.SaveChanges(); } AccountQuota new_aq = new AccountQuota(); new_aq.Account_Id = account_id; new_aq.Quota_Cd = select_quota.Quota_Cd; db.AccountQuotas.Add(new_aq); db.SaveChanges(); if (!old_idcard.Equals(idcard)) { FreebieEvent.AccountUpdateEvent(account, idcard, "Idcard", Permission.f_update_profile_page_id); } else { FreebieEvent.AccountUpdateEvent(account, null, null, Permission.f_update_profile_page_id); } return(RedirectToAction("ViewAccProfile")); } } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } else { ViewBag.NotAgree = System.Configuration.ConfigurationManager.AppSettings["Account006"]; } var account_interest = db.AccountInterests.Where(x => x.Account_Id.Equals(account.Account_Id)).SingleOrDefault(); if (account_interest == null) { account_interest = new AccountInterest(); } List <string> interest_arrs = load_interest(account_interest); ViewBag.InterestSelected = interest_arrs; init_dropdown(account); ViewBag.Step = 3; return(View(account)); }
/// <summary> /// Create or update a quota. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='resourceName'> /// Name of the resource. /// </param> /// <param name='quota'> /// New network quota to create. /// </param> public static Quota CreateOrUpdate(this IQuotasOperations operations, string location, string resourceName, Quota quota) { return(operations.CreateOrUpdateAsync(location, resourceName, quota).GetAwaiter().GetResult()); }
public void QuandoCriuoUmaQuotaDeFareloOFluxoECarregamento() { var quota = new Quota(Enumeradores.MaterialDeCarga.Farelo, DefaultObjects.ObtemFornecedorPadrao(), "1000", DateTime.Today, 1000); Assert.AreEqual(Enumeradores.FluxoDeCarga.Carregamento, quota.FluxoDeCarga); }
/// <summary> /// Returns a list of quotas from the server. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server from which to /// get the quotas. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response structure for the Quota List operation. /// </returns> public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Sql.Models.QuotaListResponse> ListAsync(string serverName, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serverName", serverName); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/serverquotas"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result QuotaListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new QuotaListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure")); if (serviceResourcesSequenceElement != null) { foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"))) { Quota serviceResourceInstance = new Quota(); result.Quotas.Add(serviceResourceInstance); XElement valueElement = serviceResourcesElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")); if (valueElement != null) { string valueInstance = valueElement.Value; serviceResourceInstance.Value = valueInstance; } XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; serviceResourceInstance.Name = nameInstance; } XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; serviceResourceInstance.Type = typeInstance; } XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; serviceResourceInstance.State = stateInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public static AgendamentoDeCarregamento ObtemAgendamentoDeCarregamentoComPesoEspecifico(Quota quota, decimal peso) { var factory = new AgendamentoDeCarregamentoFactory(peso); return((AgendamentoDeCarregamento)factory.Construir(quota, "IOQ5338")); }