How to check if nested brackets are in the correct logical order

I am starting a series of blog posts on algorithms and data structures with the first one being the easiest!

Q. Write a method that checks if the nested brackets are in the correct logical order. The input string is the following:

“{ [ () {} ] }”

Please note, there can be many interpretations, but here’s how I am attempting to solve this question which may not necessarily be the most efficient solution. Here it goes…

First off, I create a console app and write a function that removes erroneous spaces like so:

 
        public static String FilterErroneousChars(String input)
        {
            int len = input.Length;
            char[] arr = input.ToCharArray();
            String filter = "";
            for (int i = 0; i < len; i++)
            {
                if (arr[i].Equals('(') || arr[i].Equals(')') || arr[i].Equals('[') || arr[i].Equals(']') || arr[i].Equals('{') || arr[i].Equals('}'))
                {
                    filter += arr[i];
                }
            }
            return filter;
        }

Once the function is executed, it'll return a string with no spaces, i.e. "{[(){}]}".

Next, I call the method from Program Main() and pass in the compressed string as input like so:

Then, I check to see if any of the nested pair(s) is equal. If the condition is met, the program replaces the nested brackets with an empty string until there's nothing left.

In the end, I check to see if the length of the string is 0. Once this condition evaluates to True, we know, that the input string is well-formed, else NOT.

I hope, those of you that are new to data structures, you might find this algorithmic exercise useful.

String s = Algorithms.FilterErroneousChars("{ [ () {} ] }");
            while ((s.Length != 0) && (s.Contains("[]") || s.Contains("()") || s.Contains("{}")))
            {
                s = s.Replace("[]", "");
                s = s.Replace("()", "");
                s = s.Replace("{}", "");
            }

            if (s.Length == 0)
            {
                Console.WriteLine("Well Formed");
            }
            else
            {
                Console.WriteLine("Not Well Formed");
            }

Posted in Algorithms & Data Structures | Comments Off on How to check if nested brackets are in the correct logical order

What package(s) do I need for EF Core 2.x?

First off, it is important to note that there are a couple of ways to download package(s).
1. You can use NuGet right from inside Visual Studio IDE
2. You can also use CLI (Command Line Interface)

Here, I’ll demonstrate both of them.

Even though you could install Microsoft.EntityFrameworkCore, however, you would need a database provider to interact with. Given, that EF Core is modular, and depending on the data-store you want to work with, you would only need to install that specific database provider.

Unlike EF 6.x, where SQL Server is the default database provider; that is not the case with EF Core. EF Core supports a variety of databases that include the following:

  • Microsoft SQL Server
  • SQLite
  • Postgres SQL
  • MySQL
  • SqlServerCompact (By Erik Jensen)
  • In-Memory Testing

When using CLI, you would want to install the following by navigating to Tools – NuGet Package Manager – Package Manager Console.

c:\Install-Package Microsoft.EntityFrameworkCore.SqlServer

If you wish to create a database using Migrations from your POCO classes or what is typically referred as Code-First workflow, you would need to install the following from the command line:

c:\Install-Package Microsoft.EntityFramework.Tools

You might also need Design tools in the event you want to create Controllers and Views using the Scaffolding feature of ASP.NET Core MVC. This can be obtained by installing the following:

c:\Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

In the event where you want to use Visual Studio’s IDE, you can simply navigate to Tools – NuGetPackageManager – Manage NuGet Packages for Solution.

Once, the NuGet Window opens up, you can type in the appropriate package in the Search text field which will give you a list of stable packages unless you check the Include Prerelease check box to the right of the search field.

That’s all there is to it!

Posted in ORM | Comments Off on What package(s) do I need for EF Core 2.x?

Mongo DB and .NET

This is my last blog post of the year 2017 where I am going to showcase how you can make the .NET application talk to a Mongo DB.

Just a quick recap…MongoDB is a document database that stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structures can be changed over time.

If you want to know about Mongo DB, what it is and why you should use it, you can read the article from one of my earlier posts here.

First things first, install the following:

  • Robo 3T from www.robomongo.org

Robo 3T (formerly Robomongo) is the free lightweight GUI embedded shell for MongoDB users.

Launch Visual Studio and create a Console App (.NET Framework).

Now install the following packages from NuGet:

  • MongoDB.Bson
  • MongoDB.Driver
  • MongoDB.Driver.Core

Packages

It’s time to write some code, but before that, add references to the project and use the following namespaces:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using System;
using System.Linq;

