public SecretController() { IValidationDictionary validationDictionary = new ModelStateWrapper(ModelState); _secretService = new SecretService(validationDictionary); _sshSecretService = new SshSecretService(validationDictionary, true); _ctx = new CurrentContext(); }
public HomeController() { var dictionary = new ModelStateWrapper(ModelState); _facade = new UserFacade(dictionary); _profileService = new ProfileService(dictionary); _ctx = new CurrentContext(); }
public ServiceController() { IValidationDictionary validationDictionary = new ModelStateWrapper(ModelState); _service = new ServiceService(validationDictionary); _clientInServicesService = new ClientInServicesService(validationDictionary); _ctx = new CurrentContext(); }
public async Task<UserExchangeResult> GetUsers(UserExchangeRequest request, CurrentContext currentContext, HttpRequestMessage httpRequest) { var result = await Task.FromResult<UserExchangeResult>( repository.GetUsers(request, currentContext, httpRequest)); return result; }
public ActionResult PrintOrder(Guid id) { var ctx = new CurrentContext(); var user = ctx.GetUser(id); var orderTemplate = _customResorces.GetResource("Order_View"); orderTemplate.Value = AppendUserData(user, orderTemplate); return View(orderTemplate); }
public LocationProvider( CurrentContext currentContext, IGeocodingManager geocodingManager, ILocationServicesManager locationServicesManager) { _currentContext = currentContext; _geocodingManager = geocodingManager; _locationServicesManager = locationServicesManager; }
public UserController() { _ctx = new CurrentContext(); validationDictionary = new ModelStateWrapper(ModelState); _facade = new UserFacade(validationDictionary); _sshSecretService = new SshSecretService(validationDictionary, true); _statusService = new StatusService(validationDictionary); _profileService = new ProfileService(validationDictionary); }
public ActionResult Index() { var ctx = new CurrentContext(); var model = new SettingsViewModel { BuildVersion = AssemblyVersion.Version, ServerName = ctx.GetCurrentHost() != null ? ctx.GetCurrentHost().Address : "" }; return View(model); }
public Search( ILocationProvider locationProvider, ISearchingManager searchingManager, CurrentContext currentContext, INavigationService navigationService, MainPageViewModel mainPageViewModel) { _locationProvider = locationProvider; _searchingManager = searchingManager; _currentContext = currentContext; _navigationService = navigationService; _mainPageViewModel = mainPageViewModel; }
public PushSharpPushService( IDeviceRepository deviceRepository, ILogger<IPushService> logger, CurrentContext currentContext, IHostingEnvironment hostingEnvironment, GlobalSettings globalSettings) { _deviceRepository = deviceRepository; _logger = logger; _currentContext = currentContext; InitGcmBroker(globalSettings); InitApnsBroker(globalSettings, hostingEnvironment); }
public UserExchangeResult GetUsers(UserExchangeRequest sopRequest, CurrentContext currentContext, HttpRequestMessage httpRequest) { var result = new UserExchangeResult(); var users = unitOfWork.GetRepository<UserProfile>().GetTable(); foreach (var user in users) { var nameLabel = ""; if (string.IsNullOrEmpty(user.FirstName) && string.IsNullOrEmpty(user.LastName)) { nameLabel = user.UserName; } else { nameLabel = String.Format("{0} {1} ({2})", user.FirstName, user.LastName, user.UserName); } var nebUser = new NEBUser { Name = nameLabel, UserName = user.UserName, Id = user.Id, BillTo = new List<Customer>() }; var customers = unitOfWork.GetRepository<CustomerUserProfile>().GetTable() .Where(x => x.UserProfile.Id == nebUser.Id) .Join(unitOfWork.GetRepository<Customer>().GetTable(), customerUserProfile => customerUserProfile.Customer.Id, customer => customer.Id, (customerUserProfile, customer) => customer); foreach (var customer in customers) { if (!string.IsNullOrEmpty(customer.CustomerName) && customer.IsActive) { nebUser.BillTo.Add(new Customer() { IdString = customer.IdString }); } } result.Users.Add(nebUser); } result.Success = true; return result; }
public Message GetMessage(int id) { var message = _messagesRepository.GetMessage(id); var ctx = new CurrentContext(); var client = ctx.CurrentClient; var user = ctx.GetSystemUser(); //var userId = ctx.CurrentUserId; //var messageType = MessageTypeService.GetMessageType(message.MessageTypeId); message.MessageTypeReference.Load(); //message.MessageType = messageType; message.Client = client; message.User = user; return message; }
public OrganizationsController( IOrganizationRepository organizationRepository, IOrganizationUserRepository organizationUserRepository, IOrganizationService organizationService, IUserService userService, IPaymentService paymentService, CurrentContext currentContext, GlobalSettings globalSettings, IPolicyRepository policyRepository) { _organizationRepository = organizationRepository; _organizationUserRepository = organizationUserRepository; _organizationService = organizationService; _userService = userService; _paymentService = paymentService; _currentContext = currentContext; _globalSettings = globalSettings; _policyRepository = policyRepository; }
public Result[] RunHealthChecks() { var registry = new Registry(); var results = new List <Result>(); foreach (var healthCheckContainer in registry.HealthCheckContainers) { var healthCheck = healthCheckContainer.GetInstance(); var context = new CurrentContext(); var stopWatch = new Stopwatch(); var result = new Result { HealthCheckName = healthCheck.Name, HealthCheckDescription = healthCheck.Description, }; if (healthCheck is IAutoHealthCheck) { stopWatch.Start(); ((IAutoHealthCheck)healthCheck).Run(context); stopWatch.Stop(); } else if (healthCheck is ITriggeredHealthCheck) { ((ITriggeredHealthCheck)healthCheck).GetStatus(context); } else { throw new Exception("Unknow health check type"); } result.TimeTakenInTicks = stopWatch.ElapsedTicks; result.Passed = context.Response.Passed; result.Data = context.Response.Data; healthCheckContainer.SetState(result.Passed); result.FailureCount = healthCheckContainer.FailureCount; result.FailingSince = healthCheckContainer.FailingSince; } return(results.ToArray()); }
public void TestFixtureSetUp() { overrideContext = new TestContext(); OverrideContextCleanUp = CurrentContext.Override(overrideContext); repo = new InMemoryConfigurationRegistry(); repo.ConnStrings.Add( "main", new ConnectionStringSettings( "main", "Data Source=DbFile1.db;Version=3", "System.Data.SQLite")); repo.ConnStrings.Add( "NhConfig1", new ConnectionStringSettings( "NhConfig1", "Data Source=:memory:;Version=3;New=True;", "System.Data.SQLite")); repo.ConnStrings.Add( "NhConfig2", new ConnectionStringSettings( "NhConfig2", "Data Source=:memory:;Version=3;New=True;", "System.Data.SQLite")); OverrideSettings = ConfigurationRegistry.Override(repo); NHibernateSessionManager.GenerateDbFor("files//NhConfigFile1.cfg.xml"); }
// GET: /Cart/ public ActionResult Win(int idPro) { using (var ctx = new QLBHEntities()) { var c = CurrentContext.GetCart(); //tiem den san pham co ID = idPro, va user da dau gia no co id = id user hien tai da dang nhap var u = c.Items .Where(i => i.idUser == CurrentContext.GetCurUser().f_ID&& i.Product.ProID == idPro) .FirstOrDefault(); //nếu sản phẩm hết thời gian đấu giá if (u.Product.DateTime >= DateTime.Now) { int idU = CurrentContext.GetCurUser().f_ID; if (CurrentContext.GetCart().PriceMax(idU, idPro) == true) { var ord = new Order { OrderDate = DateTime.Now, UserID = CurrentContext.GetCurUser().f_ID, Total = u.Price//tổng giá đấu }; var detail = new OrderDetail { ProID = u.Product.ProID, Price = u.Product.Price, Amount = u.Price//giá đấu }; ord.OrderDetails.Add(detail); //ord.Total += detail.Amount; ctx.Orders.Add(ord); ctx.SaveChanges(); } } } //CurrentContext.GetCart().Items.Clear(); return(RedirectToAction("Index", "Cart")); }
public ActionResult UpdateProfile(string password, string npassword) { var result = new ArrayList(); try { string EncryptOldPassword = StringUtils.MD5(npassword); string EncryptNewPassword = StringUtils.MD5(npassword); var a = CurrentContext.GetCurUser(); var ctx = new QLHSEntities(); var u = ctx.Users.Where(p => p.username == a.username && p.password == EncryptOldPassword).FirstOrDefault(); if (u == null) { result.Add( new { value = -1, message = "Mật khẩu cũ chưa đúng" }); return(Json(result, JsonRequestBehavior.AllowGet)); } u.password = EncryptNewPassword; ctx.SaveChanges(); result.Add( new { value = 1 }); return(Json(result, JsonRequestBehavior.AllowGet)); } catch (Exception e) { result.Add( new { value = -1, message = "Lỗi " + e.ToString() }); return(Json(result, JsonRequestBehavior.AllowGet)); } }
public async Task <IActionResult> ProcessAzureQueue([FromBody] JObject request) { InitializeEnvironment(); try { var subClient = SubscriptionClient.CreateFromConnectionString(_connectionString, _topicName, _subscriptionName); subClient.OnMessage(m => { Log.Information($"Processing Azure Queue message: {m.GetBody<string>()}"); }); var messages = subClient.ReceiveBatch(_maxMessagesCount); if (messages != null && messages.Count() > 0) { var command = Command <ImportSellableItemFromContentHubCommand>(); var mappingPolicy = CurrentContext.GetPolicy <SellableItemMappingPolicy>(); foreach (var message in messages) { //Check entity type and match it to policy settings if (message != null && message.Properties.ContainsKey("target_id")) { var argument = new ImportCatalogEntityArgument(mappingPolicy, typeof(SellableItem)) { ContentHubEntityId = (string)message.Properties["target_id"] }; var result = await command.Process(CurrentContext, argument).ConfigureAwait(false); //TODO: complete on success, define failure(s) handling message.Complete(); } } } //TODO: return meaningful message(s) return(new ObjectResult(true)); //return result != null ? new ObjectResult(result) : new NotFoundObjectResult("Error importing SellableItem data"); } catch (Exception ex) { Log.Error(ex, "Error processing Azure queue message(s)"); return(new ObjectResult(ex)); } }
/// <summary> /// Notifies all subscribers that a scan has completed. /// </summary> // Revision History // MM/DD/YY Who Version Issue# Description // -------- --- ------- ------ ------------------------------------------- // 08/25/09 RCG 2.21.03 Extracted method from ScanForDevicesCallback private void NotifySubscribers() { List <OperationContext> ContextsToRemove = new List <OperationContext>(); WriteLog(Logger.LoggingLevel.Minimal, "Notifying Subscribers"); lock (m_ScanSubscribers) { // Notify the clients foreach (OperationContext CurrentContext in m_ScanSubscribers) { if (CurrentContext.Channel.State == CommunicationState.Opened) { try { WriteLog(Logger.LoggingLevel.Minimal, "\tNotifying: " + CurrentContext.SessionId); IZigBeeRadioCallBack CallBack = CurrentContext.GetCallbackChannel <IZigBeeRadioCallBack>(); CallBack.NotifyNetworkScanned(m_ZigBeeDevices); } catch (Exception ex) { // The callback must have faulted for some reason we can just ignore it // since it should be removed from the list. WriteLog(Logger.LoggingLevel.Minimal, "Exception occurred: " + ex.Message); } } else { // Looks like we lost a client we should remove them from the subscription ContextsToRemove.Add(CurrentContext); } } // Remove any dead contexts - This needs to be done outside of the previous loop // so we dont modify the list while going through it. foreach (OperationContext CurrentContext in ContextsToRemove) { m_ScanSubscribers.Remove(CurrentContext); WriteLog(Logger.LoggingLevel.Minimal, "Dead client removed: " + CurrentContext.SessionId); } } }
/// <summary> /// Porte from void journal_t::register_metadata(const string& key /// </summary> public void RegisterMetadata(string key, Value value, Item context) { if (CheckingStyle == JournalCheckingStyleEnum.CHECK_WARNING || CheckingStyle == JournalCheckingStyleEnum.CHECK_ERROR) { if (!KnownTags.Contains(key)) { if (context == null) { KnownTags.Add(key); } else if (CheckingStyle == JournalCheckingStyleEnum.CHECK_WARNING) { CurrentContext.Warning(String.Format("Unknown metadata tag '{0}'", key)); } else if (CheckingStyle == JournalCheckingStyleEnum.CHECK_ERROR) { throw new ParseError(String.Format("Unknown metadata tag '{0}'", key)); } } } if (!Value.IsNullOrEmpty(value)) { foreach (CheckExprPair pair in TagCheckExprsMap.GetValues(key)) { BindScope boundScope = new BindScope(CurrentContext.Scope, context); ValueScope valScope = new ValueScope(boundScope, value); if (!pair.Expr.Calc(valScope).AsBoolean) { if (pair.CheckExprKind == CheckExprKindEnum.EXPR_ASSERTION) { throw new ParseError(String.Format(ParseError.ParseError_MetadataAssertionFailedFor, key, value, pair.Expr)); } else { CurrentContext.Warning(String.Format(ParseError.ParseError_MetadataCheckFailedFor, key, value, pair.Expr)); } } } } }
/// <summary> /// Moves the squaddies to cover near the context indicator position. /// A working list is used to prevent squaddies being issued the same cover points. /// </summary> /// <param name="_context"></param> void SquadCoverCommand(CurrentContext _context) { order_target_bobber.SetTarget(_context.indicator_position); // Working list to prevent squaddies being issued the same cover. List <CoverPoint> allocated_points = new List <CoverPoint>(); foreach (SquaddieAI squaddie in squad_sense.squaddies) { var cover_points = GameManager.scene.tactical_assessor.ClosestCoverPoints( _context.indicator_position, squaddie.settings.cover_search_radius); if (cover_points.Count <= 0) { break; } CoverPoint target_point = null; foreach (CoverPoint cover_point in cover_points) { if (target_point != null) { break; } if (allocated_points.Contains(cover_point)) { continue; } target_point = cover_point; } if (target_point == null) { break; } allocated_points.Add(target_point); squaddie.IssueMoveCommand(target_point.position); } }
/// <summary> /// Finds the position and length of the next ANSI sequence starting at the specified offset. /// </summary> /// <param name="startOffset"></param> private Match FindPosition(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; // If the line has already been collapsed, ignore it. If we don't ignore it then the client will crash // or throw an exception on the second thing that is gagged (either here or in the GagElementGenerator). if (_parent?.Gag?.CollapsedLineSections.ContainsKey(endLine.LineNumber) ?? false) { return(new Match() { MatchOffset = startOffset }); } var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); int index = relevantText.Text.IndexOf('\x1B', relevantText.Offset, relevantText.Count); var m = new Match { MatchOffset = index > -1 ? index - relevantText.Offset + startOffset : -1 }; if (index == -1) { return(m); } int endIndex = relevantText.Text.IndexOfAny(ParseExtended ? _endMarkersExtended : _endMarkers, index); if (endIndex > -1) { endIndex++; m.Length = endIndex - index; } else { // There was no end to this sequence which might be a partial sequence. m.MatchOffset = -1; } return(m); }
// GET: Auction/ShowWin public ActionResult ShowWin() { using (var ctx = new AuctionSiteDBEntities()) { int id = CurrentContext.GetCurUser().ID; var list = (from p in ctx.Products join u in ctx.Users on p.UserID equals u.ID where p.lastuser == id && p.Bought == true select new ProductVM { UserID = p.UserID, ID = p.ID, Name = p.Name, PriceDisplay = p.PriceDisplay, Description = u.Name, }).ToList(); return(View(list)); } }
protected void Page_Load(object sender, EventArgs e) { if (CurrentContext.IsLogged() == true) { Response.Redirect("~/index.aspx"); } if (IsPostBack == false) { string msg = Request.QueryString["msg"]; switch (msg) { case "1": lbMsg.Text = "Đăng ký thành công. Bạn có thể đăng nhập."; break; default: break; } } }
public CustomTokenRequestValidator( UserManager <User> userManager, IDeviceRepository deviceRepository, IDeviceService deviceService, IUserService userService, IEventService eventService, IOrganizationDuoWebTokenProvider organizationDuoWebTokenProvider, IOrganizationRepository organizationRepository, IOrganizationUserRepository organizationUserRepository, IApplicationCacheService applicationCacheService, IMailService mailService, ILogger <ResourceOwnerPasswordValidator> logger, CurrentContext currentContext, GlobalSettings globalSettings) : base(userManager, deviceRepository, deviceService, userService, eventService, organizationDuoWebTokenProvider, organizationRepository, organizationUserRepository, applicationCacheService, mailService, logger, currentContext, globalSettings) { _userManager = userManager; }
protected override string DoProcess(dynamic args, string content) { string ref_p = ComFunc.nvl(args.ref_p); int times = IntStd.IsInt(args.times) ? IntStd.ParseStd(args.times).Value : 1; var rtn = ""; if (ref_p != "" && CurrentContext.GetParsedContent("ref", ref_p) != null) { for (int i = 0; i < times; i++) { rtn += ComFunc.nvl(CurrentContext.GetParsedContent("ref", ref_p)); } } else { rtn = ""; } return(rtn); }
private void RunTestWith(string dbName, Action <DatabaseContext> context) { TestUtils.CopyTestDB(dbName); var metaInfo = GetConfig(dbName); var cfg = Db4oEmbedded.NewConfiguration(); cfg.File.ReadOnly = true; metaInfo.Item1.Configure(cfg); var ctx = DatabaseContext.Create(Db4oEmbedded.OpenFile(cfg, dbName), metaInfo.Item2); CurrentContext.NewContext(ctx); try { context(ctx); } finally { CurrentContext.CloseContext(); } }
public void ShowLoading(string message, bool withProgress = false) { if (CurrentContext == null) { return; } CurrentContext.RunOnUiThread(() => { if (_progressDialog == null || (_progressDialog != null && (_progressDialog.IsShowing == false))) { _progressDialog = ProgressDialogFactory(CurrentContext, message, withProgress); } if (_progressDialog.IsShowing == false) { _progressDialog.Show(); } }); }
/// <summary> /// コンソールを終了します。 /// </summary> public void Detach() { if (!IsAttached) { throw new InvalidOperationException("コンソールはアタッチされていません。"); } IsAttached = false; CurrentSession.PreMessageReceived -= new EventHandler <MessageReceivedEventArgs>(Session_PreMessageReceived); CurrentSession.PostMessageReceived -= new EventHandler <MessageReceivedEventArgs>(Session_PostMessageReceived); try { CurrentContext.Dispose(); } catch {} foreach (Context ctx in ContextStack) { try { ctx.Dispose(); } catch {} } CurrentContext = null; }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (CurrentContext.IsLogged() == false) { filterContext.Result = new RedirectResult("~/Account/Login"); return; } if (CurrentContext.GetCurUser().f_Level < this.RequiredPermission) { filterContext.Result = new RedirectResult("~/Error/Index"); return; } base.OnActionExecuting(filterContext); }
public JsonResult DeleteFavProduct(int id) { try { var User = CurrentContext.GetCurUser(); Favorite temp = db.Favorites.Where(x => x.ProductID == id && x.UserID == User.UserID).FirstOrDefault(); if (temp == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(Json(new { Result = "Error" })); } db.Favorites.Remove(temp); db.SaveChanges(); return(Json(new { Result = "OK" })); } catch (Exception ex) { return(Json(new { Result = "ERROR", Message = ex.Message })); } }
private ClientContext(ClientConfig configuration) { _config = configuration; if (configuration == null) { throw new InvalidOperationException( "Current Context could not be initialized. No configuration passed to the context"); } var logger = LogFactory.CreateInstance(configuration.Runtime.LogInfo); var cache = CacheFactory.Create(configuration.Caching); cache.ItemRemoved += (sender, args) => Log.Debug("Item removed from cache: " + args.CacheKey + " Reason : " + args.RemoveReason); CurrentContext.CreateDefault(logger, new CommandArgs(string.Empty), cache); }
public PoliciesController( IPolicyRepository policyRepository, IPolicyService policyService, IOrganizationService organizationService, IOrganizationUserRepository organizationUserRepository, IUserService userService, CurrentContext currentContext, GlobalSettings globalSettings, IDataProtectionProvider dataProtectionProvider) { _policyRepository = policyRepository; _policyService = policyService; _organizationService = organizationService; _organizationUserRepository = organizationUserRepository; _userService = userService; _currentContext = currentContext; _globalSettings = globalSettings; _organizationServiceDataProtector = dataProtectionProvider.CreateProtector( "OrganizationServiceDataProtector"); }
protected void Page_Load(object sender, EventArgs e) { SectionTitle = AppLogic.GetString("giftregistry.aspx.13", SkinID, ThisCustomer.LocaleSetting, true); if (AppLogic.AppConfigBool("GoNonSecureAgain")) { SkinBase.GoNonSecureAgain(); } if (ThisCustomer.IsNotRegistered) { string requestedPage = Security.UrlEncode(Request.Url.PathAndQuery); Response.Redirect("findgiftregistry.aspx"); } if (!AppLogic.AppConfigBool("GiftRegistry.Enabled")) { CurrentContext.GoPageNotFound(); } }
/// <summary> /// Close current transaction, this function is private because is used inside a DisposableAction. /// We need to check if are inside an exception handler to doom the transaction, then we need to /// remove the global transaction from the context and committ it. /// </summary> private static void CloseCurrentTransaction() { Verify.That(IsInTransaction, "Cannot doom the transaction because there is not an active transaction"); if (Utils.ExceptionUtils.IsInExceptionHandler()) { CurrentTransaction.Doom(); } Boolean IsDoomed = CurrentTransaction.IsDoomed; OnTransactionClosing(IsDoomed); Transaction currentTransaction = CurrentTransaction; CurrentTransactionList.RemoveAt(CurrentTransactionList.Count - 1); if (CurrentTransactionList.Count == 0) { CurrentContext.ReleaseData(TransactionScopeKey); } currentTransaction.Complete(); OnTransactionClosed(IsDoomed); }
protected void VerifyCanCreateUseAndDisposeNestedUnitOfWork() { Assert.AreEqual(-1, CurrentContext.UnitOfWorkNestingLevel, "level before starting UnitOfWork = -1"); CurrentContext.CreateUnitOfWork(); Assert.AreEqual(0, CurrentContext.UnitOfWorkNestingLevel, "level before starting UnitOfWork = 0"); CurrentContext.CreateNestedUnitOfWork(); Assert.AreEqual(1, CurrentContext.UnitOfWorkNestingLevel, "level after staring Nested UnitOfWork = 1"); // in nested unit-of-work UnitOfWork.CurrentSession.Save(new GuidEntityForTesting()); UnitOfWork.CurrentSession.Flush(); CurrentContext.DisposeUnitOfWork(); // in original unit-of-work UnitOfWork.CurrentSession.Save(new GuidEntityForTesting()); UnitOfWork.CurrentSession.Flush(); CurrentContext.DisposeUnitOfWork(); }
static public string PrepareGit(string branch) { CurrentContext.ValidateAdmin(); if (!Lock()) { return("Locked by another user!"); } Git git = getGit(); List <string> res = new List <string>(); git.RunCommand("rebase --abort"); res.AddRange(git.Checkout("master")); git.DeleteBranch(branch); res.AddRange(git.ResetHard("origin/master")); res.AddRange(git.PullOrigin()); res.AddRange(git.Status()); res.AddRange(git.Checkout(branch)); res.AddRange(git.PullOrigin()); return(string.Join(Environment.NewLine, res.ToArray()).Replace(Environment.NewLine, "<br/>")); }
public ActionResult Register(RegisterVM model) { if (!ModelState.IsValid) { // TODO: Captcha validation failed, show error message ViewBag.ErrorMsg = "Sai mã xác nhận, vui lòng nhập lại!"; } else { if (CurrentContext.GetCheckEmail().checkEmailHopLe(model.Email) == false) { ViewBag.ErrorMsg = "Email đã tồn tại, mời nhập email khác!"; } else { // TODO: Captcha validation passed, proceed with protected action User u = new User { f_Username = model.Username, f_Email = model.Email, f_Name = model.Name, f_Password = StringUtils.Md5(model.RawPWD), f_Permission = 0, f_DOB = DateTime.ParseExact(model.DOB, "d/m/yyyy", null), f_Phone = model.Phone, f_Address = model.Address, //f_Money = Decimal.Parse(model.Money, NumberStyles.Currency) f_Money = Convert.ToDecimal(model.Money.ToString().TrimStart('¥')) }; using (QLBHEntities ctx = new QLBHEntities()) { ctx.Users.Add(u); ctx.SaveChanges(); } } } return(View()); }
private void _current_timer_tm_Tick(object sender, EventArgs e) { _local_time_al_lb.Text = string.Format("Local Time: {0:hh:mm tt}", DateTime.Now); _local_time_lb.Text = string.Format("Local Time: {0:hh:mm tt}", DateTime.Now); if (!IsInternetExists) { InternetConnectionCount++; if (InternetConnectionCount >= CommonConst.CHECK_CONNECTION_INTERVAL) { InternetConnectionCount = 0; if (WebProcessor.CheckInternetConnection()) { IsInternetExists = true; try { CurrentContext.GetInstance().VersionData.VersionDetected = VersionController.GetInstance().GetVersionData(string.Empty); if (CurrentContext.GetInstance().VersionData.VersionDetected) { _new_version_lb.TextAlign = ContentAlignment.MiddleCenter; DetectVersionState(); } else { CurrentContext.GetInstance().VersionData.State = VersionState.UNKNOWN; } SetVersionButton(); ConfVersionPanel(); } catch { CurrentContext.GetInstance().VersionData.State = VersionState.UNKNOWN; } } else { IsInternetExists = false; } } } }
protected override ExecutionContext LoadToken(ushort tokenId) { ContractState contract = CurrentContext.GetState <ExecutionContextState>().Contract; if (contract is null || tokenId >= contract.Nef.Tokens.Length) { throw new InvalidOperationException(); } MethodToken token = contract.Nef.Tokens[tokenId]; if (token.ParametersCount > CurrentContext.EvaluationStack.Count) { throw new InvalidOperationException(); } StackItem[] args = new StackItem[token.ParametersCount]; for (int i = 0; i < token.ParametersCount; i++) { args[i] = Pop(); } return(CallContractInternal(token.Hash, token.Method, token.CallFlags, token.HasReturnValue, args)); }
protected void VerifyCanCreateUseAndDisposeSession() { ISession session = null; try { if (IoC.IsNotInitialized) { IoC.Initialize(); } CurrentContext.CreateUnitOfWork(); session = CurrentContext.CreateSession(); Assert.IsNotNull(session); session.Save(new GuidEntityForTesting()); session.Flush(); } finally { CurrentContext.DisposeSession(session); CurrentContext.DisposeUnitOfWork(); } }
/// <summary> /// Ported from void journal_t::register_commodity(commodity_t& comm, /// </summary> public void RegisterCommodity(Commodity commodity, Post post = null) { if (CheckingStyle == JournalCheckingStyleEnum.CHECK_WARNING || CheckingStyle == JournalCheckingStyleEnum.CHECK_ERROR) { if (!commodity.Flags.HasFlag(CommodityFlagsEnum.COMMODITY_KNOWN)) { if (post == null) // Porting note: it is equal "context.which() == 0" assuming that we never deal with xact { commodity.Flags |= CommodityFlagsEnum.COMMODITY_KNOWN; } else if (CheckingStyle == JournalCheckingStyleEnum.CHECK_WARNING) { CurrentContext.Warning(String.Format("Unknown commodity '{0}'", commodity)); } else if (CheckingStyle == JournalCheckingStyleEnum.CHECK_ERROR) { throw new ParseError(String.Format("Unknown commodity '{0}'", commodity)); } } } }
public bool CreateTransaction(LoadMoneyViewModel model) { try { var _ctx = new CurrentContext(); var _transaction = new Transaction { Sum = model.Sum, Comment = model.Comment, Balance = model.Balance, PaymentMethod = PaymentMethodService.GetPaymentMethod(model.MethodId), User = _ctx.CurrentASPUser, Client = _ctx.GetClient(model.ClientId) }; _repository.CreateTransaction(_transaction); return true; } catch (Exception ex) { _validationDictionary.AddError("_FORM", "Transaction is not saved. " + ex.Message); return false; } }
public bool CreateMessage(Message message) { try { var ctx = new CurrentContext(); var client = ctx.CurrentClient; var userId = ctx.CurrentUserId; var messageType = MessageTypeService.GetMessageType(message.MessageTypeId); message.MessageType = messageType; //message.MessageTypeId; var user = ctx.GetSystemUser(); message.Client = client; message.User = user; //message.User.UserId = userId; _messagesRepository.CreateMessage(message); return true; } catch (Exception ex) { _validationDictionary.AddError("_FORM", "Message not created" + ex.Message); return false; } }
public void ProcessClientPayment() { var ctx = new CurrentContext(); _repository.ProcessClientPayment(ctx.CurrentUserId); }
public static string SecureLink(this HtmlHelper html, string label, string link) { var ctx = new CurrentContext(); var user = ctx.GetUser(ctx.CurrentUserId); return user.IsInRole(ROLES.admin) ? link : label; }
private Client BuildClient(ClientViewModel viewModel) { var ctx = new CurrentContext(); var client = ClientService.GetClient(viewModel.UserId) ?? new Client { User = ctx.GetUser(viewModel.UserId) }; client.Credit = viewModel.Credit; client.Status = StatusService.GetStatus(viewModel.StatusId); return client; }
private CurrentContext WriteClassStartTag(int hvoItem) { CurrentContext ccOld = m_cc; if (m_cc != CurrentContext.insideLink) m_cc = CurrentContext.insideObject; int clid = m_cache.GetClassOfObject(hvoItem); string sClass = m_cache.MetaDataCacheAccessor.GetClassName((uint)clid); IndentLine(); if (m_cc == CurrentContext.insideLink) { sClass = sClass + "Link"; m_writer.WriteLine("<{0} target=\"hvo{1}\">", sClass, hvoItem); } else { if (clid == LexEntry.kclsidLexEntry && m_sFormat == "xhtml") WriteEntryLetterHeadIfNeeded(hvoItem); else if (clid == ReversalIndexEntry.kclsidReversalIndexEntry && m_sFormat == "xhtml") WriteReversalLetterHeadIfNeeded(hvoItem); m_writer.WriteLine("<{0} id=\"hvo{1}\">", sClass, hvoItem); } m_rgElementTags.Add(sClass); m_rgClassNames.Add(sClass); return ccOld; }
private void WriteFieldEndTag(int flid, CurrentContext ccOld) { m_cc = ccOld; int iTop = m_rgElementTags.Count - 1; string sField = m_rgElementTags[iTop]; m_rgElementTags.RemoveAt(iTop); if (sField != null && sField.Length > 0) { IndentLine(); m_writer.WriteLine("</{0}>", sField); } }
public List<Message> ListMessages() { CurrentContext ctx = new CurrentContext(); if(Roles.IsUserInRole(ctx.CurrentASPUser.UserName, ROLES.admin.ToString())) return _messagesRepository.ListMessages(); return _messagesRepository.ListMessages(ctx.CurrentASPUser.UserId); }
public List<Client> ListClients(bool deleted) { var ctx = new CurrentContext(); var _status = StatusService.GetStatus(STATUSES.Deleted); var list = _repository.ListClients(_status, deleted); var system = list.Find(c => c.UserId == ctx.GetSystemUser().UserId); if (system != null) list.Remove(system); return list; }
public AddressController() { _ctx = new CurrentContext(); _addressService = new AddressService(new ModelStateWrapper(ModelState)); }
private void WriteClassEndTag(int hvoItem, CurrentContext ccOld) { m_cc = ccOld; int iTop = m_rgElementTags.Count - 1; string sClass = m_rgElementTags[iTop]; m_rgElementTags.RemoveAt(iTop); IndentLine(); m_writer.WriteLine("</{0}>", sClass); iTop = m_rgClassNames.Count - 1; m_rgClassNames.RemoveAt(iTop); if (UpdateProgress != null && m_rgClassNames.Count == 0) UpdateProgress(this); }
public DatabaseManager(CurrentContext currentContext, IEnumsValuesProvider enumsValuesProvider) { _currentContext = currentContext; _enumsValuesProvider = enumsValuesProvider; }
public ModelFactory(CurrentContext currentContext) { _currentContext = currentContext; }
public SyncController() { _service = new SynchronizationService(new ModelStateWrapper(ModelState)); _context = new CurrentContext(); }
private CurrentContext WriteFieldStartTag(int flid) { CurrentContext ccOld = m_cc; string sXml; try { IFwMetaDataCacheManaged mdc = (IFwMetaDataCacheManaged)m_sda.MetaDataCache; CellarPropertyType cpt = (CellarPropertyType)mdc.GetFieldType(flid); string sField = mdc.GetFieldName((int)flid); switch (cpt) { case CellarPropertyType.ReferenceAtomic: // Don't treat the Self property as starting a link (or a property). // View it as just a continuation of the current state. (See FWR-1673.) if (sField != "Self" || !mdc.get_IsVirtual(flid)) m_cc = CurrentContext.insideLink; break; case CellarPropertyType.ReferenceCollection: case CellarPropertyType.ReferenceSequence: m_cc = CurrentContext.insideLink; break; default: m_cc = CurrentContext.insideProperty; break; } sXml = GetFieldXmlElementName(sField, flid/1000); if (sXml == "_") { sXml = String.Empty; } else { if (sXml == "_" + sField && ccOld == CurrentContext.insideLink && m_cc == CurrentContext.insideProperty) { AddMissingObjectLink(); sXml = GetFieldXmlElementName(sField, flid / 1000); } IndentLine(); string sUserLabel = null; if (mdc.IsCustom(flid)) { // REVIEW: NOT SURE userlabel attribute is useful (or needed) in the // new system since the field name serves as the label. On the other // hand, the field name might have spaces in it, which is a no-no for // XML element tags. if (!m_dictCustomUserLabels.TryGetValue(flid, out sUserLabel)) { sUserLabel = m_sda.MetaDataCache.GetFieldLabel((int)flid); m_dictCustomUserLabels.Add(flid, sUserLabel); } sXml = sXml.Replace(' ', '.'); } if (String.IsNullOrEmpty(sUserLabel)) m_writer.WriteLine("<{0}>", sXml); else m_writer.WriteLine("<{0} userlabel=\"{1}\">", sXml, sUserLabel); } } catch { sXml = String.Empty; } m_rgElementTags.Add(sXml); return ccOld; }
private CurrentContext WriteFieldStartTag(int flid) { CurrentContext ccOld = m_cc; string sXml; try { int cpt = m_cache.MetaDataCacheAccessor.GetFieldType((uint)flid); switch (cpt) { case (int)CellarModuleDefns.kcptReferenceAtom: case (int)CellarModuleDefns.kcptReferenceCollection: case (int)CellarModuleDefns.kcptReferenceSequence: m_cc = CurrentContext.insideLink; break; default: m_cc = CurrentContext.insideProperty; break; } string sField = m_cache.MetaDataCacheAccessor.GetFieldName((uint)flid); sXml = GetFieldXmlElementName(sField, (uint)flid/1000); if (sXml == "_" + sField && ccOld == CurrentContext.insideLink && m_cc == CurrentContext.insideProperty) { AddMissingObjectLink(); sXml = GetFieldXmlElementName(sField, (uint)flid / 1000); } IndentLine(); string sUserLabel = null; if (sField.StartsWith("custom")) { if (!m_dictCustomUserLabels.TryGetValue(flid, out sUserLabel)) { IOleDbCommand odc = null; try { odc = DbOps.MakeRowSet(m_cache, String.Format("SELECT UserLabel FROM Field$ WHERE Id={0}", flid), null); bool fMoreRows; odc.NextRow(out fMoreRows); if (fMoreRows) sUserLabel = XmlUtils.MakeSafeXmlAttribute(DbOps.ReadString(odc, 0)); } finally { if (odc != null) DbOps.ShutdownODC(ref odc); } m_dictCustomUserLabels.Add(flid, sUserLabel); } } if (String.IsNullOrEmpty(sUserLabel)) m_writer.WriteLine("<{0}>", sXml); else m_writer.WriteLine("<{0} userlabel=\"{1}\">", sXml, sUserLabel); } catch { sXml = String.Empty; } m_rgElementTags.Add(sXml); return ccOld; }
public string Connect() { var ctx = new CurrentContext(); var _host = ctx.GetCurrentHost(); return Connect(_host.Address, _host.UserName, _host.UserPassword); }
private CurrentContext WriteClassStartTag(int hvoItem) { CurrentContext ccOld = m_cc; if (m_cc != CurrentContext.insideLink) m_cc = CurrentContext.insideObject; var obj = m_cache.ServiceLocator.GetInstance<ICmObjectRepository>().GetObject(hvoItem); int clid = obj.ClassID; string sClass = m_sda.MetaDataCache.GetClassName(clid); IndentLine(); if (m_cc == CurrentContext.insideLink) { sClass = sClass + "Link"; var targetItem = hvoItem; if (obj is ILexSense) { // We want the link to go to the containing lex entry. // This has two advantages: first, the user can see the whole entry, rather than part of it // being scrolled off the top of the screen; // Secondly, some senses (e.g., of variants) may not be shown in the HTML at all, resulting in bad links (LT-11099) targetItem = ((ILexSense) obj).Entry.Hvo; } m_writer.WriteLine("<{0} target=\"hvo{1}\">", sClass, targetItem); } else { if (clid == LexEntryTags.kClassId && m_sFormat == "xhtml") WriteEntryLetterHeadIfNeeded(hvoItem); else if (clid == ReversalIndexEntryTags.kClassId && m_sFormat == "xhtml") WriteReversalLetterHeadIfNeeded(hvoItem); m_writer.WriteLine("<{0} id=\"hvo{1}\">", sClass, hvoItem); } m_rgElementTags.Add(sClass); m_rgClassNames.Add(sClass); return ccOld; }