Strong Password Generator in C#

This code snippets will let you auto-generate strong passwords. Look for the password rules in the inline comments in code

001 using System;
002 using System.Collections.Generic;
003 using System.Linq;
004 using System.Security.Cryptography.X509Certificates;
005 using System.Text;
006 using System.Threading.Tasks;
007
008 namespace PwdGen
009 {
010     class Program
011     {
012         static void Main(string[] args)
013         {
014             //Console.WriteLine(GeneratePassword2(8, 15));
015             //Console.WriteLine(GeneratePassword(8, 15));
016             Console.ReadKey();
017         }
018
019         static string GeneratePassword2(int MinLengthint MaxLength)
020         {
021
022             string ValidChars "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:;<>|=.,_-~!?&%@#$£€°^*§()+[] ";
023             string SpecialChars "!@#$%^&*()";
024             
025             string pwd string.Empty;
026
027             do
028             {
029                 Random rnd = new Random(Guid.NewGuid().GetHashCode());
030                 pwd string.Join(string.Empty, Enumerable.Repeat(ValidCharsrnd.Next(MinLengthMaxLength 1)).Select(=> s[rnd.Next(s.Length)]).ToArray());
031                 Console.WriteLine(pwd);
032             } while (
033
034                 Regex.Match(pwd"[a-zA-Z]{3,}").Success || // Not more than 3 chars in sequence
035                 Regex.Match(pwd, @"(\w)\1{2,}").Success || //Same number should not repeat more than 2 times
036                 Regex.Match(pwd"[1-9]{3,}").Success ||    // Not more than 3 numbers in sequence
037                 !Regex.Match(pwd"[A-Z]").Success ||       // At least one upper case char
038                 !Regex.Match(pwd"[a-z]").Success ||       // At least one lower case char
039                 !Regex.Match(pwd"[1-9]").Success ||         // At least one number
040                 (pwd.ToArray().Where(=> SpecialChars.ToArray().Any(l2 => l2 == l)).Count() == 0// At least one pre defined special char
041                 );
042             
043             return pwd;
044         }
045
046         static string GeneratePassword(int MinLengthint MaxLength)
047         {
048             string ValidChars "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:;<>|=.,_-~!?&%@#$£€°^*§()+[] ";
049             string SpecialChars "!@#$%^&*()";
050             
051             string pwd string.Empty;
052
053             Random rnd = new Random(Guid.NewGuid().GetHashCode());
054             
055             bool NumExist false;
056             bool IsUpper false;
057             bool IsLower false;
058             bool IsSplChr false;
059             bool NoRepeat true;
060             bool NoSeq true;
061
062             while ((!NumExist || !IsUpper || !IsLower || !IsSplChr) && (NoRepeat || NoSeq) )
063             {
064                 NumExist false;
065                 IsUpper false;
066                 IsLower false;
067                 IsSplChr false;
068                 NoRepeat true;
069                 NoSeq true;
070                 
071                 pwd string.Join(string.Empty, Enumerable.Repeat(ValidCharsrnd.Next(MinLengthMaxLength 1)).Select(=> s[rnd.Next(s.Length)]).ToArray());
072                 for (int i 0pwd.Lengthi++)
073                 {
074                     // Contains at least 1 lower case letter and 1 upper case letter (all UTF-8), at least 1 number
075
076                     if (!NumExist)
077                     {
078                         NumExist = (char.IsDigit(pwd[i]) && true);
079                     }
080                     if (!IsUpper)
081                     {
082                         IsUpper = (char.IsUpper(pwd[i]) && true);
083                     }
084                     if (!IsLower)
085                     {
086                         IsLower = (char.IsLower(pwd[i]) && true);
087                     }
088
089                     // A predefined set of special chars must be present
090                     if (!IsSplChr)
091                     {
092                         IsSplChr = (SpecialChars.IndexOf(pwd[i]) >= 0);
093                     }
094
095
096                     // Not more than 2 identical characters in a row (e.g., 111 not allowed)
097                     if (pwd.Length && NoRepeat)
098                     {
099                         NoRepeat = !((pwd[i] == pwd[1]) && (pwd[i] == pwd[2]));
100                     }
101
102                     // Not any sequence of the English alphabet / numbers (above 3 letters)
103                     if (pwd.Length && NoSeq)
104                     {
105                         NoSeq = !((pwd[2] - pwd[1]) == (pwd[1] - pwd[i]));
106                     }
107                     Console.WriteLine(!NumExist +" "+ !IsUpper " " + !IsLower " " + !IsSplChr " " +  NoRepeat +NoSeq);
108                 }
109                 
110             }
111             
112             return pwd;
113
114         }
115     }
116 }
117

View in GitHub | Made with wp-showgithubfile plugin

Upload/Download file to/fro MongoDB in Java

// This code is just for my reference

 public static void main(String[] args) {
Logger mongoLogger = Logger.getLogger( "org.mongodb.driver" );
mongoLogger.setLevel(Level.SEVERE);

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("testdb");

GridFSBucket gridFSFilesBucket = GridFSBuckets.create(database);
ObjectId fileId = new ObjectId();
try {

InputStream streamToUploadFrom = new FileInputStream(new File("d:\\200mb.mkv"));

// GridFSUploadOptions options = new GridFSUploadOptions()
// .chunkSizeBytes(1000)
// .metadata(new Document("type", "presentation"));

fileId = gridFSFilesBucket.uploadFromStream("myfile", streamToUploadFrom);

System.out.println("ObjectID" + fileId);
} catch(FileNotFoundException ex) {
System.out.println("Error" + ex.getMessage());
}


try {
FileOutputStream streamToDownloadTo = new FileOutputStream("d:/out.mkv");
gridFSFilesBucket.downloadToStream(fileId , streamToDownloadTo);
streamToDownloadTo.close();
System.out.println("Finished!");
} catch (IOException e) {
// handle exception
}
}

Bookmark: Raise event from a WPF User control

This blog is just for sample code keeping.

// UserControl1.xaml

<UserControl x:Class=”WpfApp1.UserControl1″

             xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

             xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

             xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″

             xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″

             xmlns:local=”clr-namespace:WpfApp1″

             mc:Ignorable=”d” Background=”Red” Height=”186.646″ Width=”411.693″>

    <Grid>

        <Button Content=”Button” HorizontalAlignment=”Left” Margin=”80,72,0,0″ VerticalAlignment=”Top” Width=”75″ Click=”Button_Click”/>

    </Grid>

</UserControl>


// UserControl1.xaml.cs

namespace WpfApp1

{

    /// <summary>

    /// Interaction logic for UserControl1.xaml

    /// </summary>

    public partial class UserControl1 : UserControl

    {

        public event EventHandler MyButtonClick;

        public UserControl1()

        {

            InitializeComponent();

        }

        private void Button_Click(object sender, RoutedEventArgs e)

        {

            this.MyButtonClick(this, new EventArgs());

        }

    }

}


// UserControl2.xaml

<UserControl x:Class=”WpfApp1.UserControl2″

             xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

             xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

             xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″

             xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″

             xmlns:local=”clr-namespace:WpfApp1″

             mc:Ignorable=”d”

             d:DesignHeight=”450″ d:DesignWidth=”800″ Background=”Green”>

    <Grid>

    </Grid>

</UserControl>

// MainWindow.xaml

<Window x:Class=”WpfApp1.MainWindow”

        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

        xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″

        xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″

        xmlns:local=”clr-namespace:WpfApp1″

        mc:Ignorable=”d”

        Title=”MainWindow” Height=”450″ Width=”800″>

    <Grid x:Name=”MyGrid”>

        <local:UserControl1 x:Name=”userControl1″ HorizontalAlignment=”Left” Height=”100″ Margin=”99,62,0,0″ VerticalAlignment=”Top” Width=”242″ MyButtonClick=”UserControl1_MyButtonClick” />

    </Grid>

</Window>

// MainWindow.xaml.cs

namespace WpfApp1

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    public partial class MainWindow : Window

    {

        private void UserControl1_MyButtonClick(object sender, EventArgs e)

        {

        

        }

    }

}

