A quick Sentiment Analysis app using Azure Cognitive Services

Step 1: Create a Text Analytics Resource

From the Azure Portal, create a resource “Text Analytics”

image

Once created, you should be able to get the Endpoint URL and Key from the “Keys and Endpoint” section

image

Step 2: Create a .NET Console application in Visual Studio

Get the Azure.AI.TextAnalytics nuget package for your solution

image

Here you go your sample code

 
using Azure;
using Azure.AI.TextAnalytics;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "https://mytestoutlookaddin.cognitiveservices.azure.com/";
            string key = "paste_your_key_here";

            var client = new TextAnalyticsClient(new Uri(url), new AzureKeyCredential(key));

            DocumentSentiment mood = client.AnalyzeSentiment("It's a nice day!");
            Console.WriteLine("Mood: {0}", mood.Sentiment );
            Console.WriteLine("Positive: {0}", mood.ConfidenceScores.Positive);
            Console.WriteLine("Neutral: {0}", mood.ConfidenceScores.Neutral);
            Console.WriteLine("Negative: {0}", mood.ConfidenceScores.Negative);
            Console.ReadKey();
            
        }
    }
}

Below is the output expected:

image

Read a Brainyquote and parse the value using xpath in .NET

using System;
using System.Net;
using System.Xml;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (WebClient wc = new WebClient())
            {
                string data = 
                    wc.DownloadString("https://www.brainyquote.com/link/quotebr.rss");
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(data);
                var node = xml.SelectNodes("//rss/channel/item[1]");

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("{0} by {1}",
                    node[0]["description"].InnerText,
                    node[0]["title"].InnerText
                    );

                Console.ResetColor();
            }
        }
    }
}

List of mistakes on Security aspects which developers usually make

Below are some common mistakes developers make while development. Most of the mistakes will not impact the functionality of the application so tendency is to make the mistake subconsciously. Security should be by design and it is not something we should incorporate after the development.

OWASP guidelines should be taken as high priority in addition to this list.

  1. Writing sensitive information such as passwords in the paper or sticky notes
  2. Sharing credentials between team members
  3. Hard-coding sensitive information as plain text, including passwords in the application in configuration files, databases and comments
  4. Not encrypting the database
  5. Use of untrusted code from public internet forums without proper reviews and corrections
  6. Not encrypting the communication channels such as API
  7. Not following the principle of least privileges
  8. Opening server ports to public
  9. Not enforcing password policies (strong password, expiry policy, multi-factor-authentication)
  10. Not educating oneself on the secure coding practices
  11. Writing SQL in application code, instead of using stored procedures or ORM libraries
  12. Not validating user input values at server side
  13. Not setting session expiry policy
  14. Giving password hints on unsuccessful login attempts
  15. Not using custom exception pages, instead expose the debug messages to user
  16. No logging and monitoring
  17. Not making use of cryptography libraries
  18. Not writing unit testing code
  19. Not Automating static code analysis tools such as SonarQube
  20. Using untrusted sources for downloading libraries

Create a .NET console application using command line

We don’t deal with .NET framework, or .NET Core anymore. We call it ‘.NET’. As of writing this blog, the latest version available is .NET 5. And, these steps works in previous versions of .NET Core also.

Assuming you have downloaded the latest version of .NET.

Step 1:Open command prompt

Step 2: Type: dotnet new console -name “HelloWorld

You must see a new folder named “HelloWorld” crated with a directory structure like this:

You can open Program.cs to see its contents. It has a very basic program to display “Hello World!” message.

Step 3: Your .NET console application is ready. First, you have to build it

Type command: dotnet build “HelloWorld”

You can see HelloWorld.exe file is created, in addition to some other files in your folder \HelloWorld\bin\Debug\net5.0

Step 4: Run!

You can simply run the exe file directly going to the location, or by typing this command:

Type command:

Step 5: Alternate way to run the program

Go inside your program folder, i.e., “HelloWorld“, then type command:

dotnet run HelloWorld

or simply, dotnet run

JavaScript Notification API for beginners

Just two steps:

  1. Ask user the permission to send notifications

Notification.requestPermission();

2. Create/send notifiation

notificaiton = new Notification (‘This is a notification’);     

Dapr: The distributed application runtime is now production ready

Dapr - Distributed Application Runtime

Simplify cloud-native application development. Focus on your application’s core logic and keep your code simple and portable

Dapr is an open source, portable, event-driven runtime that makes it easy for developers to build resilient, microservice, stateless and stateful applications that run on the cloud and edge. Dapr enables developers to focus on writing business logic and not solving distributed system challenges, thereby significantly improving their productivity, and reducing development time.

Read more: https://blog.dapr.io/posts/2021/02/17/announcing-dapr-v1.0/
Dapr Home: https://dapr.io/

Why .NET 5.0 and not .NET Core 5.0? And, where is .NET (core) 4.0?

Note the point…

.NET 5.0 is the next major release of .NET Core following 3.1. We named this new release .NET 5.0 instead of .NET Core 4.0 for two reasons:

  • We skipped version numbers 4.x to avoid confusion with .NET Framework 4.x.
  • We dropped “Core” from the name to emphasize that this is the main implementation of .NET going forward. .NET 5.0 supports more types of apps and more platforms than .NET Core or .NET Framework.

ASP.NET Core 5.0 is based on .NET 5.0 but retains the name “Core” to avoid confusing it with ASP.NET MVC 5. Likewise, Entity Framework Core 5.0 retains the name “Core” to avoid confusing it with Entity Framework 5 and 6.

Ref: https://docs.microsoft.com/en-us/dotnet/core/dotnet-five

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
}
}