/// <inheritdoc/> public override void ShowInView(IHtmlView htmlView, KeyValueList <string, string> variables, Navigation redirectedFrom) { base.ShowInView(htmlView, variables, redirectedFrom); _viewModel = new OpenSafeViewModel( Ioc.GetOrCreate <INavigationService>(), Ioc.GetOrCreate <ILanguageService>(), Ioc.GetOrCreate <ISvgIconService>(), Ioc.GetOrCreate <IThemeService>(), Ioc.GetOrCreate <IBaseUrlService>(), Ioc.GetOrCreate <IFeedbackService>(), Ioc.GetOrCreate <ICryptoRandomService>(), Ioc.GetOrCreate <ISettingsService>(), Ioc.GetOrCreate <IRepositoryStorageService>(), RedirectedFrom); Bindings.BindCommand("GoBack", _viewModel.GoBackCommand); Bindings.BindCommand("OkCommand", _viewModel.OkCommand); Bindings.BindCommand("CancelCommand", _viewModel.CancelCommand); Bindings.BindCommand("ResetSafeCommand", _viewModel.ResetSafeCommand); Bindings.BindText("Password", null, (v) => _viewModel.Password = SecureStringExtensions.StringToSecureString(v), null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindText("PasswordConfirmation", null, (v) => _viewModel.PasswordConfirmation = SecureStringExtensions.StringToSecureString(v), null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindInvalid("Password", () => _viewModel.InvalidPasswordError, _viewModel, nameof(_viewModel.InvalidPasswordError), HtmlViewBindingMode.OneWayToView); Bindings.BindInvalid("PasswordConfirmation", () => _viewModel.InvalidPasswordConfirmationError, _viewModel, nameof(_viewModel.InvalidPasswordConfirmationError), HtmlViewBindingMode.OneWayToView); string html = _viewService.GenerateHtml(_viewModel); View.LoadHtml(html); }
/// <inheritdoc/> public override void ShowInView(IHtmlView htmlView, KeyValueList <string, string> variables, Navigation redirectedFrom) { base.ShowInView(htmlView, variables, redirectedFrom); IStoryBoardService storyBoardService = Ioc.GetOrCreate <IStoryBoardService>(); SerializeableCloudStorageCredentials credentials = storyBoardService.ActiveStory.LoadFromSession <SerializeableCloudStorageCredentials>(SynchronizationStorySessionKey.CloudStorageCredentials); _viewModel = new CloudStorageAccountViewModel( Ioc.GetOrCreate <INavigationService>(), Ioc.GetOrCreate <ILanguageService>(), Ioc.GetOrCreate <ISvgIconService>(), Ioc.GetOrCreate <IThemeService>(), Ioc.GetOrCreate <IBaseUrlService>(), storyBoardService, Ioc.GetOrCreate <IFeedbackService>(), Ioc.GetOrCreate <ICloudStorageClientFactory>(), credentials); Bindings.BindCommand("GoBack", _viewModel.GoBackCommand); Bindings.BindCommand("OkCommand", _viewModel.OkCommand); Bindings.BindCommand("CancelCommand", _viewModel.CancelCommand); Bindings.BindText("Url", null, (v) => _viewModel.Url = v, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindText("Username", null, (v) => _viewModel.Username = v, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindText("Password", () => SecureStringExtensions.SecureStringToString(_viewModel.Password), (v) => _viewModel.Password = SecureStringExtensions.StringToSecureString(v), _viewModel, nameof(_viewModel.Password), HtmlViewBindingMode.TwoWayPlusOneTimeToView); Bindings.BindCheckbox("Secure", null, (v) => _viewModel.Secure = v, null, null, HtmlViewBindingMode.OneWayToViewmodel); string html = _viewService.GenerateHtml(_viewModel); View.LoadHtml(html); }
/// <inheritdoc/> public override void ShowInView(IHtmlView htmlView, KeyValueList <string, string> variables, Navigation redirectedFrom) { base.ShowInView(htmlView, variables, redirectedFrom); _viewModel = new OpenSafeViewModel( Ioc.GetOrCreate <INavigationService>(), Ioc.GetOrCreate <ILanguageService>(), Ioc.GetOrCreate <ISvgIconService>(), Ioc.GetOrCreate <IThemeService>(), Ioc.GetOrCreate <IBaseUrlService>(), Ioc.GetOrCreate <IFeedbackService>(), Ioc.GetOrCreate <ICryptoRandomService>(), Ioc.GetOrCreate <ISettingsService>(), Ioc.GetOrCreate <IRepositoryStorageService>(), RedirectedFrom); VueBindingShortcut[] shortcuts = new[] { new VueBindingShortcut(VueBindingShortcut.KeyEscape, nameof(OpenSafeViewModel.GoBackCommand)), new VueBindingShortcut(VueBindingShortcut.KeyEnter, nameof(OpenSafeViewModel.OkCommand)), }; VueBindings = new VueDataBinding(_viewModel, View, shortcuts); _viewModel.VueDataBindingScript = VueBindings.BuildVueScript(); VueBindings.StartListening(); string html = _viewService.GenerateHtml(_viewModel); View.LoadHtml(html); }
/// <summary>初始化各状态</summary> protected virtual void InitStates(ref int name) { IsRun = false; mStateIndex = 0; mStates = new KeyValueList <int, IState>(); SubStateWillChange = int.MaxValue; IState state; int max = StateInfos.Length; mStateList = new List <IState>(max); for (int i = 0; i < max; i++) { state = StateInfos[i]; if (state.IsValid) { state.SetFSMName(name); state.SetFSM(this); state.StateFrameUpdater = StateFrameUpdater; AddState(i, ref state); AfterStateInited(ref state); } else { state.Dispose(); } } Array.Clear(StateInfos, 0, StateInfos.Length); }
/// <summary> /// 发送消息,执行 /// </summary> /// <param name="_name"></param> public void SendNotice(string _name) { if (m_noticesList.ContainsKey(_name)) { m_noticesList[_name](); } }
/// <inheritdoc/> public override void ShowInView(IHtmlView htmlView, KeyValueList <string, string> variables, Navigation redirectedFrom) { base.ShowInView(htmlView, variables, redirectedFrom); _viewModel = new SettingsViewModel( Ioc.GetOrCreate <INavigationService>(), Ioc.GetOrCreate <ILanguageService>(), Ioc.GetOrCreate <ISvgIconService>(), Ioc.GetOrCreate <IThemeService>(), Ioc.GetOrCreate <IBaseUrlService>(), Ioc.GetOrCreate <ISettingsService>(), Ioc.GetOrCreate <IStoryBoardService>()); Bindings.BindCommand("GoBack", _viewModel.GoBackCommand); Bindings.BindCommand("ChangeCloudSettingsCommand", _viewModel.ChangeCloudSettingsCommand); Bindings.BindCommand("ClearCloudSettingsCommand", _viewModel.ClearCloudSettingsCommand); Bindings.BindDropdown("SelectedEncryptionAlgorithm", null, SetEncryptionAlgorithmToViewmodel, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindDropdown("SelectedAutoSyncMode", null, (string value) => _viewModel.SelectedAutoSyncMode = value, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindText("CloudStorageSettings", () => _viewModel.AccountSummary, null, _viewModel, nameof(_viewModel.AccountSummary), HtmlViewBindingMode.OneWayToView); Bindings.BindBackgroundImage("SelectedTheme", () => _viewModel.SelectedTheme.Image, _viewModel, nameof(_viewModel.SelectedTheme), HtmlViewBindingMode.OneWayToView); Bindings.BindCheckbox("UseSolidColorTheme", null, (bool value) => _viewModel.UseSolidColorTheme = value, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindText("ColorForSolidThemeHex", null, (string value) => _viewModel.ColorForSolidThemeHex = value, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindDropdown("SelectedThemeMode", null, (string value) => _viewModel.SelectedThemeMode = value, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindDropdown("SelectedNoteInsertionMode", null, (string value) => _viewModel.SelectedNoteInsertionMode = value, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindCheckbox("UseColorForAllNotesInDarkMode", null, (bool value) => _viewModel.UseColorForAllNotesInDarkMode = value, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.BindText("ColorForAllNotesInDarkModeHex", null, (string value) => _viewModel.ColorForAllNotesInDarkModeHex = value, null, null, HtmlViewBindingMode.OneWayToViewmodel); Bindings.UnhandledViewBindingEvent += UnhandledViewBindingEventHandler; string html = _viewService.GenerateHtml(_viewModel); View.LoadHtml(html); }
public TerritoryIDType?MoveTowardsNearestBorder(TerritoryIDType id, bool neutralOk) { var neighborDistances = new KeyValueList <TerritoryIDType, int>(); foreach (var immediateNeighbor in Map.Territories[id].ConnectedTo.Keys) { var nearestBorder = FindNearestBorder(immediateNeighbor, id, neutralOk); if (nearestBorder != null) { neighborDistances.Add(immediateNeighbor, nearestBorder.Depth); } } if (neighborDistances.Count == 0) { return(null); } var ret = neighborDistances.GetKey(0); int minValue = neighborDistances.GetValue(0); for (int i = 1; i < neighborDistances.Count; i++) { if (neighborDistances.GetValue(i) < minValue) { ret = neighborDistances.GetKey(i); minValue = neighborDistances.GetValue(i); } } return(ret); }
public static void SetLanguage(List <KeyValue> lanuages) { currentLanuage = lanuages; _currentLanuage = new KeyValueList(); _currentLanuage.AddRange(currentLanuage); }
public KeyValueList LoginToDatabase(string database, string username, string password) { string errorMessage = string.Empty; //if (password.Length == 0) errorMessage = "Please enter password"; //if (username.Length == 0) errorMessage = "Please enter user name"; //if (database.Length == 0) errorMessage = "Please provide domain name."; //if (!AppContext.Current.Settings.AllowUsersToLogin) errorMessage = "All logins were restricted by administrator."; //string authenticationType = AppContext.Current.Settings.AuthenticationType; //if (authenticationType != "Database") errorMessage = "Use " + authenticationType + " authentiation"; //if (errorMessage.Length == 0) //{ // // Now lets check if employee exist inside aspnet_ tables and import new users if required. // Engine.Security.Check.CheckToImportMissingUsers(username); // // Here must be validation with password. You can add third party validation here; // bool success = System.Web.Security.Membership.ValidateUser(username, password); // if (!success) errorMessage = "Validation failed. User name '" + username + "' was not found."; //} var results = new KeyValueList(); //if (errorMessage.Length > 0) //{ // results.Add("Status", false); // results.Add("Message", errorMessage); //} //else //{ // Engine.Security.Authentication.SetCurrentUser(username); // SessionContext.Current.InitConfigOnValidationSuccess(username); // results.Add("Status", true); // results.Add("Message", "Welcome to " + database + "!"); //} return(results); }
public KeyValueList LoginCheck() { var results = new KeyValueList(); // If context user exist then... string currentUser = string.Empty; if (System.Web.HttpContext.Current.User != null) { if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { currentUser = System.Web.HttpContext.Current.User.Identity.Name; } } results.Add("FormsCookieName", FormsAuthentication.FormsCookieName); //FormsAuthentication.GetAuthCookie(); HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie.Value.Length > 0) { var ticket = FormsAuthentication.Decrypt(cookie.Value); } string v = string.Empty; for (int i = 0; i < cookie.Values.AllKeys.Length; i++) { v += cookie.Values.AllKeys[i] + ", "; } results.Add("values", cookie.Value.ToString()); //System.Web.HttpContext.Current.Response.Cookies; results.Add("IdentityName", System.Threading.Thread.CurrentPrincipal.Identity.Name); results.Add("CurrentUser", currentUser); return(results); }
private HotFixClient() { "log".Log("Application will run almost in hot fix client.."); mCommonUpdaters = new CommonUpdaters(); mStateMapper = new KeyValueList <IState, IUpdate>(); mFSMMapper = new KeyValueList <IStateMachine, IUpdate>(); Modulars = new DecorativeModulars(); Configs = new ConfigHelper(); Datas = new DataWarehouse(); FSMs = new StateMachines { FSMFrameUpdater = OnFSMFrameUpdater, StateFrameUpdater = OnStateFrameUpdater, }; Sounds = new SoundEffects(); Sounds.Init(); #region 对主工程框架中热更端需要覆盖的各功能单元做重填充,以使得相同功能的代码定义转移到热更端 Framework framework = Framework.Instance; framework.ReloadUnit(new IFrameworkUnit[] { framework.CreateUnitByBridge(Framework.UNIT_MODULARS, Modulars), framework.CreateUnitByBridge(Framework.UNIT_CONFIG, Configs), framework.CreateUnitByBridge(Framework.UNIT_DATA, Datas), framework.CreateUnitByBridge(Framework.UNIT_FSM, FSMs), framework.CreateUnitByBridge(Framework.UNIT_SOUND, Sounds), }); #endregion }
public AssetsPooling() { mPool = new KeyValueList <int, Stack <GameObject> >(); mCompPool = new KeyValueList <int, Stack <Component> >(); mPoolElmMax = new KeyValueList <int, int>(); mCompPoolElmMax = new KeyValueList <int, int>(); }
public Servers(params Action[] onInites) { mServerMapper = new KeyValueList <string, IServer>(); mNewServers = new List <IServer>(); mServersWillSort = new List <IServer>(); mServersWillCheck = new List <IServer>(); mInitPriorType = typeof(ServerPriority); mAliasID = new IntegerID <string>(); mTypeMapper = new IntegerMapper <Type>(); mBinderIDs = new IntegerID <ResolvableBinder>(); mResolvableNameMapper = new IntegerMapper <string>(); mBinderMapper = new Dictionary <int, ResolvableBinder>(); mResolvablesMapper = new Dictionary <int, IResolvable>(); mResolvableConfigs = new KeyValueList <int, IResolvableConfig>(); int max = onInites.Length; for (int i = 0; i < max; i++) { OnInit += onInites[i]; } }
/// <summary>销毁</summary> public virtual void Dispose() { mIsStateActived = false; IState state = default; int max = mSubStateList.Size; var list = mSubStateList.Keys; for (int i = 0; i < max; i++) { state = mSubStateList.GetValue(list[i]); #if ILRUNTIME state?.Dispose(); #else Utils.Reclaim(state); #endif } #if ILRUNTIME mSubStateList?.Clear(); mSubStateList = default; #else Utils.Reclaim(mSubStateList); #endif mIsInited = false; mSubState = default; mSubStateList = default; mFSM = default; mFSMName = int.MaxValue; mChangingState = default; mChangingStateParam = default; mSelfParam = default; }
/// <inheritdoc/> protected override void ViewNotifiedEventHandler(KeyValueList <string, string> parameters = null) { bool boolValue = parameters["checked"] != null; ValueFromViewEventHandler = boolValue; ViewToViewmodel(); }
/// <inheritdoc/> public override void ShowInView(IHtmlView htmlView, KeyValueList <string, string> variables, Navigation redirectedFrom) { base.ShowInView(htmlView, variables, redirectedFrom); _viewModel = new RecycleBinViewModel( Ioc.GetOrCreate <INavigationService>(), Ioc.GetOrCreate <ILanguageService>(), Ioc.GetOrCreate <ISvgIconService>(), Ioc.GetOrCreate <IThemeService>(), Ioc.GetOrCreate <IBaseUrlService>(), Ioc.GetOrCreate <IFeedbackService>(), Ioc.GetOrCreate <ISettingsService>(), Ioc.GetOrCreate <ICryptoRandomService>(), Ioc.GetOrCreate <IRepositoryStorageService>()); Bindings.BindCommand("GoBack", _viewModel.GoBackCommand); Bindings.BindCommand("EmptyRecycleBin", _viewModel.EmptyRecycleBinCommand); Bindings.BindGeneric <object>( NotesChangedEventHandler, null, null, null, new HtmlViewBindingViewmodelNotifier(_viewModel, "Notes"), HtmlViewBindingMode.OneWayToViewPlusOneTimeToView); Bindings.UnhandledViewBindingEvent += BindingsEventHandler; string html = _viewService.GenerateHtml(_viewModel); htmlView.LoadHtml(html); }
private void LogFromTester(ITester tester, int logID, params string[] args) { ITester target = tester ?? mDefaultTester; if (target == null) { return; } KeyValueList <int, LogItem> list = mLoggerMapper[target.Name]; if ((list != null) && list.IsContainsKey(logID)) { LogItem logger = list[logID]; string log = string.Format(logger.format, args).Append(" (", mLogCount.ToString(), ")"); if (mLogSignTarget != null) { DebugUtils.LogInColorAndSignIt(mLogSignTarget, log); mLogSignTarget = null; } else { if (string.IsNullOrEmpty(logger.logColor)) { DebugUtils.LogInColor(log); } else { DebugUtils.LogInColor(logger.logColor, log); } } logger.onLoged?.Invoke(); mLogCount++; } }
public virtual void InitModular() { mCreaterByAttributes = new List <ModularNoticeCreater>(); mDecoraterByAttributes = new List <ModularNoticeDecorater>(); mListenerByAttributes = new List <ModularNoticeListener>(); mModularNotifierMapper = new KeyValueList <Action <INoticeBase <int> >, ModularNotifier>(); if (NoticeCreates == default) { NoticeCreates = new ModularNoticeCreater[0]; } else { } if (NoticeDecoraters == default) { NoticeDecoraters = new ModularNoticeDecorater[0]; } else { } if (NoticeListeners == default) { NoticeListeners = new ModularNoticeListener[0]; } else { } InitCustomHandlers(); GenerateModularHandlers(); }
/// <inheritdoc/> public void Navigate(string controllerId, string variableName, string variableValue) { var variables = new KeyValueList <string, string>(StringComparer.InvariantCultureIgnoreCase); variables[variableName] = variableValue; Navigate(controllerId, variables); }
public void IsEnumerable() { KeyValueList <string, string> list = new KeyValueList <string, string>(); list["one"] = "once"; list["two"] = "twice"; int index = 0; foreach (var item in list) { switch (index) { case 0: Assert.AreEqual("one", item.Key); break; case 1: Assert.AreEqual("two", item.Key); break; default: throw new Exception("Too many iterations"); } index++; } }
/// <inheritdoc/> public override void ShowInView(IHtmlView htmlView, KeyValueList <string, string> variables, Navigation redirectedFrom) { base.ShowInView(htmlView, variables, redirectedFrom); _viewModel = new SettingsViewModel( Ioc.GetOrCreate <INavigationService>(), Ioc.GetOrCreate <ILanguageService>(), Ioc.GetOrCreate <ISvgIconService>(), Ioc.GetOrCreate <IThemeService>(), Ioc.GetOrCreate <IBaseUrlService>(), Ioc.GetOrCreate <ISettingsService>(), Ioc.GetOrCreate <IStoryBoardService>(), Ioc.GetOrCreate <IFeedbackService>(), Ioc.GetOrCreate <ICloudStorageClientFactory>(), Ioc.GetOrCreate <IFilePickerService>()); VueBindingShortcut[] shortcuts = new[] { new VueBindingShortcut(VueBindingShortcut.KeyEscape, nameof(SettingsViewModel.GoBackCommand)), }; VueBindings = new VueDataBinding(_viewModel, View, shortcuts); _viewModel.VueDataBindingScript = VueBindings.BuildVueScript(); VueBindings.StartListening(); string html = _viewService.GenerateHtml(_viewModel); View.LoadHtml(html); }
/// <inheritdoc/> public override void ShowInView(IHtmlView htmlView, KeyValueList <string, string> variables, Navigation redirectedFrom) { base.ShowInView(htmlView, variables, redirectedFrom); IStoryBoardService storyBoardService = Ioc.GetOrCreate <IStoryBoardService>(); SerializeableCloudStorageCredentials credentials = storyBoardService.ActiveStory.LoadFromSession <SerializeableCloudStorageCredentials>(SynchronizationStorySessionKey.CloudStorageCredentials); _viewModel = new CloudStorageAccountViewModel( Ioc.GetOrCreate <INavigationService>(), Ioc.GetOrCreate <ILanguageService>(), Ioc.GetOrCreate <ISvgIconService>(), Ioc.GetOrCreate <IThemeService>(), Ioc.GetOrCreate <IBaseUrlService>(), storyBoardService, Ioc.GetOrCreate <IFeedbackService>(), Ioc.GetOrCreate <ICloudStorageClientFactory>(), credentials); VueBindingShortcut[] shortcuts = new[] { new VueBindingShortcut(VueBindingShortcut.KeyEscape, nameof(CloudStorageAccountViewModel.CancelCommand)), new VueBindingShortcut(VueBindingShortcut.KeyEnter, nameof(CloudStorageAccountViewModel.OkCommand)), }; VueBindings = new VueDataBinding(_viewModel, View, shortcuts); _viewModel.VueDataBindingScript = VueBindings.BuildVueScript(); VueBindings.StartListening(); string html = _viewService.GenerateHtml(_viewModel); View.LoadHtml(html); }
public void FillAssets(ref List <CustomAssetComponent> assets) { CustomAsset item; CustomAssetComponent comp; KeyValueList <string, CustomAsset> cahcer; string bundleName; int max = assets.Count; for (int i = 0; i < max; i++) { comp = assets[i]; if (comp != default) { bundleName = comp.GetBundleName(); cahcer = new KeyValueList <string, CustomAsset>(); mAssetsCacher.Add(cahcer); mBundleMapper[bundleName] = mAssetsCacher.Count - 1; int n = comp.Assets.Count; for (int j = 0; j < n; j++) { item = comp.Assets[j]; cahcer[item.assetName] = item; } } } }
public async void When_SettingStartType_Should_SetServiceStartMode() { var serviceName = "WinRM"; var values1 = new KeyValueList <string, string> { { "startType", "Automatic" } }; var values2 = new KeyValueList <string, string> { { "startType", "Disabled" } }; var values3 = new KeyValueList <string, string> { { "startType", "Manual" } }; var result1 = await _restApiClient.Post($"/api/winservices/{serviceName}/setStartType", values1); var serviceInfo1 = await GetService(serviceName); var result2 = await _restApiClient.Post($"/api/winservices/{serviceName}/setStartType", values2); var serviceInfo2 = await GetService(serviceName); var result3 = await _restApiClient.Post($"/api/winservices/{serviceName}/setStartType", values3); var serviceInfo3 = await GetService(serviceName); Assert.Equal(HttpStatusCode.OK, result1.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, result2.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, result3.Response.StatusCode); Assert.Equal("Auto", serviceInfo1.StartMode); Assert.Equal("Disabled", serviceInfo2.StartMode); Assert.Equal("Manual", serviceInfo3.StartMode); }
public override void Init(IShipDockComponentContext context) { base.Init(context); mArounds = new KeyValueList <int, List <int> >(); mPhysicsCheckable = new KeyValueList <int, bool>(); }
protected override KeyValueList <Grouping, IEnumerable <ParsedData> > GroupFields(IEnumerable <ParsedData> data) { Grouping g; var dates = data.Select(log => log.Log.Date); var start = dates.Min(); var end = dates.Max(); end = end.Add(data.Where(log => log.Log.Date.Equals(end)).First().Log.Duration); if (start.Date.Equals(end.Date)) { string en = $"Logs {start:HH':'mm} - {end:HH':'mm}"; string de = $"Logs {start:HH':'mm} - {end:HH':'mm}"; g = new Grouping(@"https://wiki.guildwars2.com/images/1/1f/Spirit_Vale_%28achievements%29.png", new NamedObject(en, de)); } else { string en = $"Logs {start:yyyy'-'MM'-'dd' 'HH':'mm} - {end:yyyy'-'MM'-'dd' 'HH':'mm}"; string de = $"Logs {start:dd'.'MM'.'yyy' 'HH':'mm} - {end:dd'.'MM'.'yyy' 'HH':'mm}"; g = new Grouping(@"https://wiki.guildwars2.com/images/1/1f/Spirit_Vale_%28achievements%29.png", new NamedObject(en, de)); } var list = new KeyValueList <Grouping, IEnumerable <ParsedData> > { { g, data } }; return(list); }
/// <summary> /// Used by OTHERKeyValueList.AddRange() /// This adds this list of values to the passed list. The keys are not copied over /// </summary> /// <param name="array">The list AddRange is being called on</param> /// <param name="arrayIndex"> /// The starting index for the copy operation. AddRange seems to pass the last index. /// </param> public void CopyTo(KeyValueList <K, V> otherKeyValueList, int index) { foreach (KeyValuePair <K, V> kvp in this) { otherKeyValueList[kvp.Key] = kvp.Value; } }
private void GetRepeatsVersionRes(ref List <ResVersion> repeates) { repeates = new List <ResVersion>(); KeyValueList <string, ResVersion> realMapper = new KeyValueList <string, ResVersion>(); foreach (var item in mRes) { if (realMapper.ContainsKey(item.name)) { if (realMapper[item.name].version >= item.version) { Debug.LogWarning("Repeate version item, name is " + item.name); repeates.Add(item); } else { realMapper[item.name] = item; } } else { realMapper[item.name] = item; } } }
public bool execute(ReconCOM rc, String[] argv) { try { int iRet; String user = argv.Length > 1 ? argv[1] : "System"; String sDestDN = argv.Length > 2 ? argv[2] : "0"; KeyValueList kvl = new KeyValueList(); rc.T_GetAttachedDataList(Program.CallID, out kvl); iRet = rc.T_ConsultCall(user, sDestDN, Program.CallID, kvl); System.Console.WriteLine(); if (iRet == (int)enErrorCode.E_SUCCESS) { return(true); } System.Console.WriteLine((enErrorCode)iRet); return(false); } catch (Exception ex) { System.Console.WriteLine("Exception: ", ex + " - " + ex.Message); return(false); } }
/// <summary> /// Triggers the <see cref="Notified"/> event. /// </summary> /// <param name="parameters">Argument passed from the view to the binding.</param> public void OnNotified(KeyValueList <string, string> parameters) { if (Notified != null) { Notified(parameters); } }
public async void When_PostingCopyActionWithoutSourcePath_Should_Return400AndValidationMessage() { using (var fs = new FsInitializer()) { fs.CreateItems( new DirItem("dir", new FileItem("1.txt"))); var values = new KeyValueList<string, string> { {"action", "COPY"}, {"destPath", Path.Combine(fs.TempPath, "dir/2.txt")} }; var result = await _restApiClient.Post("/api/fs", values); var jcontent = JParser.ParseContent(result.Content); Assert.Equal(HttpStatusCode.BadRequest, result.Response.StatusCode); Assert.NotNull(jcontent["ModelState"]["SourcePath"]); } }
public async void When_SettingStartTypeWithUnknownValue_Should_Return400AndValidationMessage() { var values = new KeyValueList<string, string> {{"startType", "unknown"}}; var result = await _restApiClient.Post("/api/winservices/WinRM/setStartType", values); var jcontent = JParser.ParseContent(result.Content); Assert.Equal(HttpStatusCode.BadRequest, result.Response.StatusCode); Assert.Equal("The request is invalid.", jcontent["Message"]); }
private async Task EnsureServiceIsNotDisabled(string serviceName) { var service = await GetService(serviceName); if (service.StartMode == "Disabled") { var values = new KeyValueList<string, string> {{"startType", "Automatic"}}; await _restApiClient.Post($"/api/winservices/{serviceName}/setStartType", values); } }
public static string GetDisplayValue(object value, string type, KeyValueList<string, string> typeHints, Option[] options) { string text; try { var format = typeHints["DisplayFormat"]; switch (type) { case DataTypes.Time: case DataTypes.NullableTime: { if (value != null) { var time = (TimeSpan)value; text = string.Format(CultureInfo.CurrentCulture, format ?? "{0:" + CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern + "}", new DateTime(1, 1, 1, time.Hours, time.Minutes, time.Seconds, time.Milliseconds)); } else text = string.Empty; break; } case DataTypes.Date: case DataTypes.NullableDate: text = value != null ? string.Format(CultureInfo.CurrentCulture, format ?? "{0:" + CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern.Replace("dddd", null).Trim(',', ' ') + "}", value) : string.Empty; break; case DataTypes.DateTime: case DataTypes.NullableDateTime: text = value != null ? string.Format(CultureInfo.CurrentCulture, format ?? "{0:" + CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern.Replace("dddd", null).Trim(',', ' ') + " " + CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern + "}", value) : string.Empty; break; case DataTypes.DateTimeOffset: case DataTypes.NullableDateTimeOffset: text = value != null ? string.Format(CultureInfo.CurrentCulture, format ?? "{0:" + CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern.Replace("dddd", null).Trim(',', ' ') + " " + CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern + " (UTCzzz)}", value) : string.Empty; break; case DataTypes.Boolean: case DataTypes.NullableBoolean: text = value != null ? Service.Current.Messages[((bool)value) ? (typeHints["TrueKey"] ?? "True") : (typeHints["FalseKey"] ?? "False")] : string.Empty; break; case DataTypes.YesNo: text = value != null ? Service.Current.Messages[((bool)value) ? (typeHints["TrueKey"] ?? "Yes") : (typeHints["FalseKey"] ?? "No")] : string.Empty; break; case DataTypes.KeyValueList: text = Convert.ToString(value); if (options != null && options.Length > 0) { foreach (var option in options.Where(option => (option.Key) == text)) { text = option.DisplayValue; break; } } break; case DataTypes.BinaryFile: { var str = (value as String) ?? string.Empty; text = str.Split('|').FirstOrDefault(); } break; default: text = value != null ? string.Format(CultureInfo.CurrentCulture, format ?? "{0}", value) : string.Empty; break; } } catch { text = value != null ? value.ToString() : string.Empty; } return text; }
public async void When_CopyingAlreadyExistingDirectoryWithOverwriteSetToTrue_Should_CopyEntireDirectory() { using (var fs = new FsInitializer()) { fs.CreateItems( new DirItem("dir1", new DirItem("subdir"), new FileItem("1.txt", "source_content")), new DirItem("dir2", new DirItem("subdir"), new DirItem("subdir2"), new FileItem("1.txt", "dest_content"))); var values = new KeyValueList<string, string> { {"action", "COPY"}, {"sourcePath", Path.Combine(fs.TempPath, "dir1")}, {"destPath", Path.Combine(fs.TempPath, "dir2")}, {"overwrite", "true"} }; var result = await _restApiClient.Post("/api/fs", values); Assert.Equal(HttpStatusCode.OK, result.Response.StatusCode); Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir2"))); Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir2\\subdir"))); Assert.False(Directory.Exists(Path.Combine(fs.TempPath, "dir2\\subdir2"))); Assert.True(File.Exists(Path.Combine(fs.TempPath, "dir2\\1.txt"))); Assert.Equal("source_content", File.ReadAllText(Path.Combine(fs.TempPath, "dir2\\1.txt"))); } }
public async void When_SettingStartType_Should_SetServiceStartMode() { var serviceName = "WinRM"; var values1 = new KeyValueList<string, string> {{"startType", "Automatic"}}; var values2 = new KeyValueList<string, string> {{"startType", "Disabled"}}; var values3 = new KeyValueList<string, string> {{"startType", "Manual"}}; var result1 = await _restApiClient.Post($"/api/winservices/{serviceName}/setStartType", values1); var serviceInfo1 = await GetService(serviceName); var result2 = await _restApiClient.Post($"/api/winservices/{serviceName}/setStartType", values2); var serviceInfo2 = await GetService(serviceName); var result3 = await _restApiClient.Post($"/api/winservices/{serviceName}/setStartType", values3); var serviceInfo3 = await GetService(serviceName); Assert.Equal(HttpStatusCode.OK, result1.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, result2.Response.StatusCode); Assert.Equal(HttpStatusCode.OK, result3.Response.StatusCode); Assert.Equal("Auto", serviceInfo1.StartMode); Assert.Equal("Disabled", serviceInfo2.StartMode); Assert.Equal("Manual", serviceInfo3.StartMode); }
protected override void OnFormClosed(FormClosedEventArgs e) { switch (e.CloseReason) { case CloseReason.TaskManagerClosing: case CloseReason.ApplicationExitCall: case CloseReason.WindowsShutDown: break; default: if (this.cmbTemplate.Modified) { KeyValueList<string, ListViewColumnInfo[]> list = new KeyValueList<string, ListViewColumnInfo[]>(); list.AddRange(this.cmbTemplate.GetItems<ListViewColumnInfo[]>()); Settings.Default.ColumnTemplates = (list.Count > 0) ? list : null; } break; } base.OnFormClosed(e); }
public KeyValueList SignOut() { FormsAuthentication.SignOut(); var results = new KeyValueList(); results.Add("Status", true); results.Add("Message", "Good bye!"); return results; }
public async void When_CopyingExistingFile_Should_CopyIt() { using (var fs = new FsInitializer()) { fs.CreateItems( new DirItem("dir", new FileItem("1.txt", "Hello Test"))); var sourcePath = Path.Combine(fs.TempPath, "dir/1.txt"); var destPath = Path.Combine(fs.TempPath, "dir/2.txt"); var values = new KeyValueList<string, string> { {"action", "COPY"}, {"sourcePath", sourcePath}, {"destPath", destPath} }; Assert.False(File.Exists(destPath)); var result = await _restApiClient.Post("/api/fs", values); Assert.Equal(HttpStatusCode.OK, result.Response.StatusCode); Assert.True(File.Exists(sourcePath)); Assert.True(File.Exists(destPath)); Assert.Equal(File.ReadAllText(destPath), "Hello Test"); } }
internal PersistentObject(JObject model) : base(model) { JToken attributesToken; if (model.TryGetValue("attributes", out attributesToken)) { var attributes = (JArray)attributesToken; Attributes = attributes.Select(jAttr => jAttr["lookup"] != null ? new PersistentObjectAttributeWithReference((JObject)jAttr, this) : new PersistentObjectAttribute((JObject)jAttr, this)).ToArray(); } else Attributes = new PersistentObjectAttribute[0]; JToken queriesToken; if (model.TryGetValue("queries", out queriesToken)) { var queries = (JArray)queriesToken; Queries = new KeyValueList<string, Query>(queries.Select(jQuery /* :-) */ => Service.Current.Hooks.OnConstruct((JObject)jQuery, this, false)).ToDictionary(q => q.Name, q => q)); } else Queries = new KeyValueList<string, Query>(new Dictionary<string, Query>()); var parent = (JObject)model["parent"]; if (parent != null) Parent = Service.Current.Hooks.OnConstruct(parent); // Initialize Tabs and Groups var tabIndex = 0; var attributeTabs = !IsHidden ? Attributes.OrderBy(attr => attr.Offset).GroupBy(attr => attr.Tab).Select(tab => { var groups = tab.OrderBy(attr => attr.Offset).GroupBy(attr => attr.GroupName).Select(group => new PersistentObjectAttributeGroup(group.Key, group.ToArray())).ToArray(); if (groups.Length == 1) groups[0].IsNameVisible = false; var t = (PersistentObjectTab)CreateAttributesTab(groups.SelectMany(g => g.Attributes).ToArray(), string.IsNullOrEmpty(tab.Key) ? Label : tab.Key, this); t.Index = tabIndex++; return t; }) : new PersistentObjectTabAttributes[0]; Tabs = attributeTabs.Concat(Queries.OrderBy(q => q.Value.Offset).Select(q => CreateQueryTab(q.Value))).ToList(); if (!IsHidden) { // Initialize Action JToken actionsToken; if (model.TryGetValue("actions", out actionsToken)) { var actions = ActionBase.GetActions(actionsToken, this); Actions = actions.Where(a => !a.IsPinned).ToArray(); PinnedActions = actions.Where(a => a.IsPinned).ToArray(); Actions.Run(a => a.Initialize()); PinnedActions.Run(a => a.Initialize()); } else Actions = PinnedActions = new ActionBase[0]; } else Actions = PinnedActions = new ActionBase[0]; // Also check IsInEdit (Object could have been reconstructed after suspend/resume) IsInEdit = IsInEdit || IsNew || StateBehavior.HasFlag(StateBehavior.OpenInEdit) || StateBehavior.HasFlag(StateBehavior.StayInEdit); IsDirty = IsDirty; // Also triggers reconstructed changes // Specials HasNotification = !string.IsNullOrWhiteSpace(Notification); Service.Current.Hooks.OnConstruct(this); Tabs.Select((tab, n) => tab.Index = n).Run(); }
public async void When_CopyingDirectoryByUNCPath_Should_CopyEntireDirectory() { using (var fs = new FsInitializer()) { fs.CreateItems( new DirItem("dir", new DirItem("subdir", new FileItem("2.txt")), new FileItem("1.txt"))); var uncTempPath = fs.TempPath.Replace(@"C:\", @"\\localhost\C$\"); var sourcePath = Path.Combine(uncTempPath, "dir"); var destPath = Path.Combine(uncTempPath, "dir2"); var values = new KeyValueList<string, string> { {"action", "COPY"}, {"sourcePath", sourcePath}, {"destPath", destPath} }; Assert.False(Directory.Exists(Path.Combine(fs.TempPath, "dir2"))); var result = await _restApiClient.Post("/api/fs", values); Assert.Equal(HttpStatusCode.OK, result.Response.StatusCode); // verify source Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir"))); Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir\\subdir"))); Assert.True(File.Exists(Path.Combine(fs.TempPath, "dir\\subdir\\2.txt"))); Assert.True(File.Exists(Path.Combine(fs.TempPath, "dir\\1.txt"))); // verify destination Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir2"))); Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir2\\subdir"))); Assert.True(File.Exists(Path.Combine(fs.TempPath, "dir2\\subdir\\2.txt"))); Assert.True(File.Exists(Path.Combine(fs.TempPath, "dir2\\1.txt"))); } }
public KeyValueList SignIn(string username, string password) { string errorMessage = string.Empty; if (password.Length == 0) errorMessage = "Please enter password"; if (username.Length == 0) errorMessage = "Please enter user name"; if (errorMessage.Length == 0) { // Here must be validation with password. You can add third party validation here; bool success = Membership.ValidateUser(username, password); if (!success) errorMessage = "Validation failed. User name '" + username + "' was not found."; } var results = new KeyValueList(); if (errorMessage.Length > 0) { results.Add("Status", false); results.Add("Message", errorMessage); } else { FormsAuthentication.Initialize(); var user = Membership.GetUser(username, true); if (user == null) { results.Add("Status", false); results.Add("Message", "'" + username + "' was not found."); } else { var roles = Roles.GetRolesForUser(username); string rolesString = string.Empty; for (int i = 0; i < roles.Length; i++) { if (i > 0) rolesString += ","; rolesString += roles[i]; } var loginRememberMinutes = 30; var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath); // Encrypt the cookie using the machine key for secure transport. var hash = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); // Hashed ticket // Set the cookie's expiration time to the tickets expiration time if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; HttpContext.Current.Response.Cookies.Add(cookie); // Create Identity. var identity = new System.Security.Principal.GenericIdentity(user.UserName); // Create Principal. var principal = new RolePrincipal(identity); System.Threading.Thread.CurrentPrincipal = principal; // Create User. HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles); results.Add("Status", true); results.Add("Message", "Welcome!"); } } return results; }
public async void When_CopyingEmptyDirectory_Should_CopyIt() { using (var fs = new FsInitializer()) { fs.CreateItems(new DirItem("dir")); var values = new KeyValueList<string, string> { {"action", "COPY"}, {"sourcePath", Path.Combine(fs.TempPath, "dir")}, {"destPath", Path.Combine(fs.TempPath, "dir2")} }; Assert.False(Directory.Exists(Path.Combine(fs.TempPath, "dir2"))); var result = await _restApiClient.Post("/api/fs", values); Assert.Equal(HttpStatusCode.OK, result.Response.StatusCode); Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir2"))); } }
public async void When_CopyingNonExistingFile_Should_Return404() { using (var fs = new FsInitializer()) { var sourcePath = Path.Combine(fs.TempPath, "non_existing.txt"); var destPath = Path.Combine(fs.TempPath, "dir/2.txt"); var values = new KeyValueList<string, string> { {"action", "COPY"}, {"sourcePath", sourcePath}, {"destPath", destPath} }; Assert.False(File.Exists(destPath)); var result = await _restApiClient.Post("/api/fs", values); Assert.Equal(HttpStatusCode.NotFound, result.Response.StatusCode); Assert.False(File.Exists(sourcePath)); Assert.False(File.Exists(destPath)); } }
public async void When_CopyingAlreadyExistingDirectoryWithoutOverwrite_Should_Return500AndNotChangeDestination() { using (var fs = new FsInitializer()) { fs.CreateItems( new DirItem("dir1", new DirItem("subdir"), new FileItem("1.txt", "source_content")), new DirItem("dir2", new DirItem("subdir"), new FileItem("1.txt", "dest_content"))); var values = new KeyValueList<string, string> { {"action", "COPY"}, {"sourcePath", Path.Combine(fs.TempPath, "dir1")}, {"destPath", Path.Combine(fs.TempPath, "dir2")} }; var result = await _restApiClient.Post("/api/fs", values); var jcontent = JParser.ParseContent(result.Content); Assert.Equal(HttpStatusCode.InternalServerError, result.Response.StatusCode); Assert.Equal("System.IO.IOException", jcontent["ExceptionType"]); Assert.NotNull(jcontent["ExceptionMessage"]); Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir2"))); Assert.True(Directory.Exists(Path.Combine(fs.TempPath, "dir2\\subdir"))); Assert.True(File.Exists(Path.Combine(fs.TempPath, "dir2\\1.txt"))); Assert.Equal("dest_content", File.ReadAllText(Path.Combine(fs.TempPath, "dir2\\1.txt"))); } }
private async Task<PersistentObject> SignInAsync(string user, string password, string token = null, string accessToken = null, string serviceProvider = null) { try { IsBusy = true; var data = CreateData(user, token); if (string.IsNullOrEmpty(accessToken)) { if (password != null) { data["password"] = password; data.Remove("authToken"); } } else { data.Remove("userName"); data.Remove("authToken"); data["accessToken"] = accessToken; data["serviceProvider"] = serviceProvider; } var response = await PostAsync("GetApplication", data); var ex = (string)response["exception"] ?? (string)response["ExceptionMessage"]; if (!string.IsNullOrEmpty(ex)) throw new Exception(ex); var po = Hooks.OnConstruct((JObject)response["application"]); if (po.FullTypeName == "Vidyano.Error" || !string.IsNullOrEmpty(po.Notification)) throw new Exception(po.Notification); User = (string)response["userName"] ?? user; UserPicture = await Hooks.UserPictureFromUrl((string)response["userPicture"]); AuthToken = (string)response["authToken"]; Application = po; var cultureInfo = new CultureInfo(Application["Culture"].ValueDirect); CultureInfo.DefaultThreadCurrentCulture = cultureInfo; CultureInfo.DefaultThreadCurrentUICulture = cultureInfo; Messages = new KeyValueList<string, string>(Application.Queries["ClientMessages"].ToDictionary(item => (string)item["Key"], item => (string)item["Value"]), true); Actions = Application.Queries["Actions"].ToDictionary(item => (string)item["Name"], item => new ActionBase.Definition { Name = (string)item["Name"], DisplayName = (string)item["DisplayName"], IsPinned = (bool)item["IsPinned"], RefreshQueryOnCompleted = (bool)item["RefreshQueryOnCompleted"], Offset = (int)item["Offset"], Options = ((string)item["Options"] ?? string.Empty).Trim().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(str => str.Trim()).ToArray(), SelectionRule = ExpressionParser.Get((string)item["SelectionRule"]) }); await UpdateSession(response); var bulkEdit = Actions["BulkEdit"]; bulkEdit.SelectionRule = ExpressionParser.Get("=1"); } finally { IsBusy = false; } IsConnected = true; await Hooks.OnInitialized(); return Application; }
public async void When_CopyingFileToAlreadyExistingPathWithoutOverwrite_Should_Return500AndExceptionMessage() { using (var fs = new FsInitializer()) { fs.CreateItems( new DirItem("dir", new FileItem("1.txt"), new FileItem("2.txt"))); var sourcePath = Path.Combine(fs.TempPath, "dir/1.txt"); var destPath = Path.Combine(fs.TempPath, "dir/2.txt"); var values = new KeyValueList<string, string> { {"action", "COPY"}, {"sourcePath", sourcePath}, {"destPath", destPath} }; var result = await _restApiClient.Post("/api/fs", values); var jcontent = JParser.ParseContent(result.Content); Assert.Equal(HttpStatusCode.InternalServerError, result.Response.StatusCode); Assert.True(File.Exists(destPath)); Assert.Equal("System.IO.IOException", jcontent["ExceptionType"]); Assert.NotNull(jcontent["ExceptionMessage"]); } }