Delivered a session on Virtual Classrooms – best practices to School Teachers

I got an opportunity to present a session on etiquette and tips & tricks in the 5-day online workshop organized by IT Milan Seva Foundation and & NTU Kerala.  About 100 teachers from different schools across Kerala attended the event. The sessions were handled by experts in technology field and mine was on day-4. The program name was “പഞ്ചദിന ശാക്തീകരണ ശില്പശാല“, which formally concluded today. This stands here as my first ever technology session in Malayalam and, I am crediting this session also to my giving-back-to-community personal goal.

Best Practices Deck

Topics covered:

– Etiquettes

– Best Practices & tricks

– Google Calendar

– Google Forms

– Chrome extensions

Video recording of the same can be watched here.

Part-2 of Python Learning (Malayalam) Series has been published

You can Read the article here:

– പ്രോഗ്രാമിംഗ് പഠിക്കാൻ പഠിക്കാം – പൈത്തൺ പ്രോഗ്രാമിംഗ് ഭാഗം 2 – https://www.janmabhumi.in/read/python-programming-part-2/

– YouTube Video of the same: https://www.youtube.com/watch?v=rRZA2rCXzEs

All previous Parts – https://www.janmabhumi.in/admin-news-listing/?username=b19GgNpk1nCEhD9APPZ9Ch2RL0fgfM

May subscribe to playlist for updates on future parts – https://www.youtube.com/channel/UC3s4kM_Ov55FF02I5nQZB4g