protected override void Context() { _view = A.Fake <IParameterIdentificationChartFeedbackView>(); _chartDisplayPresenter = A.Fake <IChartDisplayPresenter>(); _dimensionFactory = A.Fake <IDimensionFactory>(); _predictedVsObservedChartService = A.Fake <IPredictedVsObservedChartService>(); _displayUnitRetriever = A.Fake <IDisplayUnitRetriever>(); _parameterIdentification = A.Fake <ParameterIdentification>(); _observationColumns = new List <DataColumn>(); _curveList = new List <Curve>(); _baseGrid = DomainHelperForSpecs.ObservedData().BaseGrid; _outputMapping = new OutputMapping(); sut = new ParameterIdentificationPredictedVsObservedFeedbackPresenter(_view, _chartDisplayPresenter, _dimensionFactory, _displayUnitRetriever, _predictedVsObservedChartService); A.CallTo(() => _parameterIdentification.AllOutputMappings).Returns(new[] { _outputMapping }); A.CallTo(() => _parameterIdentification.AllObservationColumnsFor(A <string> ._)).Returns(_observationColumns); _observationColumns.Add(new DataColumn()); _observationColumns.Add(new DataColumn()); A.CallTo(() => _predictedVsObservedChartService.AddCurvesFor(_observationColumns, A <DataColumn> ._, A <ParameterIdentificationPredictedVsObservedChart> ._, A <Action <DataColumn, Curve> > ._)).Invokes(x => { var action = x.Arguments.Get <Action <DataColumn, Curve> >(3); _observationColumns.Each(observation => { var curve = new Curve { Name = "Best" }; action(new DataColumn(ShortGuid.NewGuid(), A.Fake <IDimension>(), _baseGrid), curve); _curveList.Add(curve); }); _chart = x.GetArgument <ParameterIdentificationPredictedVsObservedChart>(2); }); }
public async Task <ActionResult> Create(MapEntity model) { if (!ModelState.IsValid) { return(this.View(model)); } model.PartitionKey = MapEntity.MainKey; model.RowKey = ShortGuid.NewGuid().Value; try { // upload image to blob storage. model.ImageAddress = await UploadImageToStorage(model.RowKey, model.ImageAddress); await TableStorage.Insert(model); } catch (StorageException error) { Task.Run(() => RavenClient.CaptureException(error)); ViewBag.Alerts = new List <AlertModel> { new AlertModel(AlertType.Danger, error.Message) }; return(this.View(model)); } this.TempData["Alerts"] = AlertModel.CreateSingle(AlertType.Success, string.Format("{0} by {1} was created.", model.Title, model.Author)); this.TempData["Highlight"] = new HighlightModel(AlertType.Success, model.PartitionKey, model.RowKey); return(this.RedirectToAction("Index")); }
public ClaimsIdentity GenerateUserIdentity(UserManager <UserModel, int> manager, string authenticationType) { this.claims = manager.CreateIdentity(this, authenticationType); var stsId = ShortGuid.NewGuid(); this.claims.AddClaim(new Claim("sts:id", stsId, ClaimValueTypes.String)); var stsData = manager.GetSecurityStamp(Id); this.claims.AddClaim(new Claim("sts:ds", CryptographService.CreateMacCode(stsData, stsId), ClaimValueTypes.String)); this.claims.AddClaim(new Claim(System.IdentityModel.Tokens.JwtRegisteredClaimNames.AuthTime, DateTime.UtcNow.Ticks.ToString(), ClaimValueTypes.Integer64)); this.claims.AddClaim(new Claim("name", this.Name, ClaimValueTypes.String)); // 不要なクレームを削除 var delClaim = this.claims.Claims.Where(c => c.Type == "AspNet.Identity.SecurityStamp").SingleOrDefault(); if (delClaim != null) { this.claims.TryRemoveClaim(delClaim); } delClaim = this.claims.Claims.Where(c => c.Type == "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider").SingleOrDefault(); if (delClaim != null) { this.claims.TryRemoveClaim(delClaim); } return(this.claims); }
private void CreateTest() { Test test = new Test(); test.Code = ShortGuid.NewGuid().ToString(); test.Company_Id = Company.Id; test.CreationDate = this.creationDate; test.CurrentEvaluations = 0; test.Disordered = true; test.OneQuestionnaire = true; test.EvaluationNumber = employees; test.EvaluationsLefts = employees; test.GroupByCategories = false; test.MinimumPeople = 2; test.ConfidenceLevel_Id = 1; test.StandardError_Id = 6; test.Name = "Medición de Engagement Organizacional - " + Company.Name; test.Questionnaire_Id = 74; test.RecordsPerPage = 7; test.StartDate = DateTime.Now; test.EndDate = DateTime.Now.AddDays(weeks * 7); test.Text = "Medición Demo de Engagement Organizacional para " + Company.Name; test.User_Id = 8; test.Weighted = false; if (!new TestsServices().Add(test)) { this.Ok = false; } else { CreateDemographicsInTest(test.Id); } }
public async Task <ActionResult <Job> > CreateJob(CreateJobModel data) { // // Validate input // if (data == null) { return(BadRequest()); } // // Perform action // var db = this._context; var jobId = ShortGuid.NewGuid(); var job = new Job(jobId) { Status = JobStatus.Created, Threads = data.Threads, Files = data.Links.Select(f => new File(jobId, f.Name) { Url = f.Url }).ToArray() }; // HACK: Simplified Job(s) queue integration. // NOTE: DO NOTE USE THIS CODE IN PRODUCTION!! try { db.Add(job); await db.SaveChangesAsync(); } catch (DbUpdateException ex) { var dbEx = ex.InnerException as System.Data.Common.DbException; if (dbEx != null) { return(ValidationProblem(new ValidationProblemDetails(new Dictionary <String, String[]>() { { $"{dbEx.ErrorCode}", new [] { dbEx.Message } } }))); } throw; } var queue = this._queue; if (queue != null && !queue.TryAdd(job, TimeSpan.FromMilliseconds(500))) { Log.Warn("Job {id} has been created, but was not queued for processing and will be ignored.", job.Id); } // END HACK // // Report result // return(CreatedAtAction("Get", new { id = job.Id }, job)); }
/// <summary> /// 在新建的AppDomain中新建一个看门狗,并在超时后,调用指定Type的指定MethodName函数 /// </summary> /// <param name="targetDomain">指定的目标AppDomain</param> /// <param name="softDogName">自定义看门狗名称,不允许重复</param> /// <param name="timeOut">超时时间设定,不允许低于1秒</param> /// <param name="type">超时后将执行的函数所在类的Type</param> /// <param name="methodName">超时后将指定的函数名称</param> /// <param name="args">超时后将执行的函数的参数,所有参数值必须为可序列化</param> /// <returns></returns> public static SoftDogInterface CreateSoftDog(string softDogName, int timeOut, Type type, string methodName, params object[] args) { var appDomain = createNewDomain(ShortGuid.NewGuid().ToString()); return(CreateSoftDog(appDomain, softDogName, timeOut, type, methodName, args)); }
public static string GenerateZipName(int count) { return(count + "-inbox-files-" + AppTime.Now().ToString("MM_dd_yyyy", CultureInfo.InvariantCulture) + "_" + ShortGuid.NewGuid() + ".zip"); }
public ActionResult SendMonthlyStatement(AuthorStatementRequestToken request, string img) { var token = _billingManageServices.GetAuthorMonthlyStatement(request); if (!token.IsValid) { return(ErrorResponse(token.Message)); } string error; var imageBytes = Convert.FromBase64String(img.Substring(img.IndexOf(',') + 1)); var stream = new MemoryStream(imageBytes.Length); stream.Write(imageBytes, 0, imageBytes.Length); var fileName = FileEnums.eFileOwners.Author + "/Charts/" + ShortGuid.NewGuid() + ".png"; var etag = _s3Wrapper.Upload(fileName, "image/png", stream, out error); var url = string.IsNullOrEmpty(etag) ? "#" : _s3Wrapper.GetFileURL(fileName); token.ChartImageUrl = url; var body = RenderRazorViewToString("MonthlyStatementEmail", token); var result = _billingManageServices.SendAuthorMonthlyStatement(token, body, out error); return(Json(new JsonResponseToken { success = result, error = error }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Create new local device. Initialize device /// </summary> /// <param name="deviceType">The type of device on which the new record is created</param> /// <returns>New device definition</returns> public async Task <Device> CreateDevice(DeviceTypeEnum deviceType) { const string methodCode = "M01"; Device device = new Device(); device.DeviceId = ShortGuid.NewGuid().Value; device.Name = $"{deviceType.LocalizedName}"; device.FolderId = Guid.NewGuid().ToString("N"); device.CreatedWhen = DateTimeOffset.Now; Log.Trace(methodCode, "Create Device {@DeviceType}", deviceType.LocalizedName); await dalRepo.SaveAsync(device); await Log.AuditAsync(AuditCodes.CreateDevice, DataTypeEnum.Device, device.DeviceId, SystemEntityGuidConst.UserSystem); /* * if(string.IsNullOrEmpty(app.ActualFoderDevices)) * app.ActualFoderDevices = Guid.NewGuid().ToString("N"); * * device.FolderId = app.ActualFoderDevices; * device.CreatedWhen = DateTimeOffset.Now; * device.UpdatedWhen = device.CreatedWhen; * return device; */ return(null); }
public async Task <string> GeneratePasswordResetTokenAsync(string userName, int tokenExpirationInMinutesFromNow = 1440) { if (string.IsNullOrEmpty(userName)) { throw new ArgumentNullException(nameof(userName)); } var user = await _unitOfWorkAsync.RepositoryAsync <ApplicationUser>() .Queryable() .SingleOrDefaultAsync(u => u.UserName.Equals(userName.Trim())); if (user == null) { return(string.Empty); } string token = ShortGuid.NewGuid(); user.PasswordResetToken = token; user.TrackingState = TrackingState.Modified; _unitOfWorkAsync.RepositoryAsync <ApplicationUser>().Update(user); await _unitOfWorkAsync.SaveChangesAsync(); return(token.Trim()); }
/// <summary> /// Initializes the hud for the specified avatar. It will create a temporary ticket-id for authentication purposes. /// The client browser will send an event back over websockets when it has initialized. /// </summary> /// <param name="avatar">The avatar.</param> public void Initialize(GameAvatar avatar) { var guid = ShortGuid.NewGuid(); _avatarSessionTicets.Add(guid, avatar.Session); _instance.UrlSendOverlay(avatar, _url + "?" + guid); }
} = new VAICOMMessageWrapper(); //used to temporarily stop PTT for VAICOM private ClientStateSingleton() { ShortGUID = ShortGuid.NewGuid(); DcsPlayerRadioInfo = new DCSPlayerRadioInfo(); PlayerCoaltionLocationMetadata = new DCSPlayerSideInfo(); // The following members are not updated due to events. Therefore we need to setup a polling action so that they are // periodically checked. DcsGameGuiLastReceived = 0; DcsExportLastReceived = 0; _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += (s, e) => { NotifyPropertyChanged("IsGameConnected"); NotifyPropertyChanged("IsLotATCConnected"); NotifyPropertyChanged("ExternalAWACSModeConnected"); }; _timer.Start(); FixedChannels = new PresetChannelsViewModel[10]; for (int i = 0; i < FixedChannels.Length; i++) { FixedChannels[i] = new PresetChannelsViewModel(new FilePresetChannelsStore(), i + 1); } LastSent = 0; IsConnected = false; ExternalAWACSModelSelected = false; LastSeenName = Settings.GlobalSettingsStore.Instance.GetClientSetting(Settings.GlobalSettingsKeys.LastSeenName).StringValue; }
private static DirectoryInfo GetNewTempDir() { string appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string tempName = ShortGuid.NewGuid(); return(new DirectoryInfo(Path.Combine(appData, tempName))); }
public void Validate(IEnumerable <Picture> objectToValidate) { var toValidate = objectToValidate as Picture[] ?? objectToValidate.ToArray(); var duplicatedPictureNames = toValidate.GroupBy(x => x.Name) .Where(x => x.Count() > 1) .ToList(); if (!duplicatedPictureNames.Any()) { return; } foreach (var duplicatedGroup in duplicatedPictureNames) { foreach (var picture in duplicatedGroup) { var dupName = picture.Name; picture.Name = dupName + ShortGuid.NewGuid(); } } var toLongPicNames = toValidate.Where(x => x.Name.Length > 50); foreach (var longPicName in toLongPicNames) { longPicName.Name = longPicName.Name.Remove(10, longPicName.Name.Length - 10); } }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { if (_dataService.IsExistingUsername(username)) { status = MembershipCreateStatus.DuplicateUserName; return(null); } if (_dataService.IsExistingEmail(email)) { status = MembershipCreateStatus.DuplicateEmail; return(null); } TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)); string salt = SimpleHash.GetSalt(32); string activationCode = ShortGuid.NewGuid(); User user = new User() { email = email, usergroupid = 3, username = username, password = SimpleHash.MD5(password, salt), passworddate = DateTime.Now.Date, usertitle = "Guest", joindate = Convert.ToInt32(ts.TotalSeconds), timezoneoffset = -6, options = 45108439, salt = salt, showbirthday = 0, showvbcode = 0, membergroupids = string.Empty }; user = _dataService.CreateForumUser(user, activationCode); if (user != null) { Login login = new Login(); login.Username = username; login.Password = SimpleHash.MD5(password, salt); login.Email = email; login.ForumUserId = user.userid; login.PasswordSalt = salt; login = _dataService.CreateLogin(login); if (login != null) { NtxfcMembershipProvider provider = Membership.Provider as NtxfcMembershipProvider; provider.SendConfirmationEmail(username, email, String.Format("{0}/Account/Activation/?u={1}&i={2}", ConfigurationManager.AppSettings["MemberUrl"], HttpContext.Current.Server.UrlEncode(username), activationCode)); status = MembershipCreateStatus.Success; return(new MembershipUser(this.Name, username, login.Id, login.Email, string.Empty, string.Empty, true, false, new DateTime(), new DateTime(), new DateTime(), new DateTime(), new DateTime())); } } status = MembershipCreateStatus.ProviderError; return(null); }
public async Task <IActionResult> Register(RegisterViewModel vm) { if (ModelState.IsValid) { var user = new AppUser { UserName = ShortGuid.NewGuid().ToString(), PhoneNumber = vm.PhoneNumber }; var result = await _userManager.CreateAsync(user, vm.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, vm.PhoneNumber); await _smsSender.SendSmsAsync(vm.PhoneNumber, code); var vmRegisterVerifyCode = new RegisterVerifyCodeViewModel(); vmRegisterVerifyCode.ReturnUrl = Url.Action(nameof(RegisteredConfirmation), GetControllerName <AccountController>(), new { vm.ReturnUrl }); vmRegisterVerifyCode.UserId = user.Id; vmRegisterVerifyCode.PhoneNumber = vm.PhoneNumber; return(View(nameof(RegisterVerifyCode), vmRegisterVerifyCode)); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(vm)); }
public DummyMoleculeContainerDTO MapFrom(IObjectBase objectBase) { var dto = Map <DummyMoleculeContainerDTO>(objectBase); dto.Id = ShortGuid.NewGuid(); dto.MoleculePropertiesContainer = _objectBaseToDTOObjectBaseMapper.MapFrom(_moleculePropertiesContainer); return(dto); }
public SimulationTransfer() { AllObservedData = new List <DataRepository>(); PkmlVersion = Constants.PKML_VERSION; Id = ShortGuid.NewGuid(); Favorites = new Favorites(); JournalPath = string.Empty; }
public Deck() { _cards = ImmutableList <Card> .Empty; DeckId = ShortGuid.NewGuid(); Enabled = true; CreatedBy = CreatedBy.DeckOfCards; }
protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { //Dont redirect for Post action, as we may loose the form data if (requestContext.HttpContext.Request.HttpMethod == HttpMethod.Post.ToString()) { return base.GetHttpHandler(requestContext); } //Get current unique id from RouteData var guidString = Convert.ToString(requestContext.RouteData.Values["tabid"]); //if true, then construct new url with tab id if (!string.IsNullOrEmpty(guidString)) { //create new guid guidString = ShortGuid.NewGuid().ToString(); //construct redirect url string rootUrl = requestContext.AbsoluteUriBeforeRoute(); string controller = Convert.ToString(requestContext.RouteData.Values["controller"]); string action = Convert.ToString(requestContext.RouteData.Values["action"]); string id = Convert.ToString(requestContext.RouteData.Values["id"]); string queryString = requestContext.HttpContext.Request.Url.Query; string url = $"{rootUrl}/t/{guidString}"; bool skipToQueryString = false; if (controller.Equals("Main", StringComparison.OrdinalIgnoreCase) && action.Equals("Index", StringComparison.OrdinalIgnoreCase)) { skipToQueryString = true; } if(!skipToQueryString) { url += $"/{controller}"; if (!action.Equals("Index", StringComparison.OrdinalIgnoreCase)) { url += $"/{action}"; } } if (!string.IsNullOrWhiteSpace(id)) { url += $"/{id}"; } url += queryString; //redirect permanantly to unique tab url requestContext.HttpContext.Response.Redirect(url, true); } return base.GetHttpHandler(requestContext); }
public RootNodeType(string name, ApplicationIcon icon, ClassificationType classificationType = ClassificationType.Unknown) { Id = ShortGuid.NewGuid().ToString(); Name = name; Icon = icon; _classification = new Classification { ClassificationType = classificationType }; }
public void NewGuidTest() { ShortGuid expected = new ShortGuid(); // TODO: Initialize to an appropriate value ShortGuid actual; actual = ShortGuid.NewGuid(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public string CreateUserAndAccount(string userName, string password, string email, Guid myGuid, bool requireConfirmationToken = false) { if (string.IsNullOrEmpty(userName)) { throw new ArgumentNullException(nameof(userName)); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } if (string.IsNullOrEmpty(email)) { throw new ArgumentNullException(nameof(email)); } string token = null; if (requireConfirmationToken) { token = ShortGuid.NewGuid(); } var isConfirmed = !requireConfirmationToken; if (token == null) { return(null); } var user = new ApplicationUser { UserName = userName.Trim(), Email = email.Trim(), ConfirmationToken = token.Trim(), IsConfirmed = isConfirmed }; user.TrackingState = TrackingState.Added; var result = _userManager.Create(user, password.Trim()); if (result.Succeeded) { return(token); } var innerMsg = new StringBuilder(); foreach (var msg in result.Errors) { innerMsg.Append(msg); } var ex = new MembershipCreateUserException(innerMsg.ToString()); throw ex; }
public void ShowData(IReadOnlyList <DataRepository> data) { var chart = _chartFactory.Create <CurveChart>().WithAxes(); chart.Id = ShortGuid.NewGuid(); chart.Name = getChartName(data); addChartToProject(chart); ShowChart(chart, data); }
private EntityMetaData mapFrom(CurveChart chart) { var entityMetaData = new EntityMetaData { Id = ShortGuid.NewGuid() }; serialize(entityMetaData, chart); return(entityMetaData); }
public UsedObservedDataNode(UsedObservedData usedObservedData, DataRepository observedData) : base(usedObservedData) { _observedData = observedData; Tag = usedObservedData; UpdateText(); //new id should not be the one from the data repository=>hence a new id _id = ShortGuid.NewGuid(); }
public DummyMoleculeDTO MapFrom(IMoleculeBuilder moleculeBuilder, IContainer container) { var dto = Map <DummyMoleculeDTO>(moleculeBuilder); dto.MoleculeBuilder = moleculeBuilder; dto.StructureParent = container; dto.Id = ShortGuid.NewGuid(); return(dto); }
public DummyReactionDTO MapFrom(IReactionBuilder reactionBuilder, IContainer container) { var dto = Map <DummyReactionDTO>(reactionBuilder); dto.Id = ShortGuid.NewGuid(); dto.ReactionBuilder = reactionBuilder; dto.StructureParent = container; return(dto); }
public DummyParameterDTO MapFrom(IParameter parameter, IContainer structureParent, IObjectBaseDTO modelParent) { var dto = Map <DummyParameterDTO>(parameter); dto.ParameterToUse = Map <ObjectBaseDTO>(parameter); dto.Parent = structureParent; dto.ModelParentName = modelParent.Name; dto.Id = ShortGuid.NewGuid(); return(dto); }
public Curve() { Id = ShortGuid.NewGuid(); _name = string.Empty; _description = string.Empty; _xData = null; _yData = null; CurveOptions = new CurveOptions(); Rules = new BusinessRuleSet(); }