Generating Random Passwords (with required characters) in c#

passwordIn looking for a way to create some passwords that included sets of characters (lower case, upper, numbers or symbols) below is a chunk of code that seems to do the job. It makes use of RNGCryptoServiceProvider from System.Security.Cryptography instead of the classic Random.

You can choose a set length or variable:

//use a set length
string pass = GenerateAPassword(10);

//or get a random length between two ints
string pass = GenerateAPassword(12, 15);

The required parts of the password are created using a simple string array. -Be careful is creating small sets of strings, as it could take longer to create a password to fulfill the requirements.

 string[] parts = new string[] { "abcdefghjkmnpqrstuvwxyz", "ABCDEFGHJKLMNPQRSTUVWXYZ", "23456789", "*&^%$#@!" };

 

Below is the needed code.

You’ll need: using System.Security.Cryptography & using System.Text at the least.

public string GenerateAPassword(int length, int maxl = 0)
        {
            //separate required parts of password below
            //below i have lower, upper, numbers and symbols
            string[] parts = new string[] { "abcdefghjkmnpqrstuvwxyz", "ABCDEFGHJKLMNPQRSTUVWXYZ", "23456789", "*&^%$#@!" };

            if (length < parts.Length + 1)
            {
                return "invalid length";
            }

            //
            if (maxl > 0)
            {
                length = rngNumber(length, maxl);
            }

            StringBuilder pass = new StringBuilder();
            int l = length;
            while (0 < l--)
            {
                pass.Append(string.Join("", parts)[rngNumber(0, string.Join("", parts).Length - 1)]);
            }

            //check of parts of password exist
            foreach (string part in parts)
            {
                if (pass.ToString().IndexOfAny(part.ToCharArray()) == -1)
                {
                    //create again if missing
                    return GenerateAPassword(length);
                }
            }

            return pass.ToString();
        }

        private static readonly RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        public static int rngNumber(int min, int max)
        {
            byte[] randomNumber = new byte[1];

            rng.GetBytes(randomNumber);

            return (int)(min + (Math.Floor(Math.Max(0, ((Convert.ToDouble(randomNumber[0])) / 255d) - 0.00000000001d) * (max - min + 1))));
        }

 

Generating Random Passwords (with required characters) in c#

DataTable Row Loop c# Performance Testing (Linq vs. Select vs. Parallel vs. For)

froot-loopsI still find myself using DataTables (from SQL Server, mySQL, etc.) on a regular basis. In an effort to see how some different methods of looping through the data performs and what method might be the fastest, I put together some small, fast tests, below are my test results.

[Just jump to the fastest method.]

datatable-row-tests

My sample data was comprised of about a 34,000  row datatable – running these tests on a i7, 32gb, VS2015 setup. The 34,000 was chosen because a box of Froot Loops contains about 1800 Froot Loops (I think), but 1800 was too small, so how about 18 boxes of Froot Loops?

Continue reading “DataTable Row Loop c# Performance Testing (Linq vs. Select vs. Parallel vs. For)”

DataTable Row Loop c# Performance Testing (Linq vs. Select vs. Parallel vs. For)

Parsing JSON data in C# (JSON.NET, Linq, HttpClient)

Parsing JSON in C# is pretty simple. I’m a fan of using Newtonsoft.Json (known as JSON.NET) – I’ve found this to be the fastest, easiest JSON parser available.

Below are some steps to get parsing on your own (or jump down to the full source code). You can also grab this on GitHub. I’m just using a simple console app for this example. My JSON is also coming from a Google Custom Search (via http get). You’ll need to have your own JSON url (or maybe get a test url here).

  1. Start a new project > console application.
  2. In Package Manager Console, run: Install-Package Newtonsoft.Json
  3. Add the below to the top of your code file (Program.cs):
    using Newtonsoft.Json.Linq;
    using System;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
  4. Create a task to get some JSON data from http:public static async Task<string> httpResponse(string url)
    {
    IWebProxy iprox = WebProxy.GetDefaultProxy();
    iprox.Credentials = CredentialCache.DefaultCredentials;HttpClientHandler httpHandler = new HttpClientHandler()
    {
    UseProxy = true,
    Proxy = iprox,
    PreAuthenticate = true,
    UseDefaultCredentials = true,
    Credentials = CredentialCache.DefaultCredentials
    };using (var httpClient = new HttpClient(httpHandler))
    return await httpClient.GetStringAsync(url);
    }
  5. Now get some data:
    JObject jData = JObject.Parse(httpResponse(@”https://www.googleapis.com/customsearch/v1?youneedtocreateyourownlink&#8221;).Result);
  6. Read some simple data:
    string sampleValue = (string)jData[“url”][“type”];
  7. Read array of data:
    foreach (var sampleItem in jData[“items”])
    {
    string sampleItemValue = (string)sampleItem[“link”];
    Console.WriteLine(sampleItemValue);
    }

The full source:

using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace parsingJSON
{
    internal class Program
    {
        public static async Task<string> httpResponse(string url)
        {
            //i'm using a proxy, you could remove this if needed.
            IWebProxy iprox = WebProxy.GetDefaultProxy();
            iprox.Credentials = CredentialCache.DefaultCredentials;

            HttpClientHandler httpHandler = new HttpClientHandler()
            {
                UseProxy = true,
                Proxy = iprox,
                PreAuthenticate = true,
                UseDefaultCredentials = true,
                Credentials = CredentialCache.DefaultCredentials
            };

            using (var httpClient = new HttpClient(httpHandler))
                return await httpClient.GetStringAsync(url);
        }

        private static void Main(string[] args)
        {
            //get some JSON data
            JObject jData = JObject.Parse(httpResponse(@"https://yourJSONlinkhere").Result);

            string sampleValue = (string)jData["url"]["type"];

            Console.WriteLine(sampleValue);

            //loop through array in JSON
            foreach (var sampleItem in jData["items"])
            {
                string sampleItemValue = (string)sampleItem["link"];
                Console.WriteLine(sampleItemValue);
            }

            //filter w/ linq:

            var sampleArray =
              from p in jData["items"]
              select p;

            foreach (var sampleItem in sampleArray.Where(p => ((string)p["link"]).Contains("https")))
            {
                string sampleItemValue = (string)sampleItem["link"];
                Console.WriteLine(sampleItemValue);
            }

            Console.ReadLine();
        }
    }
}

View on GitHub

Parsing JSON data in C# (JSON.NET, Linq, HttpClient)