public void InitValidate() { var number = new Validate<int>(10, i => i < 20, false); Assert.AreEqual(number.Value, 10); number.Value = 30; Assert.AreNotEqual(number.Value, 30); Assert.AreEqual(number.Value, 10); number = 140.ToValidate(x => x == 140); Assert.AreEqual(number.Value, 140); }
public static ValidSetOfPointsCollection ForEachSet(this ValidSetOfPointsCollection self, Validate validateMethod) { ValidSetOfPointsCollection validSets = new ValidSetOfPointsCollection(); foreach (var item in self) { ValidSetOfPointsCollection list = validateMethod(item); foreach (var set in list) { validSets.Add(set); } } return validSets; }
public Compile_files(Crawl_directory_tree crawlDirTree) { var split = new Split<Tuple<string, string>, string, string>( t => t.Item2, t => t.Item1 ); var validatePath = new Validate<string>( Directory.Exists, path => string.Format("Diretory to be indexed not found: {0}", path) ); this.in_Process = _ => split.Input(_); split.Output1 += validatePath.In_Validate; validatePath.Out_ValidData += crawlDirTree.In_Process; validatePath.Out_InvalidData += _ => this.Out_ValidationError(_); split.Output0 += _ => this.Out_IndexFilename(_); crawlDirTree.Out_FileFound += _ => this.Out_FileFound(_); }
internal bool Verify() { if (!this.resultPosWasSet) { return(true); } Validate.IsFalse(IsNewHierarchy, "Hierarchy roots should not set expected positions"); if (!IsEmpty) { if ((this.MinimumSizeX - this.SizeX) >= MaxAllowedDiff) { return(false); } if ((this.MinimumSizeY - this.SizeY) >= MaxAllowedDiff) { return(false); } } if (MaxAllowedDiff <= Math.Abs(this.Left - this.LeftResultPos)) { return(false); } if (MaxAllowedDiff <= Math.Abs(this.Right - this.RightResultPos)) { return(false); } if (MaxAllowedDiff <= Math.Abs(this.Top - this.TopResultPos)) { return(false); } if (MaxAllowedDiff <= Math.Abs(this.Bottom - this.BottomResultPos)) { return(false); } return(true); }
private static async Task <TData> JsonInternal <TData>(IHttpContext context, JsonSerializerCase jsonSerializerCase) { Validate.NotNull(nameof(context), context); string body; using (var reader = context.OpenRequestText()) { body = await reader.ReadToEndAsync().ConfigureAwait(false); } try { return(Swan.Formatters.Json.Deserialize <TData>(body, jsonSerializerCase)); } catch (FormatException) { $"[{context.Id}] Cannot convert JSON request body to {typeof(TData).Name}, sending 400 Bad Request..." .Warn($"{nameof(RequestDeserializer)}.{nameof(Json)}"); throw HttpException.BadRequest("Incorrect request data format."); } }
public PlayerPreference GetPreference(string ipAddress) { Validate.NotNull(ipAddress); PlayerPreference preference; if (state.Preferences.TryGetValue(ipAddress, out preference)) { return(preference.Clone()); } if (state.LastSetPlayerPreference != null) { return(state.LastSetPlayerPreference.Clone()); } Color playerColor = RandomColorGenerator.GenerateColor(); PlayerPreference defaultPlayerPreference = new PlayerPreference(playerColor); state.LastSetPlayerPreference = defaultPlayerPreference; return(defaultPlayerPreference); }
public void SetPreference(string ipAddress, PlayerPreference playerPreference) { Validate.NotNull(ipAddress); Validate.NotNull(playerPreference); if (state.Preferences.ContainsKey(ipAddress)) { PlayerPreference currentPreference = state.Preferences[ipAddress]; if (currentPreference.Equals(playerPreference)) { return; } state.Preferences[ipAddress] = playerPreference; state.LastSetPlayerPreference = playerPreference; return; } state.Preferences.Add(ipAddress, playerPreference); state.LastSetPlayerPreference = playerPreference; }
public override void Process(PlayerCinematicControllerCall packet) { Optional <GameObject> opEntity = NitroxEntity.GetObjectFrom(packet.ControllerID); Validate.IsPresent(opEntity); MultiplayerCinematicReference reference = opEntity.Value.GetComponent <MultiplayerCinematicReference>(); Validate.IsTrue(reference); Optional <RemotePlayer> opPlayer = playerManager.Find(packet.PlayerId); Validate.IsPresent(opPlayer); if (packet.StartPlaying) { reference.CallStartCinematicMode(packet.Key, packet.ControllerNameHash, opPlayer.Value); } else { reference.CallCinematicModeEnd(packet.Key, packet.ControllerNameHash, opPlayer.Value); } }
/// <summary> /// Defines a variable in the template context by initialising it /// </summary> /// <param name="context">The template context</param> /// <param name="variable">The variable code block</param> private void ReassignVariable ( ref TemplateContext context, VariableDeclaration variable ) { Validate.IsNotNull(variable); var variableName = variable.VariableName; var value = ResolveValue ( ref context, variable.AssignedValue, variable.ValueType ); context.ReassignVariable ( variableName, value ); }
public static async IAsyncEnumerable <IEnumerable <FileInfo> > LoadFilesAsync([NotNull] IEnumerable <DirectoryInfo> directories, [NotNull] string searchPattern, SearchOption searchOption) { Validate.TryValidateParam(searchOption, nameof(searchOption)); var options = new EnumerationOptions() { IgnoreInaccessible = true }; if (searchOption == SearchOption.AllDirectories) { options.RecurseSubdirectories = true; } var validDirectories = directories.Where(directory => directory.Exists).Select(directory => directory).ToList(); foreach (var directory in validDirectories) { var files = await Task.Run(() => directory.EnumerateFiles(searchPattern, options)).ConfigureAwait(false); yield return(files); } }
public async Task RegisterHostAsync(Cluster cluster, HostInfo host) { Validate.NotNull(cluster, nameof(cluster)); Validate.NotNull(host, nameof(host)); // - Register to any attached load balancers if (cluster.Properties.TryGetValue(ClusterProperties.TargetGroupArn, out var targetGroupArnNode)) { var registration = new RegisterTargetsRequest( targetGroupArn: targetGroupArnNode, targets: new[] { new TargetDescription(id: host.ResourceId) } ); // Register the instances with the lb's target group await elbClient.RegisterTargetsAsync(registration); await eventLog.CreateAsync(new Event( action : "c", resource : "borg:host/" + host.Id )); } }
/// <summary> /// Executes an SQL query against the database /// </summary> /// <param name="connectionString">The connection string</param> /// <param name="sql">The query to execute</param> /// <returns>The data returned by the query</returns> public IDataGrid ExecuteQuery ( string connectionString, string sql ) { Validate.IsNotEmpty(connectionString); Validate.IsNotEmpty(sql); using (var connection = new SqlConnection(connectionString)) { using (var command = new SqlCommand(sql, connection)) { command.CommandType = CommandType.Text; connection.Open(); using (var reader = command.ExecuteReader()) { return(ReadToGrid(reader)); } } } }
private void DeserializeComponents(Stream stream, GameObject gameObject) { LoopHeader components = serializer.Deserialize <LoopHeader>(stream); for (int componentCounter = 0; componentCounter < components.Count; componentCounter++) { ComponentHeader componentHeader = serializer.Deserialize <ComponentHeader>(stream); if (!surrogateTypes.TryGetValue(componentHeader.TypeName, out Type type)) { type = AppDomain.CurrentDomain.GetAssemblies() .Select(a => a.GetType(componentHeader.TypeName)) .FirstOrDefault(t => t != null); } Validate.NotNull(type, $"No type or surrogate found for {componentHeader.TypeName}!"); object component = FormatterServices.GetUninitializedObject(type); serializer.Deserialize(stream, component, type); gameObject.AddComponent(component, type); } }
/// <summary> /// Defines a single query column /// </summary> /// <param name="tableName">The table name</param> /// <param name="columnName">The column name</param> /// <param name="valueType">The column value type</param> protected void DefineColumn ( string tableName, string columnName, Type valueType ) { Validate.IsNotEmpty(tableName); Validate.IsNotEmpty(columnName); Validate.IsNotNull(valueType); var columnSchema = new DataColumnSchema ( columnName, valueType ); DefineColumn ( tableName, columnSchema ); }
/// <summary> /// Deserializes the specified windows manager from the stream. /// </summary> /// <param name="stream">The stream.</param> /// <param name="windowsManager">The windows manager.</param> /// <exception cref="ArgumentNullException">stream or windowsManager are null</exception> /// <exception cref="InvalidOperationException">stream is not readable</exception> public void Deserialize(Stream stream, WindowsManager windowsManager) { Validate.NotNull(stream, "stream"); Validate.NotNull(windowsManager, "windowsManager"); Validate.Assert <InvalidOperationException>(stream.CanRead); _dockedWindows = new Dictionary <Dock, DockedWindows>(); _floatingWindows = new List <DockPane>(); _rootContainer = null; DockPositions.ForEach(dock => _dockedWindows[dock] = new DockedWindows()); // Initialize stream InitializeStream(stream); // Navigate windows manager NavigateWindowsManager(); // Finalize deserialization FinalizeDeserialization(); // Transfer contents to windows manager TransferWindowsManagerContents(windowsManager); }
public static ServiceSettings LoadDefault(string path, string slot, string location, string subscription, string storageAccountName, string suppliedServiceName, string serviceDefinitionName, out string serviceName) { ServiceSettings local; ServiceSettings defaultServiceSettings = new ServiceSettings(); if (string.IsNullOrEmpty(path)) { local = new ServiceSettings(); } else { Validate.ValidateFileFull(path, Resources.ServiceSettings); local = Load(path); } defaultServiceSettings._slot = GetDefaultSlot(local.Slot, null, slot); defaultServiceSettings._location = GetDefaultLocation(local.Location, location); defaultServiceSettings._subscription = GetDefaultSubscription(local.Subscription, subscription); serviceName = GetServiceName(suppliedServiceName, serviceDefinitionName); defaultServiceSettings._storageAccountName = GetDefaultStorageName(local.StorageAccountName, null, storageAccountName, serviceName).ToLower(); return(defaultServiceSettings); }
private void okButton_Click(object sender, EventArgs e) { var validator = new Validate(); validator.Key = keyTextBox.Text; if(validator.IsValid) { if(validator.IsExpired) { RadMessageBox.Show(LanguageManager._("Your Beta-Key is expired!!")); } else { Workspace.Settings.Add("BetaAccepted", true); _mainFrm.Show(); Hide(); } } else { RadMessageBox.Show(LanguageManager._("Your Beta-Key is invalid!!")); } }
private void WriteIfFreePort(Port port) { // Skip this port if we've already processed it. if (portToIdMap.ContainsKey(port)) { return; } int shapeId = FreePortShapeId; if (port is RelativeFloatingPort) { Shape shape; if ((null == this.freeRelativePortToShapeMap) || !this.freeRelativePortToShapeMap.TryGetValue(port, out shape)) { Validate.Fail("Relative FreePorts must be in FreeRelativePortToShapeMap"); return; } shapeId = shapeToIdMap[shape]; } portToIdMap.Add(port, NextPortId); WritePort(port, shapeId); }
/// <summary> /// Asynchronously executes the aggregate query and computes the result /// </summary> /// <param name="query">The query to execute</param> /// <param name="parameters">The parameter values</param> /// <returns>The result computed</returns> public virtual async Task <double> ExecuteAsync ( IQuery query, params ParameterValue[] parameters ) { Validate.IsNotNull(query); var queryTask = query.ExecuteAsync ( parameters ); var results = await queryTask.ConfigureAwait ( false ); return(Execute ( results.AllRows )); }
public static IEnumerable <CodeInstruction> Transpiler(MethodBase original, IEnumerable <CodeInstruction> instructions) { Validate.NotNull(INJECTION_OPERAND); foreach (CodeInstruction instruction in instructions) { yield return(instruction); if (instruction.opcode.Equals(INJECTION_OPCODE) && instruction.operand.Equals(INJECTION_OPERAND)) { /* * Multiplayer.Logic.Building.DeconstructionBegin(constructable.gameObject); */ yield return(TranspilerHelper.LocateService <Building>()); yield return(original.Ldloc <Constructable>()); yield return(new ValidatedCodeInstruction(OpCodes.Callvirt, typeof(Component).GetMethod("get_gameObject", BindingFlags.Instance | BindingFlags.Public))); yield return(new ValidatedCodeInstruction(OpCodes.Callvirt, typeof(Building).GetMethod("DeconstructionBegin", BindingFlags.Public | BindingFlags.Instance))); } } }
public static void CanRemove(LanguagesConfig languages, RemoveLanguage command) { Guard.NotNull(command, nameof(command)); Validate.It(e => { var language = command.Language; if (language == null) { e(Not.Defined(nameof(command.Language)), nameof(command.Language)); } else { EnsureConfigExists(languages, language); if (languages.IsMaster(language)) { e(T.Get("apps.languages.masterLanguageNotRemovable")); } } }); }
internal static void SetLockAndCommandTimeout(IDbConnection conn) { Validate.IsNotNull(nameof(conn), conn); // Make sure we use the underlying connection as ReliableConnection.Open also calls // this method ReliableSqlConnection reliableConn = conn as ReliableSqlConnection; if (reliableConn != null) { conn = reliableConn._underlyingConnection; } const string setLockTimeout = @"set LOCK_TIMEOUT {0}"; using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandText = string.Format(CultureInfo.InvariantCulture, setLockTimeout, AmbientSettings.LockTimeoutMilliSeconds); cmd.CommandType = CommandType.Text; cmd.CommandTimeout = CachedServerInfo.Instance.GetQueryTimeoutSeconds(conn); cmd.ExecuteNonQuery(); } }
/// <inheritdoc /> /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection{T}" /> to an /// <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied /// from <see cref="T:System.Collections.Generic.ICollection{T}" />. The <see cref="T:System.Array" /> must have /// zero-based indexing. /// </param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="array" /> is <c>null</c>.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// Thrown if the destination <paramref name="array" /> does not have enough /// space to hold the contents of the set. /// </exception> public void CopyTo(int[] array, int arrayIndex) { Validate.ArgumentNotNull(nameof(array), array); Validate.ArgumentGreaterThanOrEqualToZero(nameof(arrayIndex), arrayIndex); Validate.ArgumentGreaterThanOrEqualTo(nameof(arrayIndex), array.Length - arrayIndex, Count); for (var ci = 0; ci < _chunks.Length; ci++) { var chunk = _chunks[ci]; for (var bi = 0; bi < BitsPerChunk && chunk != 0; bi++) { if (bi > 0) { chunk >>= 1; } if (chunk % 2 == 1) { array[arrayIndex++] = _min + ci * BitsPerChunk + bi; } } } }
/// <summary> /// Gets a collection of category assignments for a report /// </summary> /// <param name="reportName">The report name</param> /// <returns>A collection of report category assignments</returns> public IEnumerable <ReportCategoryAssignment> GetCategoryAssignments ( string reportName ) { Validate.IsNotEmpty(reportName); var set = _context.Set <ReportCategoryAssignment>(); var assignments = set.Where ( a => a.ReportName.Equals ( reportName, StringComparison.OrdinalIgnoreCase ) ); return(assignments.OrderBy ( a => a.Category.Name )); }
public static void CanUpdate(Roles roles, UpdateRole command) { Guard.NotNull(command); CheckRoleExists(roles, command.Name); Validate.It(() => "Cannot delete role.", e => { if (string.IsNullOrWhiteSpace(command.Name)) { e(Not.Defined("Name"), nameof(command.Name)); } else if (Roles.IsDefault(command.Name)) { e("Cannot update a default role."); } if (command.Permissions == null) { e(Not.Defined("Permissions"), nameof(command.Permissions)); } }); }
public Validate ValidateUpdate(Candidate entity) { Validate valid = new Validate(); if (entity.Id > 0) { DataTable dt = GetById(entity.Id); valid.IsValid = dt.Rows.Count > 0; if (valid.IsValid && !string.IsNullOrEmpty(entity.Name)) { DataTable dt2 = GetByNameAndId(entity); valid.IsValid = !(dt2.Rows.Count > 0); valid.Message = !valid.IsValid ? "Já existe um item com mesma descrição." : "Item não encontrado"; } else { valid.Message = dt.Rows.Count > 0 ? "Esse item já existe." : "Item não encontrado."; } } return(valid); }
public void NullReferenceException_Test() { var customer = new Customer(); Validate .That(customer).IsNotNull("customer should not be null") .AndSelect(x => customer.Address) .Fulfills(x => x.Postcode.Length > 3, "length of postcode should be at least 4", x => "postcode cannot be null") .Result .Match( x => Assert.True(false), err => Assert.Equal(new[] { "postcode cannot be null" }, err) ); Validate .That((Customer)null).IsNotNull("not null") .And.Fulfills(x => x.Address != null, "address not null", x => "address field should be accessible") // should cause exception that will be caught .Result .Match( x => Assert.True(false), err => Assert.Equal(new[] { "not null", "address field should be accessible" }, err) ); }
/// <summary> /// Calculates the zero-based character offset of a given /// line and column position in the file. /// </summary> /// <param name="lineNumber">The 1-based line number from which the offset is calculated.</param> /// <param name="columnNumber">The 1-based column number from which the offset is calculated.</param> /// <returns>The zero-based offset for the given file position.</returns> public int GetOffsetAtPosition(int lineNumber, int columnNumber) { Validate.IsWithinRange("lineNumber", lineNumber, 1, FileLines.Count); Validate.IsGreaterThan("columnNumber", columnNumber, 0); int offset = 0; for (int i = 0; i < lineNumber; i++) { if (i == lineNumber - 1) { // Subtract 1 to account for 1-based column numbering offset += columnNumber - 1; } else { // Add an offset to account for the current platform's newline characters offset += FileLines[i].Length + Environment.NewLine.Length; } } return(offset); }
/// <summary> /// Returns an individual HTTP Header value /// </summary> /// <param name="request">The HTTP request message</param> /// <param name="key">The key of the header value to get</param> /// <returns>The header value found</returns> public static string GetHeader ( this HttpResponseMessage request, string key ) { Validate.IsNotNull(request); var headerFound = request.Headers.TryGetValues ( key, out var keys ); if (false == headerFound) { return(null); } else { return(keys.First()); } }
public static IEnumerable <CodeInstruction> Transpiler(MethodBase original, IEnumerable <CodeInstruction> instructions) { Validate.NotNull(INJECTION_OPERAND); foreach (CodeInstruction instruction in instructions) { yield return(instruction); /* * GameObject gameObject = global::Utils.CreatePrefab(prefabForTechType, maxDist, i > 0); * -> SpawnConsoleCommand_OnConsoleCommand_Patch.Callback(gameObject); * LargeWorldEntity.Register(gameObject); * CrafterLogic.NotifyCraftEnd(gameObject, techType); * gameObject.SendMessage("StartConstruction", SendMessageOptions.DontRequireReceiver); */ if (instruction.opcode == INJECTION_CODE && instruction.operand.Equals(INJECTION_OPERAND)) { yield return(new CodeInstruction(OpCodes.Dup)); yield return(new CodeInstruction(OpCodes.Call, typeof(SpawnConsoleCommand_OnConsoleCommand_Patch).GetMethod("Callback", BindingFlags.Static | BindingFlags.Public))); } } }
public unsafe void Button_Default_WithText_LineDrawing() { using Button button = new Button { Text = "Hello" }; using var emf = new EmfScope(); DeviceContextState state = new DeviceContextState(emf); Rectangle bounds = button.Bounds; button.PrintToMetafile(emf); emf.Validate( state, Validate.SkipType(Gdi32.EMR.BITBLT), Validate.TextOut("Hello"), Validate.LineTo((bounds.Right - 1, 0), (0, 0), SystemColors.ControlLightLight), Validate.LineTo((0, 0), (0, bounds.Bottom - 1), SystemColors.ControlLightLight), Validate.LineTo((0, bounds.Bottom - 1), (bounds.Right - 1, bounds.Bottom - 1), SystemColors.ControlDarkDark), Validate.LineTo((bounds.Right - 1, bounds.Bottom - 1), (bounds.Right - 1, -1), SystemColors.ControlDarkDark), Validate.LineTo((bounds.Right - 2, 1), (1, 1), SystemColors.Control), Validate.LineTo((1, 1), (1, bounds.Bottom - 2), SystemColors.Control), Validate.LineTo((1, bounds.Bottom - 2), (bounds.Right - 2, bounds.Bottom - 2), SystemColors.ControlDark), Validate.LineTo((bounds.Right - 2, bounds.Bottom - 2), (bounds.Right - 2, 0), SystemColors.ControlDark)); }
public void CreateTable(string tableName) { Validate .Begin() .IsNotNullOrEmpty(tableName) .Check(); if (!m_proxy.IsValidTableName(tableName)) { throw new ArgumentException("Invalid Table Name"); } if (DoesTableExist(tableName)) { throw new ArgumentException("Table already exists"); } // create m_proxy.CreateTable(tableName); // call a refresh to populate the ID and LastUpdate on the new table Refresh(); }
public IActionResult UpdateParty(int id, [FromBody] JsonPatchDocument <DomainParty> patchDoc) { var domainParty = _partyService.GetParty(id); Authorize.TokenAgainstResource(HttpContext.User, domainParty.CustomerId); Validate <DomainParty> .EmptyPatchRequest(patchDoc); Validate <DomainParty> .PatchRestrictedFields(patchDoc, _allowedPatchFields); patchDoc.ApplyTo(domainParty, ModelState); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var isNotifyRequest = ValidateNotifyRequest(domainParty, patchDoc); _partyService.UpdateParty(domainParty, isNotifyRequest); return(Ok()); }
public void FirmSettingsEmailBills() { bclient.MainForm.Self.Activate(); bclient.MainForm.sideBILLING.Click(); frm.MainForm.Self.Activate(); frm.MainForm.btnOffice.Click(); frm.MainForm.View.Click(); frm.MainForm.FirmSettings1.Click(); frm.MainForm.FirmSettingsForm.txtBillingEmailingBills.Click(); if (frm.BillingFirmSettingsForm.SelfInfo.Exists(5000)) { frm.BillingFirmSettingsForm.Self.Maximize(); Report.Success("Billing Abacus Payment Exchange form is displayed successfully."); Validate.AttributeContains(frm.BillingFirmSettingsForm.PnlBase.cmbbxEmailBehaviourInfo, "Text", "Send Bill E-mails to Draft Folder", "Email Behaviour Dropdown has the value Send Bill E-mails to Draft Folder"); Validate.Exists(frm.BillingFirmSettingsForm.PnlBase.cbAPXRequestTurnedOnForNewFilesInfo, " APX Request turned ON for new files is displayed as expected"); Validate.Exists(frm.BillingFirmSettingsForm.PnlBase.cbEMailBillsTurnedOnForNewFilesInfo, "Email Bills turned ON for new files is displayed as expected"); if (!frm.BillingFirmSettingsForm.PnlBase.cbEMailBillsTurnedOnForNewFiles.Checked) { frm.BillingFirmSettingsForm.PnlBase.cbEMailBillsTurnedOnForNewFiles.Click(); } if (!frm.BillingFirmSettingsForm.PnlBase.cbAPXRequestTurnedOnForNewFiles.Checked) { frm.BillingFirmSettingsForm.PnlBase.cbAPXRequestTurnedOnForNewFiles.Click(); } Report.Screenshot(); frm.BillingFirmSettingsForm.PnlBase.tabAPXURLFormat.Click(); Delay.Seconds(1); Validate.AttributeContains(frm.BillingFirmSettingsForm.PnlBase.txtBodyEmailInfo, "Text", "<<Billed Amount>>", "APX Email Template Text Body has the value <<Billed Amount>>"); Validate.AttributeContains(frm.BillingFirmSettingsForm.PnlBase.txtBodyEmailInfo, "Text", "<<PayNow URL>>", "APX Email Template Text Body has the value <<PayNow URL>>"); Delay.Seconds(1); frm.BillingFirmSettingsForm.Toolbar1.btnOK.Click(); } }
/// <summary> /// Validate 3 possible security levels for a request: ClientTag, AccessToken, UserCredentials, or All /// </summary> /// <remarks> /// validate can also be passed as a bitwise combination: /// Ex. Validate.ClientTag | Validate.AccessToken /// </remarks> protected bool ValidRequest(BaseRequest request, BaseResponse response, Validate validate) { if (request.ClientTag == MasterClientTag) return true;//bypass all security // Validate Client Tag. if ((Validate.ClientTag & validate) == Validate.ClientTag) { if(!ClientTags.Contains(request.ClientTag)) { response.Acknowledge = Acknowledge.Failure; response.Message = "Unknown Client Tag."; return false; } } // Validate access token if ((Validate.AccessToken & validate) == Validate.AccessToken) { if (_accessToken == null) { response.Acknowledge = Acknowledge.Failure; response.Message = "Invalid or expired AccessToken."; return false; } } // Validate user credentials if ((Validate.UserCredentials & validate) == Validate.UserCredentials) { //Todo: tie userName to WindowsPrincipal or .net membership provider? //System.Security.Principal.WindowsPrincipal userPrincipal; if (_userName == null)//temp - any user name constitutes valid credentials { response.Acknowledge = Acknowledge.Failure; response.Message = "Please login and provide user credentials before accessing these methods."; return false; } } return true; }
public ValidationRule(Validate validate) : this(validate, null) { }
public ValidationRule(Validate validate, string failureMessage) : this(validate, failureMessage, null) { }
public FormValidateSetup(jqSelector Id) { this.Id = Id; Option = new Validate(); }
private static Validate GetValidateTask() { Validate task = new Validate(); task.BuildEngine = new FakeBuildEngine(); task.CFUser = Settings.Default.User; task.CFPassword = Settings.Default.Password; task.CFServerUri = Settings.Default.ServerUri; task.CFSpace = "TestSpace"; task.CFOrganization = "TestOrg"; task.CFStack = "testStack"; task.CFAppName = "testApp"; task.CFRoutes = new string[2] { "test.domain.com;test3.domain.com", "test2.domain.com" }; task.CFServices = @"service1,mysql,myPlan;service2,mssql2012,myPlan;"; return task; }
public ValidationRule(Validate validate, string failureMessage, object value) { Validate = validate; Value = value; if (failureMessage != null) { ErrorMessage = failureMessage; } else { //setup default error messages switch (Validate) { case Validate.Required: ErrorMessage = "This field is Required"; break; default: ErrorMessage = "Field error"; break; } } }
/// <summary> /// Validate 3 security levels for a request: ClientTag, AccessToken, and User Credentials /// </summary> /// <param name="request">The request message.</param> /// <param name="response">The response message.</param> /// <param name="validate">The validation that needs to take place.</param> /// <returns></returns> private bool ValidRequest(RequestBase request, ResponseBase response, Validate validate) { // Validate Client Tag. In production this should query a 'client' table in a database. if ((Validate.ClientTag & validate) == Validate.ClientTag) { if (request.ClientTag != "ABC123") { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Unknown Client Tag"; return false; } } // Validate access token if ((Validate.AccessToken & validate) == Validate.AccessToken) { if (_accessToken == null) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Invalid or expired AccessToken. Call GetToken()"; return false; } } // Validate user credentials if ((Validate.UserCredentials & validate) == Validate.UserCredentials) { if (_userName == null) { response.Acknowledge = AcknowledgeType.Failure; response.Message = "Please login and provide user credentials before accessing these methods."; return false; } } return true; }