/// <summary> /// Generates a list of words. /// </summary> /// <param name="count">The word count.</param> /// <param name="minLength">The minimum length.</param> /// <param name="maxLength">The maximum length.</param> /// <returns>ImmutableList<System.String>.</returns> public static ImmutableList <string> GenerateWords(int count, int minLength, int maxLength) { Encapsulation.TryValidateParam(count, minimumValue: 1, paramName: nameof(count)); var strings = new List <string>(); for (var wordCount = 0; wordCount < count; wordCount++) { strings.Add(GenerateWord(minLength, maxLength)); } return(strings.ToImmutableList()); }
/// <summary> /// Creates collection of coordinates. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count">The collection count.</param> /// <returns>List<T>.</returns> /// <example>[0]: {2089369587--284215139} [1]: {244137335-1577361939}</example> public static IEnumerable <T> GenerateCoordinateCollection <T>(int count) where T : ICoordinate, new() { Encapsulation.TryValidateParam(count, 0, int.MaxValue, nameof(count)); var coordinates = new List <T>(count); for (var personCount = 0; personCount < count; personCount++) { coordinates.Add(GenerateCoordinate <T>()); } return(coordinates); }
/// <summary> /// Creates a random word. /// </summary> /// <param name="length">The length.</param> /// <param name="minCharacter">The minimum character.</param> /// <param name="maxCharacter">The maximum character.</param> /// <returns>System.String.</returns> /// <example>LBEEUMHHHK</example> public static string GenerateWord(int length, char minCharacter, char maxCharacter) { Encapsulation.TryValidateParam(length, 1, int.MaxValue, nameof(length)); var word = new StringBuilder(length); for (var wordCount = 0; wordCount < length; wordCount++) { _ = word.Append(GenerateCharacter(minCharacter, maxCharacter)); } return(word.ToString()); }
/// <summary> /// Creates an IPerson collection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="count">The collection count.</param> /// <returns>List<PersonFixed>.</returns> /// <example>[0]: "*****@*****.**" [1]: "*****@*****.**"</example> public static PersonCollection <T> GeneratePersonCollection <T>(int count) where T : IPerson, new() { Encapsulation.TryValidateParam(count, 1, int.MaxValue, nameof(count)); var people = new PersonCollection <T>(count); _ = Parallel.For(0, count, index => { people.Add(RandomData.GeneratePerson <T>()); }); return(people); }
/// <summary> /// Ins the specified source. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="list">The list.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> /// <exception cref="ArgumentNullException">source - Source cannot be null. /// or /// list - List cannot be null or have a 0 length.</exception> /// <remarks>Original code by: Rory Becker</remarks> public static bool In <T>(this T source, params T[] list) { Encapsulation.TryValidateParam(list, nameof(list)); foreach (T value in list) { if (value.Equals(source)) { return(true); } } return(false); }
public static XDocument StringToXDocument(string input, XmlResolver resolver) { Encapsulation.TryValidateParam(input, nameof(input)); var options = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = resolver }; using (var reader = XmlReader.Create(new StringReader(input), options)) { return(XDocument.Load(reader)); } }
/// <summary> /// un g zip as an asynchronous operation. /// </summary> /// <param name="gzipPath">The gzip path.</param> /// <param name="expandedFilePath">The expanded file path.</param> /// <param name="deleteGZipFile">if set to <c>true</c> [delete g zip file].</param> /// <returns>Task.</returns> public static async Task UnGZipAsync(string gzipPath, string expandedFilePath, bool deleteGZipFile) { Encapsulation.TryValidateParam(gzipPath, nameof(gzipPath)); Encapsulation.TryValidateParam(expandedFilePath, nameof(expandedFilePath)); Encapsulation.TryValidateParam <ArgumentInvalidException>(File.Exists(gzipPath), nameof(gzipPath), "GZip file not found."); await UnGZipAsync(gzipPath, expandedFilePath).ConfigureAwait(true); if (deleteGZipFile) { File.Delete(gzipPath); } }
/// <summary> /// Gets the registry key. /// </summary> /// <param name="name">The name.</param> /// <returns>RegistryKey.</returns> /// <exception cref="System.PlatformNotSupportedException">The platform exception.</exception> public static RegistryKey GetCurrentUserRegistryKey(string name) { Encapsulation.TryValidateParam(name, nameof(name)); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return(Registry.CurrentUser.OpenSubKey(name)); } else { throw new PlatformNotSupportedException(); } }
/// <summary> /// Creates a random number string. /// </summary> /// <param name="length">The length.</param> /// <returns>System.String.</returns> /// <example>"446085072052112"</example> public static string GenerateNumber(int length) { Encapsulation.TryValidateParam(value: length, minimumValue: 1, maximumValue: int.MaxValue, paramName: nameof(length)); var sb = new StringBuilder(length); for (var count = 0; count < length; count++) { sb.Append(_random.Next(0, 9)); } return(sb.ToString()); }
/// <summary> /// Creates object from a Json file. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="file">The file.</param> /// <returns>T.</returns> /// <exception cref="FileNotFoundException">File not found.</exception> public static T FromJsonFile <T>(string file) where T : class { Encapsulation.TryValidateParam(file, nameof(file)); if (File.Exists(file) == false) { throw new FileNotFoundException("File not found.", file); } var json = File.ReadAllText(file, Encoding.UTF8); return(JsonSerializer.Deserialize <T>(json)); }
/// <summary> /// Queue factory. Always synchronized. /// </summary> /// <param name="durationMilliseconds">The duration milliseconds.</param> /// <returns>CountdownTimerQueue.</returns> public static TimerQueue GetOrCreateQueue(int durationMilliseconds) { Encapsulation.TryValidateParam <ArgumentException>(durationMilliseconds.IsNegative() == false, nameof(durationMilliseconds)); if (durationMilliseconds == Timeout.Infinite) { return(new InfiniteTimerQueue()); } TimerQueue queue; object key = durationMilliseconds; // Box once. var weakQueue = (WeakReference)_queuesCache[key]; if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null) { lock (_newQueues) { weakQueue = (WeakReference)_queuesCache[key]; if (weakQueue == null || (queue = (TimerQueue)weakQueue.Target) == null) { queue = new CountdownTimerQueue(durationMilliseconds); weakQueue = new WeakReference(queue); _newQueues.AddLast(weakQueue); _queuesCache[key] = weakQueue; // Take advantage of this lock to periodically scan the table for garbage. if (++_cacheScanIteration % CacheScanPerIterations == 0) { var garbage = new List <object>(); // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = _queuesCache.GetEnumerator(); while (e.MoveNext()) { DictionaryEntry pair = e.Entry; if (((WeakReference)pair.Value).Target is null) { garbage.Add(pair.Key); } } for (var i = 0; i < garbage.Count; i++) { _queuesCache.Remove(garbage[i]); } } } } } return(queue); }
/// <summary> /// Gets all. /// </summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns>IEnumerable<T>.</returns> public override bool Equals(object obj) { Encapsulation.TryValidateParam <ArgumentNullException>(obj != null, nameof(obj)); if (!(obj is Enumeration otherValue)) { return(false); } var typeMatches = this.GetType().Equals(obj.GetType()); var valueMatches = this._value.Equals(otherValue.Value); return(typeMatches && valueMatches); }
/// <summary> /// Checks to see if the value is in the specified source. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="list">The list.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> /// <remarks>Original code by: Rory Becker</remarks> public static bool In <T>(this T source, params T[] list) { Encapsulation.TryValidateParam <ArgumentOutOfRangeException>(list != null && list.Length != 0, "list is null or empty."); foreach (var value in list) { if (value.Equals(source)) { return(true); } } return(false); }
/// <summary> /// Creates list of email addresses. /// </summary> /// <param name="emailAddressType">Type of the email address.</param> /// <param name="emailAddresses">Array of email addresses.</param> /// <returns>List<EmailAddress>.</returns> public static EmailAddress[] CreateEmailAddressList(EmailAddressType emailAddressType, params string[] emailAddresses) { Encapsulation.TryValidateParam(emailAddressType, nameof(emailAddressType)); Encapsulation.TryValidateParam(emailAddresses, nameof(emailAddresses)); var addresses = new List <EmailAddress>(); addresses.AddRange(emailAddresses.Select(address => new EmailAddress(address) { EmailAddressType = emailAddressType })); return(addresses.ToArray()); }
/// <summary> /// Determines whether the specified the string contains any. /// </summary> /// <param name="input">The string.</param> /// <param name="characters">The characters.</param> /// <returns><c>true</c> if the specified characters contains any; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException">input - List cannot be null. /// or /// characters - Characters cannot be null or 0 length. /// or /// Null character.</exception> /// <exception cref="System.ArgumentNullException">Null character.</exception> public static bool ContainsAny(this string input, params string[] characters) { Encapsulation.TryValidateParam(characters, nameof(characters)); foreach (var character in characters) { if (input.Contains(character)) { return(true); } } return(false); }
/// <summary> /// Finds first item or returns null. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The list.</param> /// <param name="match">The match.</param> /// <returns>System.Nullable<T>.</returns> /// <exception cref="ArgumentNullException"> /// list - Source cannot be null. /// or /// match - Match cannot be null. /// </exception> public static T?FirstOrNull <T>(this IEnumerable <T> list, Func <T, bool> match) where T : struct { Encapsulation.TryValidateParam <ArgumentNullException>(match == null, "Match cannot be null."); foreach (T local in list) { if (match?.Invoke(local) ?? default(bool)) { return(new T?(local)); } } return(null); }
/// <summary> /// Deserializes the specified Json. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json">The json.</param> /// <returns>T.</returns> public static T Deserialize <T>(string json) where T : class { Encapsulation.TryValidateParam(json, nameof(json)); var obj = TypeHelper.Create <T>(); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { var ser = new DataContractJsonSerializer(obj.GetType()); obj = ser.ReadObject(ms) as T; } return(obj); }
/// <summary> /// Deletes a temporary file. /// </summary> /// <param name="file">The file.</param> public void DeleteFile(string file) { Encapsulation.TryValidateParam(file, nameof(file)); if (File.Exists(file)) { File.Delete(file); } if (this._files.Contains(file)) { this._files.Remove(file); } }
/// <summary> /// Sets the attributes normal for all files and directories in the path. /// </summary> /// <param name="path">The path.</param> public static void SetAttributesNormal(string path) { Encapsulation.TryValidateParam(path, nameof(path)); for (var directoryCount = 0; directoryCount < Directory.GetDirectories(path).Length; directoryCount++) { SetAttributesNormal(Directory.GetDirectories(path)[directoryCount]); } for (var fileCount = 0; fileCount < Directory.GetFiles(path).Length; fileCount++) { File.SetAttributes(Directory.GetFiles(path)[fileCount], System.IO.FileAttributes.Normal); } }
/// <summary> /// Deletes the folders. /// </summary> /// <param name="folders">The folders.</param> /// <returns>System.Int32.</returns> public int DeleteFolders(IEnumerable <DirectoryInfo> folders) { Encapsulation.TryValidateParam(folders, nameof(folders)); var successCount = 0; var list = folders.ToList(); for (int i = 0; i < list.Count; i++) { DirectoryInfo tempFolder = list[i]; if (tempFolder.Exists) { try { tempFolder.Delete(recursive: true); successCount += 1; this.OnProcessed(new FileProgressEventArgs { Name = tempFolder.FullName, ProgressState = FileProgressState.Deleted }); } catch (Exception ex) when(ex is IOException || ex is SecurityException || ex is UnauthorizedAccessException || ex is DirectoryNotFoundException) { this.OnProcessed(new FileProgressEventArgs { Name = tempFolder.FullName, ProgressState = FileProgressState.Error, Message = ex.Message }); } } else { this.OnProcessed(new FileProgressEventArgs { Name = tempFolder.FullName, ProgressState = FileProgressState.Error, Message = Resources.FolderNotFound }); } } return(successCount); }
/// <summary> /// Delete directory, with retries, as an asynchronous operation. /// </summary> /// <param name="directory">The directory.</param> /// <returns>Task<System.Boolean>.</returns> /// <exception cref="System.ArgumentNullException">directory</exception> /// <exception cref="ArgumentNullException">directory</exception> public static async Task <bool> DeleteDirectoryAsync(DirectoryInfo directory) { Encapsulation.TryValidateParam <ArgumentNullException>(directory != null); if (directory.Exists) { await Task.Factory.StartNew(() => { DeleteDirectory(directory.FullName); return(true); }).ConfigureAwait(true); } return(false); }
/// <summary> /// Generates files. /// </summary> /// <param name="count">The file count.</param> /// <param name="fileLength">Length of the file.</param> /// <returns>System.ValueTuple<System.String, IEnumerable<System.String>>.</returns> /// <example>Path: "C:\\Users\\dotNetDave\\AppData\\Local\\Temp\\" Files: Count = 100</example> public static (string Path, IEnumerable <string> Files) GenerateFiles(int count = 100, int fileLength = 1000) { Encapsulation.TryValidateParam(count, 1, int.MaxValue, nameof(count)); Encapsulation.TryValidateParam(fileLength, 1, int.MaxValue, nameof(fileLength)); var files = new List <string>(count); for (var fileCount = 0; fileCount < count; fileCount++) { files.Add(GenerateTempFile(fileLength)); } return(Path.GetTempPath(), files.AsEnumerable()); }
/// <summary> /// Adds if not exists. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list">The list.</param> /// <param name="value">The value.</param> /// <exception cref="ArgumentNullException">list - List cannot be null. /// or /// value - Value cannot be null.</exception> /// <exception cref="ArgumentException">list - List cannot be read-only.</exception> public static void AddIfNotExists <T>(this ICollection <T> list, T value) { Encapsulation.TryValidateParam <ArgumentNullException>(value != null, "Value is required."); Encapsulation.TryValidateParam(list, nameof(list)); foreach (var item in list) { if (TypeHelper.GetInstanceHashCode(item) == TypeHelper.GetInstanceHashCode(value)) { return; } } list.Add(value); }
/// <summary> /// Finds first item or returns null. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="match">The match.</param> /// <returns>System.Nullable<T>.</returns> public static T?FirstOrNull <T>(this IEnumerable <T> source, Func <T, bool> match) where T : struct { Encapsulation.TryValidateParam <ArgumentNullException>(match != null); foreach (var local in source.AsParallel()) { if (match.Invoke(local) && default(bool)) { return(new T?(local)); } } return(null); }
/// <summary> /// Sends mail async. /// </summary> /// <param name="fromAddress">From email address.</param> /// <param name="subject">Subject.</param> /// <param name="message">Message.</param> /// <param name="bodyHtml">Sets message is HTML.</param> /// <param name="sendAddresses">Send to email addresses.</param> public async Task SendMailAsync(EmailAddress fromAddress, string subject, string message, bool bodyHtml, EmailAddress[] sendAddresses) { Encapsulation.TryValidateParam <ArgumentNullException>(fromAddress.IsNotNull(), nameof(fromAddress)); Encapsulation.TryValidateParam(subject, nameof(subject)); Encapsulation.TryValidateParam(message, nameof(message)); Encapsulation.TryValidateParam(sendAddresses, nameof(sendAddresses)); // 'Set default types, just in case. fromAddress.EmailAddressType = EmailAddressType.SendFrom; using (var tempMessage = CreateMailMessage(fromAddress, subject, message, bodyHtml, sendAddresses)) { await this._mailServer.SendMailAsync(tempMessage).ConfigureAwait(false); } }
/// <summary> /// Sends mail. /// </summary> /// <param name="fromAddress">From email address.</param> /// <param name="subject">Subject.</param> /// <param name="message">Message.</param> /// <param name="bodyHtml">Sets message is HTML.</param> /// <param name="sendAddresses">Send email addresses.</param> public void SendMail(EmailAddress fromAddress, string subject, string message, bool bodyHtml, EmailAddress[] sendAddresses) { Encapsulation.TryValidateParam <ArgumentNullException>(fromAddress.IsNotNull(), nameof(fromAddress)); Encapsulation.TryValidateParam(subject, nameof(subject)); Encapsulation.TryValidateParam(message, nameof(message)); Encapsulation.TryValidateParam(sendAddresses, nameof(sendAddresses)); // 'Set default types, just in case. fromAddress.EmailAddressType = EmailAddressType.SendFrom; using (var tempMessage = CreateMailMessage(fromAddress, subject, message, bodyHtml, sendAddresses)) { this.SendMailMessage(tempMessage, null); } }
/// <summary> /// Serializes the specified obj to xml. /// </summary> /// <param name="obj">The obj.</param> /// <returns>System.String.</returns> /// <exception cref="ArgumentNullException">obj</exception> public static string Serialize(object obj) { Encapsulation.TryValidateParam <ArgumentNullException>(obj != null, nameof(obj)); using (var writer = new StringWriter()) { using (var xmlWriter = XmlWriter.Create(writer)) { var serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(xmlWriter, obj); return(writer.ToString()); } } }
public static async Task <string> DownloadStringAsync(Uri address, string clientId = "NONE") { Encapsulation.TryValidateParam(address, nameof(address)); using (WebClient client = new WebClient()) { if (clientId.HasValue()) { client.Headers.Add("CLIENTID", clientId); } // Download the data return(await client.DownloadStringTaskAsync(address)); } }
private static void setNextRoundInfo(Form form, Encapsulation message) { var roundInfo = Encapsulation.Deserialize <RoundInfo>(message); GameInfo.RoundGuid = roundInfo.UniqueId; if (roundInfo.PlayerWinStatus != WinStatus.Tie) { string label_name = (roundInfo.PlayerWinStatus == WinStatus.Win) ? "lbl_youScore" : "lbl_ennemyScore"; form.Invoke(new MethodInvoker(delegate { form.Controls.Find(label_name, true).FirstOrDefault().Text = $"{(int.Parse(form.Controls.Find(label_name, true).FirstOrDefault().Text) + 1)}"; })); } }
/// <summary> /// Adds an object to the <see cref="T:System.Collections.Concurrent.ConcurrentBag"></see>. /// </summary> /// <param name="item">The object to be added to the <see cref="T:System.Collections.Concurrent.ConcurrentBag`1"></see>. The value can be a null reference (Nothing in Visual Basic) for reference types.</param> public new void Add(T item) { Encapsulation.TryValidateParam <ArgumentNullException>(item != null, nameof(item)); var hashCode = item.GetHashCode(); lock (this._lock) { if (this._hashCodes.Contains(hashCode) == false) { base.Add(item); this._hashCodes.Add(hashCode); } } }
void FUNCTION(out pBaseLangObject outObj, pBaseLangObject parent, Encapsulation e) { var obj = new Function(parent); obj.encapsulation = e; outObj = obj; pBaseLangObject blo; VarType v; if (la.kind == 57) { Get(); obj.IsAsync = true; } if (la.kind == 58) { Get(); obj.Override = true; } if (StartOf(2)) { VARTYPE(out v); obj.varType = new VarTypeObject(v); } else if (la.kind == 48) { Get(); obj.varType = new VarTypeObject(VarType.Void); } else if (StartOf(12)) { bool isStrict = false; if (la.kind == 49) { Get(); isStrict = true; } IDENTACCESS(out blo, obj, false); obj.varType = new VarTypeObject((Ident)blo, isStrict); if (la.kind == 21) { Template te; TEMPLATE(out te, outObj); obj.varType.TemplateObject = te; } } else SynErr(94); IDENT(out blo, obj); obj.Name = (Ident)blo; Expect(10); if (StartOf(13)) { NEWVARIABLE(out blo, obj); obj.addChild(blo); while (la.kind == 18) { Get(); NEWVARIABLE(out blo, obj); obj.addChild(blo); } } Expect(11); obj.markArgListEnd(); Expect(14); while (StartOf(14)) { CODEINSTRUCTION(out blo, obj); obj.addChild(blo); } Expect(15); }
public Encapsulation.Structure GetStructureEncapsulated(Encapsulation.Structure testValue, bool barewordOkay = false) { throw new NotImplementedException(); }
void NEWVARIABLE(out pBaseLangObject outObj, pBaseLangObject parent, Encapsulation e = Encapsulation.NA) { var obj = new Variable(parent, la.col, la.line); obj.encapsulation = e; outObj = obj; pBaseLangObject blo; VarType v; if (StartOf(2)) { VARTYPE(out v); obj.varType = new VarTypeObject(v); } else if (StartOf(12)) { bool isStrict = false; if (la.kind == 49) { Get(); isStrict = true; } IDENTACCESS(out blo, obj); obj.varType = new VarTypeObject((Ident)blo, isStrict); if (la.kind == 21) { Template te; TEMPLATE(out te, outObj); obj.varType.TemplateObject = te; } } else SynErr(93); IDENT(out blo, outObj); obj.Name = (Ident)blo; if (la.kind == 7 || la.kind == 8 || la.kind == 9) { BODY_ASSIGNMENT(out blo, outObj); obj.addChild(blo); } }
void AUTOVARIABLE(out pBaseLangObject outObj, pBaseLangObject parent, Encapsulation e = Encapsulation.NA) { var obj = new Variable(parent, la.col, la.line); obj.encapsulation = e; outObj = obj; pBaseLangObject blo; Expect(60); obj.varType = new VarTypeObject(VarType.Auto); IDENT(out blo, outObj); obj.Name = (Ident)blo; BODY_ASSIGNMENT(out blo, outObj); obj.addChild(blo); }
void CONSTRUCTOR(out pBaseLangObject outObj, pBaseLangObject parent, Encapsulation e) { var obj = new Function(parent); obj.varType = new VarTypeObject(((oosClass)parent).Name, true); obj.encapsulation = e; outObj = obj; pBaseLangObject blo; IDENT(out blo, obj); obj.Name = (Ident)blo; Expect(10); if (StartOf(13)) { NEWVARIABLE(out blo, obj); obj.addChild(blo); while (la.kind == 18) { Get(); NEWVARIABLE(out blo, obj); obj.addChild(blo); } } Expect(11); obj.markArgListEnd(); if (la.kind == 59) { Get(); IDENTACCESS(out blo, obj); obj.addChild(blo); while (StartOf(1)) { IDENTACCESS(out blo, obj); obj.addChild(blo); } } obj.markBaseCallEnd(); Expect(14); while (StartOf(14)) { CODEINSTRUCTION(out blo, obj); obj.addChild(blo); } Expect(15); }
void ENCAPSULATION(out Encapsulation e) { e = Encapsulation.NA; if (la.kind == 25) { Get(); e = Encapsulation.Public; } else if (la.kind == 26) { Get(); e = Encapsulation.Private; } else if (la.kind == 27) { Get(); e = Encapsulation.Protected; } else SynErr(84); }