public ActionResult Edit(User user) { var id = new Guid(Request.Form["Id"]); var user1 = User as ApplicationUser; try { _userUILogic.UpdateUser(id, user); return(RedirectToAction("Index", "User", new { allbody = "both" })); } catch (Exception exception) { if (user1 != null) { this._log.ErrorFormat( "Current User: {0} - An exception occurred with the following message: {1}", user1.UserName, exception.Message); } _applicationAlert.RaiseAlert(ApplicationAlertKind.System, exception.TraceInformation()); if (Request.IsAjaxRequest()) { return(PartialView("Edit", user)); } return(View("Edit", user)); } }
public ActionResult Create(OwnerInvitationModel newModel) { var user = User as ApplicationUser; try { if (!ModelState.IsValid) { return(RedirectToAction("Index", new { reload = true })); } var emailNotExist = _invitationUILogic.NotFoundUserWithEmail(newModel.SentTo); if (emailNotExist) { _invitationUILogic.CreateInvitation(newModel, Request.Url, user); Thread.Sleep(100); //an issue when adding new invitation it do not appear on the index after adding return(RedirectToAction("Index")); } TempData.Add("CurrentInvitation", newModel); TempData.Remove("MessageError"); TempData.Add("MessageError", "Email already invited, try with another email"); ModelState.AddModelError("SentTo", "Email already invited, try with another email"); return(RedirectToAction("Index", new { reload = true })); } catch (Exception ex) { var errorMessage = "Failure to send the email, please check the SMTP configuration"; if (ExceptionHandler.Manage(ex, this, Layer.UILogic)) { errorMessage = ex.Message; } if (user != null) { _log.ErrorFormat("Current User: {0} - An exception occurred with the following message: {1}", user.UserName, ex.Message); } _applicationAlert.RaiseAlert(ApplicationAlertKind.System, ex.TraceInformation()); this.ModelState.AddModelError("Tenancy", errorMessage); TempData.Remove("MessageError"); TempData.Add("MessageError", errorMessage); TempData.Remove("CurrentInvitation"); TempData.Add("CurrentInvitation", newModel); return(RedirectToAction("Index", new { reload = true })); } }
public bool RejectInvitation(Invitation invitation) { try { using (var session = ReturnContext()) { var invit = session.Load <Invitation>(invitation.Id); if (invit != null) { if (invitation.AcceptingUser != null) { invit.AcceptingUser.Status = UserStatus.RejectInvitation; } invit.Status = InvitationStatus.Rejected; session.SaveChanges(); } else { var tenants = session.Query <Tenant>().ToArray(); foreach (Tenant tenant in tenants) { using (var tenantContext = DocumentStoreLocator.Resolve(tenant.Site)) { var invitationTenant = tenantContext.Load <Invitation>(invitation.Id); if (invitationTenant != null) { if (invitationTenant.AcceptingUser != null) { invitationTenant.AcceptingUser.Status = UserStatus.RejectInvitation; } invitationTenant.Status = InvitationStatus.Rejected; tenantContext.SaveChanges(); break; } } } } } } catch (Exception ex) { _log.ErrorFormat("InvitationManager: An exception occurred with the following message: {0}", ex.Message); _applicationAlert.RaiseAlert(ApplicationAlertKind.System, ex.TraceInformation()); } return(true); }
public static bool ValidateConfiguration(Type configType) { Debug.Assert(configType.IsEnum); IConfig config = Catalog.Factory.Resolve <IConfig>(); string missingConfigs = string.Empty; foreach (var key in Enum.GetNames(configType)) { Enum tkey = (Enum)Enum.Parse(configType, key); string val = config.Get(tkey, _missingKeyString); if (val == _missingKeyString) { var ms = string.Format("Configuration validation: cannot retrieve key {0}", key); CriticalLog.Always.WarnFormat(ms); missingConfigs += ms; } } if (!string.IsNullOrEmpty(missingConfigs)) { IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.Defect, missingConfigs); } return(true); }
public byte[] RetrieveFromBlobStorage(string key) { var container = _bc.GetContainerReference(_containerName); container.CreateIfNotExist(); string blobUri = key; var blob = container.GetBlobReference(blobUri); if (!blob.Exists()) { var es = string.Format("Image {0} cannot be found in blob storage", key); _log.Error(es); IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.Unknown, es); return(null); } byte[] bytes = blob.DownloadByteArray(); lock (_cache) { if (!_cache.ContainsKey(key)) { _dblog.InfoFormat("Image {0} retrieved from blob storage, adding to cache", key); _cache.Add(key, bytes); } } return(bytes); }
/// <summary> /// This method prevents unhandled exceptions from being thrown from the worker thread. /// </summary> public void ProtectedRun() { try { // Call the Workers Run() method Run(); } catch (SystemException sex) { var es = "Worker system exception, exiting"; IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.System, es, sex); _log.Fatal(es, sex); throw; } catch (Exception ex) { var es = string.Format("Swallowed exception while running worker {0}:", GetType().FullName); IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.Defect, es, ex); _dblog.Error(es, ex); } }
public ActionResult TakeOwnership(TakeOwnerShipModel model) { try { if (!Request.IsAuthenticated) { RedirectToAction("Login"); } if (!ModelState.IsValid) { // If we got this far, something failed, redisplay form return(View(model)); } _accountBusinessLogic.ValidateOwner(model); var validPasscode = _accountBusinessLogic.ValidatePasscode(model); if (!validPasscode) { throw new ApplicationException("Pass Code is not correct"); } if (TempData.ContainsKey("passcode")) { TempData["passcode"] = model.PassCode; } else { TempData.Add("passcode", model.PassCode); } return(RedirectToAction("Register")); } catch (Exception ex) { _log.ErrorFormat( "Current User: {0} - An exception occurred with TakeOwnership Passcode: {1}", User.Identity.Name, ex.Message); _applicationAlert.RaiseAlert(ApplicationAlertKind.System, ex.TraceInformation()); ModelState.AddModelError("Error", ex.Message); TempData.Remove("ownershipError"); TempData["ownershipError"] = ex.Message; return(View(model)); } }
public virtual bool GetBillingPlanFromCoupon(string couponPassKey, out BillingPlan billingPlan, out Coupon coupon) { Debug.Assert(!string.IsNullOrEmpty(couponPassKey)); using (var ds = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute)) { billingPlan = null; coupon = ds.Load <Coupon>(couponPassKey); } if (null == coupon) { _dblog.InfoFormat("No coupon found for passkey {0}", couponPassKey); return(false); } IUserContext _uc = Catalog.Factory.Resolve <IUserContext>(); var user = _uc.GetCurrentUser(); if (!string.IsNullOrEmpty(coupon.Target)) { if (user.PrincipalId != coupon.Target) { _dblog.InfoFormat("User {0} is not the target of coupon {1}", user.PrincipalId, coupon.PassString); return(false); } } if (coupon.TotalAllowed > 0 && (coupon.CurrentCount >= coupon.TotalAllowed)) { _dblog.InfoFormat("Coupon {0} exceeded allowed counts of {1}", coupon.PassString, coupon.TotalAllowed); return(false); } billingPlan = coupon.BillingPlan; if (null == billingPlan) { var es = string.Format("Coupon does not have a proper billing plan: coupon {0}", coupon.PassString); _log.Error(es); IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.System, es); return(false); } _dblog.InfoFormat("Coupon passkey {0} linked to billing plan {1}", couponPassKey, billingPlan.Name); return(true); }
private void MirrorCopy() { if (!Directory.Exists(_targetPath)) { Directory.CreateDirectory(_targetPath); } var blobs = Client.FromConfig().ForBlobs(); var source = blobs.GetContainerReference(SourcePath); source.CreateIfNotExist(); var versionBlob = source.GetBlobReference("Version.txt"); string versionString = versionBlob.DownloadText(); if (string.IsNullOrEmpty(versionString)) { var es = string.Format("Local File Mirror source in blob container {0} does not have blob Version.txt", SourcePath); _log.Error(es); IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.Unknown, es); versionString = Guid.NewGuid().ToString(); } string completedFile = TargetPath + "\\LFMComplete.txt"; if (!File.Exists(completedFile) || File.ReadAllText(completedFile) != versionString) { var theBlobs = source.ListBlobs(); foreach (IListBlobItem b in theBlobs) { var fileBlob = source.GetBlobReference(b.Uri.ToString()); string filename = Path.GetFileName(b.Uri.ToString()); File.Delete(filename); fileBlob.DownloadToFile(_targetPath + "\\" + filename); } File.WriteAllText(completedFile, versionString); } }
public virtual BillingPlan GetDefaultBillingPlan() { BillingPlan dbp = null; using (var ds = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute)) { dbp = ds.Load <BillingPlan>(DefaultBillingPlanName); } Debug.Assert(null != dbp); if (null == dbp) { var es = "No default billing plan found!"; _log.FatalFormat(es); IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.System, es); } return(dbp); }
public ActionResult Delete( Lok.Unik.ModelCommon.ItemRegistration.ItemRegistration itemRegistration) { var user = User as ApplicationUser; try { _itemRegistrationUILogic.Delete(itemRegistration.Id); return(null); } catch (Exception ex) { _log.ErrorFormat("Current User: {0} - An exception occurred with the following message: {1}", user.UserName, ex.Message); _applicationAlert.RaiseAlert(ApplicationAlertKind.System, ex.TraceInformation()); } return(Request.IsAjaxRequest() ? PartialView("Delete", itemRegistration) : (ActionResult)View("Delete", itemRegistration)); }
protected override void ProcessUpgradeTrx(string trxInfo, string trxCode, string subRole, string unSubRole, string subFailTemplate, string signUpTempl, string shareTempl) { Debug.Assert(!string.IsNullOrEmpty(trxInfo)); Debug.Assert(!string.IsNullOrEmpty(trxCode)); Debug.Assert(!string.IsNullOrEmpty(subRole)); Debug.Assert(!string.IsNullOrEmpty(unSubRole)); Debug.Assert(!string.IsNullOrEmpty(subFailTemplate)); Debug.Assert(!string.IsNullOrEmpty(signUpTempl)); Debug.Assert(!string.IsNullOrEmpty(shareTempl)); _dblogger.InfoFormat("Processing upgrade transaction, trxInfo {0}, trxCode {1}", trxInfo, trxCode); ApplicationUser user = null; ApplicationUserSubscription subscr = null; using (var ds = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute)) { user = ds.Load <ApplicationUser>(trxInfo); subscr = (ApplicationUserSubscription) user.Extensions.GetOrAdd(ApplicationUserSubscription.Extension, _ => new ApplicationUserSubscription()); } if (null != user) { var bp = subscr.BillingPlan; if (null == bp) { var es = string.Format("billing plan {0} not found for user {1}", subscr.BillingPlan, user.PrincipalId); _logger.Error(es); IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.System, es); return; } switch (trxCode) { case PayPal.SubscriptionSignUp: case PayPal.SubscriptionPayment: SignUpUser(user, signUpTempl, subRole, unSubRole, shareTempl); break; case PayPal.SubscriptionFailed: case PayPal.SubscriptionCancel: case PayPal.SubscriptionEnd: UnsignUser(user, subFailTemplate, unSubRole); break; } } else { var es = string.Format("user {0} not found for upgrade", trxInfo); _logger.Error(es); IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.System, es); } }
protected override void ProcessExpressTrx( string trxInfo, string trxCode, string buyerEmail, string invoice, string unSubRole, string sendAuthCodeTemplate, string subscriptionFailTemplate) { Debug.Assert(!string.IsNullOrEmpty(trxCode)); Debug.Assert(!string.IsNullOrEmpty(trxInfo)); Debug.Assert(!string.IsNullOrEmpty(invoice)); Debug.Assert(!string.IsNullOrEmpty(unSubRole)); Debug.Assert(invoice.Contains(";")); _dblogger.InfoFormat("Processing express transaction: trxInfo {0}, trxCode {1}, invoice {2}", trxInfo, trxCode, invoice); var detail = invoice.Split(';'); BillingPlan bp = null; Debug.Assert(detail.Length == 3); using (var ds = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute)) { try { string billingName = detail[1]; bp = ds.Load <BillingPlan>(billingName); if (null == bp) { var es = string.Format("no billing plan found from invoice {0}", invoice); _logger.Error(es); IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.System, es); throw new ApplicationException(); } } catch (Exception ex) { IApplicationAlert on = Catalog.Factory.Resolve <IApplicationAlert>(); on.RaiseAlert(ApplicationAlertKind.System, ex); return; } AuthorizationCode ac = ds.Load <AuthorizationCode>(trxInfo); switch (trxCode) { case PayPal.SubscriptionSignUp: case PayPal.SubscriptionPayment: Debug.Assert(!string.IsNullOrEmpty(buyerEmail)); if (null == ac || ac.Principal == null) { // no user, no auth code. So send the user an authcode to use var newAuthCode = new AuthorizationCode { Code = trxInfo, ExpirationTime = DateTime.UtcNow + TimeSpan.FromDays(90.0), Referent = bp.Name, EmailedTo = buyerEmail }; ds.Store(newAuthCode); ds.SaveChanges(); var email = SendEmail.CreateFromTemplate(_sender, Enumerable.Repeat(buyerEmail, 1).ToArray(), sendAuthCodeTemplate, trxInfo, newAuthCode.Code); email.Send(); _logger.InfoFormat("Sent authcode {0} to user {1}", newAuthCode.Code, buyerEmail); } break; case PayPal.SubscriptionFailed: case PayPal.SubscriptionCancel: case PayPal.SubscriptionEnd: { Debug.Assert(null != ac); var user = ds.Load <ApplicationUser>(ac.Principal); if (null == user) { _logger.ErrorFormat("Payment notification for unknown user {0}", ac.Principal); } else { UnsignUser(user, subscriptionFailTemplate, unSubRole); } } break; } } // doc session }
public void DoTransactNodeInfo( IEnumerable <NodeMetric> currentMetrics, DateTime metricsCollectionTime, IEnumerable <NodeAlert> newAlerts, int activityLevel, out ApplicationNodeStates desiredState, out LoggingConfiguration desiredLogging) { desiredState = ApplicationNodeStates.Running; desiredLogging = null; try { using (var dc = DocumentStoreLocator.Resolve(DocumentStoreLocator.RootLocation)) { // try to load existing node var appNode = dc.Load <ApplicationNode>(_reg.Id); // create new if necessary bool created = false; if (null == appNode) { _log.Warn("Creating application node record"); created = true; appNode = new ApplicationNode { Id = _reg.Id, ComponentType = _reg.ComponentType, MachineName = Environment.MachineName, State = ApplicationNodeStates.Running, Version = _reg.Version, IPAddress = GetLocalIP(), LoggingConfiguration = new LoggingConfiguration { ClassFilter = "none", File = _logFilePath, LogLevel = 0 } }; } // update node data desiredLogging = appNode.LoggingConfiguration; desiredState = appNode.State; appNode.LastPing = DateTime.UtcNow; appNode.MetricCollectionTime = metricsCollectionTime; appNode.Metrics = currentMetrics.ToList(); appNode.Alerts.AddRange(newAlerts); appNode.ActivityLevel = activityLevel; if (created) { dc.Store(appNode); } dc.SaveChanges(); } } catch (ConcurrencyException) { // just get it next time } catch (Exception ex) { _log.Error(ex.TraceInformation()); _alert.RaiseAlert(ApplicationAlertKind.Unknown, ex.TraceInformation()); } }
public static Tenant GetOrCreate(string tenancy) { Tenant tenant; try { var config = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Safe); var defaultDb = config[CommonConfiguration.DefaultDataDatabase]; if (Catalog.Factory.CanResolve <ITenantCreationLicense>()) { var licenseChecker = Catalog.Factory.Resolve <ITenantCreationLicense>(); licenseChecker.CheckTenantCreationLicensed(); } if (defaultDb.Equals(tenancy)) { throw new ApplicationException("A tenancy cannot use the same db name as the core db"); } var ravenServer = config[CommonConfiguration.DefaultDataConnection]; var dbName = tenancy; var user = config[CommonConfiguration.DefaultDataUser]; var pass = config[CommonConfiguration.DefaultDataPassword]; var site = String.Format(TenantConstants.RouteFormat, UnikContextTypes.UnikTenantContextResourceKind, tenancy); var id = String.Format(TenantConstants.TenantIdFormat, tenancy); tenant = new TenantManager().GetOrCreate(tenancy, site, id); if (tenant == null) { return(null); } DocumentStoreLocator.AddRoute(new Uri(site), ravenServer, dbName, user, pass, tenancy); var warehouseRoute = String.Format(TenantConstants.RouteFormat, UnikContextTypes.UnikWarehouseContextResourceKind, tenancy); DocumentStoreLocator.AddRoute( new Uri(warehouseRoute), ravenServer, String.Format(TenantConstants.WarehouseDbFormatName, dbName), user, pass, tenancy); //raise an event on tenant created //then the caller can create indexes or any other actions OnTenantCreated(site, tenancy); } catch (LicenseException lex) { Log.ErrorFormat("An exception occurred with the following message: {0}", lex.Message); ApplicationAlert.RaiseAlert(ApplicationAlertKind.System, lex.TraceInformation()); // Pass along info that tenant creation failed due to license exception. throw; } catch (Exception exception) { Log.ErrorFormat("An exception occurred with the following message: {0}", exception.Message); ApplicationAlert.RaiseAlert(ApplicationAlertKind.System, exception.TraceInformation()); return(null); } return(tenant); }