Validate Date of Birth Using Fluent Validation in C#

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:44:03

4K+ Views

To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validateRuleFor(p => p.DateOfBirth)To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.ValidationResult results = validator.Validate(person);The Validate method returns a ValidationResult object. This contains two propertiesIsValid - a boolean that says whether the validation suceeded.Errors - a collection of ValidationFailure objects containing details about any validation failuresExample 1static void Main(string[] args) {    List errors = new List();    PersonModel person = new PersonModel();    person.FirstName ... Read More

Use of Fluent Validation in C# and How to Implement It

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:41:41

2K+ Views

FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logicTo make use of fluent validation we have to install the below packageExample 1static class Program {    static void Main (string[] args) {       List errors = new List();       PersonModel person = new PersonModel();       person.FirstName = "";       person.LastName = "S";   ... Read More

Copy Files into a Directory in C#

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:37:24

4K+ Views

To Copy a file, C# provides a method File. CopyFile. Copy has 2 overloadsCopy(String, String) -Copies an existing file to a new file. Overwriting a file of the same name is not allowed.Copy(String, String, Boolean) Copies an existing file to a new file. Overwriting a file of the same name is allowed.Directory.GetFiles returns the names of all the files (including their paths) that match the specified search pattern, and optionally searches subdirectories.Examplestatic void Main (string[] args) {    string rootPath = @"C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1";    var searchSourceFolder = Directory.GetFiles(rootPath, "*.*", SearchOption.TopDirectoryOnly);    Console.WriteLine("-------------Source Folder-------------");    foreach (string file in searchSourceFolder){   ... Read More

Dash Separated Cartesian Product of Any Number of Arrays in JavaScript

AmitDiwan
Updated on 25-Nov-2020 11:35:37

183 Views

We are required to write a JavaScript function that takes in any number of arrays of literals. The function should compute and return an array of cartesian product of all the elements from the arrays separating them with a dash('−').ExampleThe code for this will be −const arr1= [ 'a', 'b', 'c', 'd' ]; const arr2= [ '1', '2', '3' ]; const arr3= [ 'x', 'y', ]; const dotCartesian = (...arrs) => {    const res = arrs.reduce((acc, val) => {       let ret = [];       acc.map(obj => {          val.map(obj_1 => { ... Read More

Different Ways to Implement Dependency Injection in C#

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:33:47

2K+ Views

The process of injecting (converting) coupled (dependent) objects into decoupled (independent) objects is called Dependency Injection.Types of Dependency InjectionThere are four types of DI:1.Constructor Injection2.Setter Injection3.Interface-based injection4.Service Locator InjectionConstructor InjectionConstructor is used to interface parameter that exposed through the parameterized contractor.It injects the dependencies through a contractor method as object creation other classes.Setter InjectionGetter and Setter Injection injects the dependency by using default public properties procedure such as Gettter(get(){}) and Setter(set(){}). TInterface InjectionInterface Injection is similar to Getter and Setter DI, the Getter and Setter DI uses default getter and setter but Interface Injection uses support interface a kind of ... Read More

Convert XML to JSON and JSON Back to XML using Newtonsoft.Json

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:32:31

3K+ Views

Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter.Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the twoSerializeXmlNodeThe JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text.DeserializeXmlNodeThe second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into an XmlNode.Example 1static void Main(string[] args) {    string xml = @"Alanhttp://www.google1.com Admin1";    XmlDocument doc = new XmlDocument();    doc.LoadXml(xml);    string json = JsonConvert.SerializeXmlNode(doc); ... Read More

Finding Number of Days Between Two Dates in JavaScript

AmitDiwan
Updated on 25-Nov-2020 07:54:45

227 Views

We are required to write a JavaScript function that takes in two dates in the 'YYYY-MM-DD' format as the first and second argument respectively. The function should then calculate and return the number of days between the two dates.For example −If the input dates are −const str1 = '2020-05-21'; const str2 = '2020-05-25';Then the output should be −const output = 4;Exampleconst str2 = '2020-05-25'; const daysBetweenDates = (str1, str2) => {    const leapYears = (year, month) => {       if (month (year * 365) + leapYears(year, month) + monthDays[month] + d; let p = days(...str1.split('-').map(Number));   ... Read More

Lucky Numbers in a Matrix in JavaScript

AmitDiwan
Updated on 25-Nov-2020 07:01:27

612 Views

Given a m * n matrix of distinct numbers, we have to return all lucky numbers in the 2-D array (matrix) in any order.A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.For example − If the input array is −const arr = [    [3, 7, 8],    [9, 11, 13],    [15, 16, 17] ];Then the output should be −const output = [15];because 15 is the only lucky number since it is the minimum in its row and the maximum in its column.ExampleThe code ... Read More

Find Distance Between Items in Array using JavaScript

AmitDiwan
Updated on 25-Nov-2020 06:49:52

326 Views

Suppose, we have a sorted (increasing order) array of Numbers like this −const arr = [2, 5, 7, 8, 9];We are required to write a JavaScript function that takes in one such array. The function should construct a new subarray for each element of the input array.The sub-array should contain the difference (difference between that very element and the succeeding elements one by one) elements.Therefore, for the first array element, the differences are −5 - 2 = 3 7 - 2 = 5 8 - 2 = 6 9 - 2 = 7Therefore, the subarray for the first element should ... Read More

Finding Number of Spaces in a String in JavaScript

AmitDiwan
Updated on 25-Nov-2020 05:23:36

1K+ Views

We are required to write a JavaScript function that takes in a string containing spaces. The function should simply count the number of spaces present in that string.For example −If the input string is −const str = 'this is a string';Then the output should be −const output = 4;Exampleconst str = 'this is a string'; const countSpaces = (str = '') => {    let count = 0;    for(let i = 0;    i < str.length; i++){       const el = str[i];       if(el !== ' '){          continue; };          count++; };       return count; }; console.log(countSpaces(str));OutputThis will produce the following output −4

Advertisements