Let’s create a POCO class and call it Book. This is done in order for the document model to map to the objects in the application code therefore making data easy to work with.

    public class Book
    {
        public  ObjectId Id { get; set; }
        public string ISBN { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public DateTime Published { get; set; }
        public string Publisher { get; set; }
    }

Let’s insert a record into the book collection like so:

private static void InsertBook()
        {
            var client = new MongoDB.Driver.MongoClient();
            var db = client.GetDatabase("admin");
            var col = db.GetCollection("Books");

            Book objBook = new Book();
            objBook.Id = ObjectId.GenerateNewId();
            objBook.ISBN = "593220";
            objBook.Title = "Debgging Mongo App";
            objBook.Author = "Obi Oberoi, Ken Cenerelli";
            objBook.Published = Convert.ToDateTime("2017-12-31T00:00:00Z");
            objBook.Publisher = "Wrox";

            col.InsertOne(objBook);
        }

To get a book collection, use the code below:

private static void GetAllBooks()
        {
            var client = new MongoDB.Driver.MongoClient();
            var db = client.GetDatabase("admin");
            var col = db.GetCollection("Books");

            foreach(Book doc in col.Find(b=> b.Title.Length > 0)
                    .SortByDescending(b=> b.Title)
                    .ToList())
            {                
                Console.WriteLine("BookID: {0}", doc.Id);
                Console.WriteLine("Title: {0}", doc.Title);
                Console.WriteLine("Author: {0}", doc.Author);
            }
            Console.ReadLine();
        }

Let’s take our code to test by calling the methods from the Main program:

static void Main(string[] args)
        {         
            InsertBook();
            GetAllBooks();            
        }

As you saw in just a few lines of code, one could easily perform CRUD operations against MongoDB with a CLR compliant language such as C#.

Posted in NoSQL | Comments Off on Mongo DB and .NET

What is the difference between Delete and Truncate

To order essay on an author of the essay not only that but safely. Our exchange provides a number of obligations, which guarantee customers that they will receive a high quality and decent work:

each essay is checked by the system Antiplagiat, which ensure that the text was unique;

you made your payment remains “frozen” for the author until the time the student will receive an essay on the order in hand;

real comments and feedback about each expert help to navigate, who to approach and what results to expect.

If you need to order essay on any subject, be sure to contact author of essay on here will execute any order with pleasure and in the shortest time will help you to come to the school with the custom essay uk and best hand.

Other types of work

To the exchange author of essay each day addresses a lot of clients that need professional help. Here  who can do the work of proofreading efficiently and competently. author of essay has such features as:

It employs a lot of specialists who work with different languages. The staff is constantly to big this allows us to assist a lot more often;

The order is carried out only by experienced professionals who have diploma in this field or are the academic staff of the Universities. They thoroughly know their work and can carry out proofreading of articles;

The cost of proofreading text

Exchange author of essay can perform all sorts of work. Proofreading articles, research papers and other assignments is in accordance with all requirements and regulations. As for the cost of proofreading the texts, it may depend on:

Scope of work;

The complexity of the subject;

Deadlines.

For urgent execution, the contractor takes a percentage of the work, as it delays other work and perform an urgent task.

Posted in ORM | Comments Off on What is the difference between Delete and Truncate

What are Nested Transactions in SQL Server?

As the name suggests, nested transaction is one that is nested within a transaction. Let’s illustrate this with an example.

Let’s create a table:

CREATE TABLE PERSON
(
	ID INT IDENTITY(1,1),
	FirstName VARCHAR(25),
	LastName VARCHAR(25),
	Gender CHAR(1)
)
SELECT * FROM PERSON

As you can see, we have a table Person with no records.


Let’s initialize a transaction and view its count

BEGIN TRANSACTION  -- 1st Transaction
SELECT @@TRANCOUNT AS TrxCount

Now, insert a record into the table

INSERT INTO PERSON VALUES ('Bill', 'Meyer', 'M')
SELECT * FROM PERSON

Let’s initialize a second transaction and view its count:

BEGIN TRANSACTION -- 2nd Transaction
SELECT @@TRANCOUNT AS TrxCount

Let’s insert another record and then view its contents. Mind you, we are currently in a nested transaction.

INSERT INTO PERSON VALUES ('Lisa', 'Ray', 'F')
SELECT * FROM PERSON

Now, let’s rollback the transaction and do a count immediately afterwards.

--Rollback Transaction
ROLLBACK
SELECT * FROM PERSON
SELECT @@TRANCOUNT AS TrxCount


The rollback rollsback to the outermost transaction that was defined. Another thing to keep in mind is that you don’t need a COMMIT TRANSACTION in order to ROLLBACK.

Posted in SQL Server | Comments Off on What are Nested Transactions in SQL Server?

How to partition the result set in SQL Server

To query the first row or the last row in a table is easy-piecey.  You simply select the Top 1 row and order the query by ascending or descending. But, how about selecting the second, third or tenth row from a table that meets a certain criteria. That’s when the query gets little tricky.

I’ll show you an easy approach from start to finish. Below is a snapshot of an Employee table with a list of employees and their salaries. The Employee table as you can see is ordered by ID with a list of random salaries.

Employee Table in Descending Order:

Max Salary:

To get a maximum salary from the employee table, the MAX() function is used to get the value. Easy eh!

How about if you want to get the second highest salary? How would you shape your query? One way is to write a sub-query like so:

SELECT MAX(Salary) AS 'Max Salary'
FROM
	Employee
WHERE
	Salary < (SELECT MAX(Salary) FROM Employee)


OR

You can also do something like this, although you'll have to do a mental math to write the following query in order to get the second highest salary:

SELECT
	TOP 1 Salary 
FROM
	(SELECT DISTINCT TOP 2 Salary
	FROM
		Employee
	ORDER BY 
		Salary DESC)
	RESULT
ORDER BY
	Salary

Using DENSE_RANK() function:

WITH RESULT AS
(
SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS RANK
FROM
	Employee
)
Select TOP 1 Salary from RESULT
WHERE RANK = 3

Summary:

The thing to remember is that numbers returned by DENSE_RANK function do not have gaps and invariably use consecutive ranks.

Happy coding 🙂

Resources

Microsoft

Posted in SQL Server | Comments Off on How to partition the result set in SQL Server

What is IDENTITY value and how does it work?

An IDENTITY is a system function that returns the last-inserted identity value.

Let’s try it out in SQL Server Management Studio. Let’s create a table called Person with it’s IDENTITY starting position set to 1 with an increment value of 1 as well.

CREATE TABLE PERSON
(
	ID INT IDENTITY(1,1) PRIMARY KEY,
	FirstName VARCHAR(25),
	LastName VARCHAR(25),
	Gender CHAR(1)
)

Let’s insert three records and view them

INSERT INTO PERSON VALUES ('Bill', 'Meyer', 'M')
INSERT INTO PERSON VALUES ('Lisa', 'Ray', 'F')
INSERT INTO PERSON VALUES ('Scott', 'Johnson', 'M')
SELECT * FROM PERSON

As you can see, the first record has a starting ID of 1 and is incremented by 1.

Now let’s try and create another table and modify its IDENTITY settings a little bit:

CREATE TABLE PEOPLE
(
	ID INT IDENTITY(1000,10) PRIMARY KEY,
	FirstName VARCHAR(25),
	LastName VARCHAR(25),
	Gender CHAR(1)
)

Notice the IDENTITY now starts a 1000 with an increment value of 10.

Let’s insert three records into the PEOPLE table.

INSERT INTO PEOPLE VALUES ('Bill', 'Meyer', 'M')
INSERT INTO PEOPLE VALUES ('Lisa', 'Ray', 'F')
INSERT INTO PEOPLE VALUES ('Scott', 'Johnson', 'M')
SELECT * FROM PEOPLE

To view the last ID that was inserted into the PEOPLE table, you can do so by issuing the following query:

SELECT @@IDENTITY AS 'Identity'

Posted in ORM | Comments Off on What is IDENTITY value and how does it work?

What is Mongo DB and why should you use it!

The word Mongo is derived from the world humongous. So in essence, it implies that its sole purpose is to store mammoth amounts of data or what is otherwise coined as ‘big data’.

MongoDB is a document oriented database unlike its traditional relational counterparts such as SQL Server, DB2, Oracle, PostgreSQL etc.  MongoDB uses a JSON like syntax which is made up of name value pairs.

The fact that MongoDB is a document database, one of the rules that govern MongoDB is that every document must be unique. Hence it should have an ID. It’s also important to remember that the size of this document is typically 16MB.

MongoDB is elastic and therefore scales horizontally unlike RDBMS that scale vertically.

One of the key concepts of MongoDB is that there should always be a copy of the primary database (although not required), it is recommended that there be at least two copies of a database. In the event of a failure of primary database, the database can be restored from one of secondary servers.

The world we live in today where businesses are constantly evolving, billions of people and ‘things’ are always communicating, changing the way organizations and customers interact with each other and the environment around them. Data comes from different geographical locations and across multiple channels. Managing this explosion of high-velocity dynamic data while maintaining customer privacy is a challenge with legacy systems to say the least. That said, data is therefore of paramount importance for any organization large or small.

The solution to support rapidly growing applications is to scale horizontally by adding servers instead of concentrating more capacity in a single server. NoSQL databases, on the other hand, usually support auto-sharding, meaning that they natively and automatically spread data across an arbitrary number of servers, without requiring the application to even be aware of the composition of the server pool. Data and query load are automatically balanced across servers, and when a server goes down, it can be quickly and transparently replaced with no application disruption. This is especially an ideal situation for web applications.

While it is true that NoSQL databases lack transaction support and semantics database element that offers guarantees about data consistency and persistence. This is a solid tradeoff based on MongoDB’s goal of being simple, fast, and scalable. Once you leave those heavyweight features at the door, it becomes much easier to scale horizontally.

Some of the big 20 companies such as Google, Facebook, LinkedIn use NoSQL databases and it fits very well with their business model. That said, MongoDB has truly become a global company with over 50,000 members, 100 User Groups all around the world. As it stands right now, MongoDB has 29 offices in 14 different countries with over 3000 customers.

What’s in MongoDB

  • Key-values stores (JSON like syntax i.e. key/value pairs)
  • Column Family Stores (hierarchical schemas)
  • Document Databases
  • Multi-nested data
  • High velocity data coming at a very high rate of speed
  • Graph Databases
  • Unstructured data and by not enforcing transactional consistency
  • Document oriented databases are schema-agnostic. This allows for agility and highly iterative development
  • Durability when used in tandem with at least three servers (minimum)
  • Profiling Queries

Types of NoSQL Databases

Is MongoDB the Right Choice?

While it’s all fine and dandy to jump to this new shiny NoSQL database, but you ought to step back and ask yourself the following questions:

  • What are some of characteristics of my data?
  • What are the business needs of my data?
  • Am I required to query across multiple tables and possibly across multiple databases?
  • Do I need my data to be transactional?

Benefits

There’s no question, when compared to relational databases, NoSQL databases are more scalable and provide superior performance. Following are some of its benefits:

  • Speed and large volumes of rapidly changing structure, semi-structure and unstructured data
  • Open source, hence mostly Free
  • Object-oriented programming that is easy to use and flexible
  • Simplicity (with virtually no complex rules i.e. tables, relationships and less Object-Relational impedance mismatch
  • Geographically distributed scale-out architecture instead of expensive, monolithic architecture

Format

MongoDB uses an open data forma called BSON which is similar to the JSON format. The BSON data format was developed by the MongoDB team. This format is special in that it facilitates searching of documents rapidly including the ability to add types for handling binary data. MongoDB stores data in BSON documents which is self-contained.

Scaling

Relational databases are designed to scale vertically, in that a single server has to host the entire database to ensure acceptable performance for cross-table joins and transactions. This can become an expensive proposition while placing limits on scale. The solution to support rapidly growing applications is to scale horizontally, by adding servers or cloud instances instead of concentrating more capacity in a single server.

References

www.MongoDB.com

http://Dataconomy.com/sql-vs-nosql-need-know

Posted in NoSQL | Comments Off on What is Mongo DB and why should you use it!

Are stored procedures pre-compiled?

Contrary to the popular belief that a stored procedure is pre-compiled when created is not true.
In fact, stored procedure is compiled on the first run or the time when the stored procedure is first executed.

more to come…

Posted in ORM | Comments Off on Are stored procedures pre-compiled?

What is Managed and Unmanaged Code?

Managed Code:

The .NET framework provides several core run-time services to the programs that run within it. For example; Exception Handling and Security. In order for these services to work, the code must provide a minimum level of information to the runtime. Code that executes under the control of the runtime is called Managed Code.

Similarly, the data that is allocated and freed by the .NET runtime’s garbage collector is called Managed Data.

Benefits of CLR:

  1. Objects are self-describing
  2. Provides Code-Access-Security
  3. Assembly based deployment to avoid DDL hell
  4. Code development made easy
  5. Side-by-side versioning of reusable components
  6. Automatic Object Lifetime Management
  7. Seamless integration between CLR compliant languages

Unmanaged Code:

Code that runs outside the runtime is called unmanaged code. COM components, ActiveX interfaces, and Win32 API functions are examples of Unmanaged Code. If you have coded in VB 6 or VC++, chances are you are already familiar with these unmanaged applications. In essence, unmanaged code is one that compiles directly to machine code. Unmanaged code lacks some of the key features such as Code-Access-Security or Memory management which were not available in the runtime. However, it was only accessible through the operating system through API calls provided in the Windows SDK.

Interoperability:

The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object.

The image below shows how COM objects can be accessed through the runtime callable wrapper.

Consuming COM from .NET:

Following are the steps to expose COM components to the .NET Framework:

  • Import a type library as an assembly
  • Create COM types in managed code
  • Compile an interop object
  • Deploy an interop application

Please note, starting with VS 2010, you can embed type information from an interop assembly directly into your executable by instructing the compiler.

Resources:

MSDN

Microsoft Docs

 

 

Posted in .NET | Leave a comment