Thursday 27 February 2020

Mongodb for beginners (Starting to end)

MongoDB is a rich document-oriented NoSQL database

In order to work with MongoDB, first we need to install MongoDB in our computer. To do this, visit the official download center and download the version for your specific OS. (Here i am talking about windows)

next is installation process. Once done, head over to the place where you installed MongoDB. Go to (C: -> Program Files -> MongoDB -> Server -> 4.0(version) -> bin)

In the bin directory, you’ll find an interesting couple of executable files.

mongod
mongo
Let’s talk about these two files.

mongod stands for “Mongo Daemon”. mongod is a background process used by MongoDB. The main purpose of mongod is to manage all the MongoDB server tasks. For instance, accepting requests, responding to client, and memory management.

mongo is a command line shell that can interact with the client (for example, system administrators and developers).

Now let’s see how we can get this server up and running. To do that on Windows, first we need to create a couple of directories in your C drive. Open up your command prompt inside your C drive and do the following:

C:\> mkdir data/db
C:\> cd data
C:\> mkdir db

The purpose of these directories is MongoDB requires a folder to store all data. MongoDB’s default data directory path is /data/db on the drive. Therefore, it is necessary that we provide those directories like so.

If you start the MongoDB server without those directories, you’ll get error

We can always work by going to the mongodb bin folder and we can execute the necessary mongodb commands from there. But to save time
we can set up your environment variables by doing Advanced System Settings -> Environment Variables -> Path(Under System Variables)

Simply copy the path of our bin folder and hit OK! In my case it’s C:\Program Files\MongoDB\Server\4.0\bin-> Edit

Working with MongoDB

There’s a bunch of GUIs to work with MongoDB server such as MongoDB Compass, Studio 3T and so on.

They provide a graphical interface so you can easily work with your database and perform queries instead of using a shell and typing queries manually.

But in this article we’ll be using command prompt to do our work so that we can become master of mongodb memory.

Now it’s time for us to dive into MongoDB commands that’ll help you to use with your future projects.

1. Open up your command prompt and type mongod to start the MongoDB server.
2. Open up another shell and type mongo to connect to MongoDB database server.

In MongoDB, the first basic step is to have a database and collection in place. The database is used to store all of the collections, and the collection in turn is used to store all of the documents. The documents in turn will contain the relevant Field Name and Field values.


The "use" command is used to create a database in MongoDB. If the database does not exist a new one will be created.MongoDB will automatically switch to the database once created.

Wednesday 26 February 2020

Use of System.Environment Class and Why is XmlSerializer so slow

System.Environment Class
The System.Environment Class provides information about the current environment and platform. The System.Environment Class uses to retrieve Environment variable settings, Version of the common language runtime, contents of the call stack etc. This class cannot be inherited.
How to get Current working directory ?
System.Environment.CurrentDirectory - will return your current working directory
How to get Machine Name ?
System.Environment.MachineName - will return your current machine name.
How to get current Operating System Version ?
System.Environment.OSVersion.ToString () - will return your current operating system version
How to get the current user name of the system ?
System.Environment.UserName - will return your current user name
=====================

Why is XmlSerializer so slow?

The XmlSerializer It makes extensive use of reflection to extract information about the fields of an object. Any time reflection becomes involved, performance drops drastically. Another reason is that there is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

XML Serialization

XML Serialization is the process of serializing a .Net Object to the form of XML or from an XML to .Net Object. The primary purpose of XML serialization in the .NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa. This is the process of converting an object into a form that can be readily transported.

What is .Net serialization

Serialization can be defined as the process of converting the state of an object instance to a stream of data, so that it can be transported across the network or can be persisted in the storage location. The advantage of serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent state of an object to a storage medium so an exact copy can be recreated at a later stage. Deserialization is its reverse process, that is unpacking stream of bytes to their original form.
Any attempt to pass the object as a parameter or return it as a result will fail unless the object derives from MarshalByRefObject. This process of serializing an object is also called deflating or marshalling an object. If the object is marshalling or it is marked as Serializable, the object will automatically be serialized.
The following program will show how to Serialize an Object and later De-serialize it.

using System;
using System.IO ;
using System.Windows.Forms;
using System.Runtime.Serialization;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//serializing the object
private void button1_Click(object sender, EventArgs e)
{
serializeObject srObj = new serializeObject();
srObj.srString = ".Net serialization test !!";
srObj.srInt = 1000;
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Stream fileStream = new FileStream("c:\\SerializeFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(fileStream, srObj);
fileStream.Close();
MessageBox.Show("Object Serialized !!");
}
//de-serializing the object
private void button2_Click(object sender, EventArgs e)
{
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Stream serialStream = new FileStream("c:\\SerializeFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
serializeObject srObj = (serializeObject)formatter.Deserialize(serialStream);
serialStream.Close();
MessageBox.Show(srObj.srString + "      " + srObj.srInt.ToString ());
}
}
//specimen class for serialization
[Serializable]
public class serializeObject
{
public string srString = null;
public int srInt = 0;
}
}

Difference between a Debug and Release build

Debug mode and Release mode are different configurations for building your .Net project. Programmers generally use the Debug mode for debugging step by step their .Net project and select the Release mode for the final build of Assembly file (.dll or .exe).
The Debug mode does not optimize the binary it produces because the relationship between source code and generated instructions is more complex. This allows breakpoints to be set accurately and allows a programmer to step through the code one line at a time. The Debug configuration of your program is compiled with full symbolic debug information which help the debugger figure out where it is in the source code.
Is Release mode is faster than Debug mode ?
The Release mode enables optimizations and generates without any debug data, so it is fully optimized. . Lots of your code could be completely removed or rewritten in Release mode. The resulting executable will most likely not match up with your written code. Because of this release mode will run faster than debug mode due to the optimizations.
What is .pdb files ?
Debug information can be generated in a .pdb (Program Database File) file depending on the compiler options that are used. A .pdb file holds debugging and project state information that allows incremental linking of a Debug configuration of your program. A Program Database File is created when you compile a VB.Net or C# program with debug mode.
In Asp.Net ?
It is important to note that Debug mode or Release mode in a web application is controlled by the web.config file, not your settings within Visual Studio.
e.g.
<system.web>
    <compilation debug="true">

Difference between normal DLL and .Net DLL

A .dll file contains compiled code you can use in your application to perform specific program functions and may be required by another application or module (such as .exe or .dll) to load it through an entry point. It is a library that contains code and data that can be used by more than one program at the same time. It helps promote modularization of code, code reuse, efficient memory usage, and reduced disk space. So the operating system and the programs load faster, run faster, and take less disk space on the computer.
What is .Net dll ?
When you implement a .Net DLL (Assembly) in .NET Languages such as C# or VB.NET you produce a Managed Assembly. Managed Assembly is the component standard specified by the .NET. Hence, .Net assemblies are understandable only to Microsoft.NET and can be used only in .NET managed applications. A manage assembly contains managed code and it is executing by the .NET Runtime. When you create a DLL with C++ you produce a win32/Com DLL. If you use this dll in a .NET Language, the Visual Studio create automatically an INTEROP file for you, so you can call the "unmanaged" dll from manage code .
For using a .Net DLL (Assembly), the simplest option is to copy the dll to the bin folder. Normal DLL files are need to be register with the "regsvr32" tool.

Differences between Stack and Heap

Stack and a Heap ?
Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM .
Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.
Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.

You can use the stack if you know exactly how much data you need to allocate before compile time and it is not too big. You can use heap if you don't know exactly how much data you will need at runtime or if you need to allocate a lot of data.
In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap. Stack is thread specific and Heap is application specific. The stack is important to consider in exception handling and thread executions.

Difference between Shallow copy and Deep copy

An object copy is a process where a data object has its attributes copied to another object of the same data type. In .Net Shallow copy and deep copy are used for copying data between objects.

What is Shallow copy ?

shallow-copy c# vb.net

Shallow copying is creating a new object and then copying the non static fields of the current object to the new object. If the field is a value type, a bit by bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not, therefore the original object and its clone refer to the same object. A shallow copy of an object is a new object whose instance variables are identical to the old object. In .Net shallow copy is done by the object method MemberwiseClone().

The situations like , if you have an object with values and you want to create a copy of that object in another variable from same type, then you can use shallow copy, all property values which are of value types will be copied, but if you have a property which is of reference type then this instance will not be copied, instead you will have a reference to that instance only.

What is Deep copy ?

deep-copy c# vb.net

Deep copy is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type, a bit by bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed. A deep copy of an object is a new object with entirely new instance variables, it does not share objects with the old. While performing Deep Copy the classes to be cloned must be flagged as [Serializable].

Deep copy is intended to copy all the elements of an object, which include directly referenced elements of value type and the indirectly referenced elements of a reference type that holds a reference to a memory location that contains data rather than containing the data itself.

Difference between Component and Control

Differences between a control and a component

A component is a class that implements the IComponent interface or that derives directly or indirectly from a class that implements IComponent.

public class BaseComponent : IComponent {}

A component does not draw itself on the form, but a control draws itself on the form or on another control. Both the Components and the Controls can be dropped onto a design surface. If you double click the item on the toolbox and it will get placed inside the form then it the item known as Controls where as the item placed below the form area (component tray) then it is known as component.
e.g. Timer is a component and that has no visual representation during runtime, but you can see it in the component tray during the design time. Progress Bar is a control and it has visual representation in both design time and runtime.
All controls are also components, but not all components are controls.
You can create a component if you want to provide functionality without UI such as with the BackgroundWorker component, then you would only need to derive from Component directly. e.g. Timer , Data Source etc.. You can create a custom control if you want to make a component where you have full control over its visual appearance. e.g. Textbox , Button etc..

Tuesday 25 February 2020

Difference between a Thread and a Process

A process is an executing instance of an application. For example, when you double-click the Microsoft Word icon, you start a process that runs Word. A thread is a path of execution within a process. Also, a process can contain multiple threads. When you start Word, the operating system creates a process and begins executing the primary thread of that process.
It's important to note that a thread can do anything a process can do. But since a process can consist of multiple threads, a thread could be considered a 'lightweight' process. Thus, the essential difference between a thread and a process is the work that each one is used to accomplish. Threads are used for small tasks, whereas processes are used for more 'heavyweight' tasks – basically the execution of applications.
Another difference between a thread and a process is that threads within the same process share the same address space, whereas different processes do not. This allows threads to read from and write to the same data structures and variables, and also facilitates communication between threads. Communication between processes – also known as IPC, or inter-process communication – is quite difficult and resource-intensive.
======================================================================
The processes and threads are independent sequences of execution, the typical difference is that threads run in a shared memory space, while processes run in separate memory spaces.
A process has a self contained execution environment that means it has a complete, private set of basic run time resources purticularly each process has its own memory space. Threads exist within a process and every process has at least one thread.
Each process provides the resources needed to execute a program. Each process is started with a single thread, known as the primary thread. A process can have multiple threads in addition to the primary thread.
On a multiprocessor system, multiple processes can be executed in parallel. Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.
Threads have direct access to the data segment of its process but a processes have their own copy of the data segment of the parent process.
Changes to the main thread may affect the behavior of the other threads of the process while changes to the parent process does not affect child processes.
Processes are heavily dependent on system resources available while threads require minimal amounts of resource, so a process is considered as heavyweight while a thread is termed as a lightweight process.
What is multithreading ?
In .NET languages you can write applications that perform multiple tasks simultaneously. Tasks with the potential of holding up other tasks can execute on separate threads is known as multithreading.

Friday 14 February 2020

Concept of Startup Class In ASP.NET Core

This class is described by its name: startup. It is the entry point of the application. It configures the request pipeline which handles all requests made to the application. The inception of startup class is in OWIN (Open Web Interface for.NET) application that is specification to reduce dependency of application on server.
Is Startup Class mandatory?
Yes, this class is mandatory in ASP.net core application. It can have any access modifier (public, private, internal). This is the entry point of the ASP.net application. It contains application configuration related items.
Must the name of class be "Startup"?
No, it is not necessary that the class name be "Startup". The ASP.net core application is a Console app and we have to configure a web host to start listening. The "Program" class does this configuration.
Following is sample code for Program class,
  1. public class Program  
  2. {  
  3.     public static void Main(string[] args)  
  4.     {  
  5.             var host = new WebHostBuilder()  
  6.             .UseKestrel()  
  7.             .UseContentRoot(Directory.GetCurrentDirectory())  
  8.             .UseStartup<Startup>()  
  9.             .Build();  
  10.             host.Run();  
  11.     }  
  12. }  
The web host is created in the main method of the Program class and here we have configuration of startup class using method "UseStartup". So it is not necessary that class name is "Startup".
Following is a typical startup class example.
  1. public class Startup   
  2. {  
  3.     public void Configure(IApplicationBuilder app)  
  4.     {  
  5.       
  6.     }  
  7.     public void ConfigureServices(IServiceCollection services)  
  8.     {  
  9.   
  10.      }       
  11. }  
Startup Class Constructor 
We can also specify constructor of the startup class. The startup class has constructor with one or three parameters.
  1. public Startup(IHostingEnvironment env)      
  2. {   
  3.   
  4. }  
  5.   
  6. public Startup(IApplicationBuilder appenv, IHostingEnvironment env,  ILoggerFactory loggerFactory)  
  7. {  
  8.   
  9. }  
IApplicationBuilder is an interface that contains properties and methods related to current environment. It is used to get the environment variables in application.
IHostingEnvironment is an interface that contains information related to the web hosting environment on which application is running. Using this interface method, we can change behavior of application.
IloggerFactory is an interface that provides configuration for the logging system in Asp.net Core. It also creates the instance of logging system.
The startup class contains two methods: ConfigureServices and Configure.
ConfigureServices Method
Declaration of this method is not mandatory in startup class. This method is used to configure services that are used by the application. When the application is requested for the first time, it calls ConfigureServices method. This method must be declared with a public access modifier, so that environment will be able to read the content from metadata.
ASP.net core has built-in support for Dependency Injection. We can add services to DI container using this method. Following are ways to define ConfigureServices method in startup class.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.         services.AddMvc();  
  4. }   
In case of specific class or library of project that would like to add to DI container, we will use the IserviceCollection. In the above example, I have just add MVC service to the ConfigureServices method.
Configure Method
This method is used to define how the application will respond on each HTTP request i.e. we can control the ASP.net pipeline. This method is also used to configure middleware in HTTP pipeline. This method accept IApplicationBuilder as a parameter. This method may accept some optional parameter such as IHostingEnvironment and ILoggerFactory. Whenever any service is added to ConfigureServices method, it is available to use in this method.
  1. public void Configure(IApplicationBuilder app)  
  2. {  
  3.     app.UseMvc();  
  4.   
  5.     app.Run(context => {  
  6.         return context.Response.WriteAsync("Hello Readers!");  
  7.     });  
  8. }  
In the above example, I have added "UseMvc" method, so system will know MVC framework need to use to handle user requests. With this method, we can also pass some additional option parameters.
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  2. {  
  3.     loggerFactory  
  4.         .AddConsole()  
  5.         .AddDebug();  
  6.   
  7.         app.UseMvc();  
  8.     
  9.     app.Run(context => {  
  10.         var logger = loggerFactory.CreateLogger("TodoApi.Startup");  
  11.         return context.Response.WriteAsync("Hello Readers!");  
  12.     });  
  13. }  
In the above example, I have added the logger console and the debug logger and MVC service. The app.Run method adds a terminal middleware delegate to the application's request pipeline.
Summary
The Startup class is mandatory and it is the entry point of the application. With the help of this class we can configure the environment in our ASP.net Core application. We can use Constructor and two different methods: ConfigureServices and Configure for setting up the environment. This class creates services and injects services as dependencies so the rest of the application can use these dependencies. The ConfigureServices used to register the service and Configure method allow us to add middleware and services to the HTTP pipeline. This is the reason ConfigureServices method calls before Configure method.

Tuesday 11 February 2020

Need to know and must have to become a Software Architect

What does a software architect do?

A software architect is an expert-level software developer who communicates with businesses and clients to design and execute solutions with a team of software engineers. A software architect makes executive software design decisions. They often act as a designer, developer and communicator. Responsibilities include:
  • Researching and evaluating technical standards and tools for a project and determining which ones are the optimal choice
  • Separating a project’s goal into several smaller solvable problems
  • Communicating business requirements, criteria and needs to software development teams
  • Designing and revising a project’s structure and UML (Unified Modeling Language) diagram
  • Distributing development tasks to a team of software engineers
  • Quality assurance testing segments of project code and checking for errors
  • Writing sections of code as part of development in a project

Average salary

Most software architects are full-time salaried employees, though some freelance or work contract positions. The salary for a software architect will vary based on regional factors, qualifications and certifications and the size of the development team.
  • Common salary in the U.S.: $140,419 per year
  • Some salaries range from $49,000 – $277,000 per year

Software architect requirements

Software architects have years of training and experience in software development and design. Some earn certifications to widen their job search and increase their earning potential.

Education

Usually, software architects will have at least a bachelor’s degree in computer science, information systems, software engineering or another related field. However, software architect positions favor training and experience over a degree, and it is possible to get a software architect position with no degree at all. Some software architects earn their master’s or doctoral degrees to gain more knowledge in the field.

Training

As a general guideline, software architects usually receive training in:
  • DevOps**:** Development Operations, or DevOps, is a set of practices intended to speed up the software development process at every step. Trained software architects typically implement and manage DevOps practices and solutions within their development team to increase efficiency.
  • Systems design: Software architects design and maintain the structure of a software project. Training in UML or systems design prepares a software architect for their role in the development team.
  • Programming: Software architects usually train in computer programming and have a working knowledge of multiple programming languages and frameworks.
Software architects could receive training in these topics on the job with their company, or off the job at seminars and conferences. Many software architects attend seminars and conferences to keep up to date with a continually changing technological industry.

Certifications

There are hundreds of certifications that a software architect may obtain. Which certifications a software architect will need will vary depending on the development team and the projects the software architect will oversee. Here are two commonly useful certifications a software architect may seek:
  • OMG Certified UML Professional 2 (OCUP 2): The OCUP 2 is a certification in UML offered by The Object Management Group. Most software architects work primarily with UML when designing project structures, and a certification in working with UML shows that a software architect is capable of systems design and dedicated to their role in the development process. If you plan to earn an OCUP 2 certification, plan to pass the Foundation exam before earning Advanced and Expert certifications.
  • Microsoft Azure Certification: Microsoft’s Azure certification program can serve as a general DevOps certification for software architects. A comprehensive understanding of the DevOps process is a requirement for modern software developers in any role. There are nine Azure certification exams you can take to show a thorough knowledge of the service.

Skills

Some skills software architects require are:
  • Problem-solving: The primary responsibility of a software architect is to act as a problem-solver. A business provides the architect with a broad request and the architect must separate the request into smaller distinct problems they can solve with the software development team.
  • Organization: Software architects often create and update large and intricate UML diagrams of a software project as it proceeds through the production cycle. Understanding designing requires an architect to think systematically and keep detailed sections of a project organized.
  • Attention to detail: A software architect should ensure the functionality of each segment of a project, and must be able to easily check project code for quality assurance to prevent any codes issues from reaching a project’s release. On large-scale projects, this requires the architect to quickly and accurately read thousands of lines of code and have the insight to know what common errors to seek.
  • Leadership: Software architects oversee the development of a project and manage the responsibilities of a team of developers, each completing distinct parts of an application. Coordinating the work of a team of developers and ensuring that each segment of a project meets the standards of the design requires strong leadership abilities.
  • Communication: Software architects often decide about a project that balances the needs of the business and the capabilities of the development team. To create a healthy compromise, architects must be able to communicate the requirements of a project to their team and develop a reasonable timeline for project completion based on their teams’ suggestions.
  • Creativity: The ability to process a situation in unique and creative ways allows for a software architect to find alternative solutions to issues that arise during the development of a project and helps reinforce their problem-solving abilities. Creativity can also assist a software architect in designing a project’s UML structure.

Software architect work environment

As a software architect, you will typically work full time in an office environment with your development team. You may conduct some of your work remotely or interface with other developers as they work off-site. Software architects typically work full time on weekdays and sometimes extra hours in the evenings or over the weekend to meet timeline goals with projects. You should be able to sit in front of a computer for extended periods of time.

How to become a software architect

You can follow these general steps to become a software architect:
  1. Earn a degree. Even though a degree is not always necessary for a position as a software architect, earning a bachelor’s in computer science, software engineering or another related field will make you a more competitive candidate when you’re seeking development positions. A degree in one of these fields will also provide you with much of the fundamental training you need to become a developer.
  2. Start your career as a software engineer or developer. Spending time as a software engineer or developer will help develop relevant skills and knowledge in the technology industry. Software architects often have between four and eight years of development experience when they acquire their positions.
  3. Build a portfolio. This may mean developing software on your own or earning certifications in development technologies. The stronger your resume is, the easier it is to find a software architect position.
  4. Try to earn a promotion. While you’re employed as a software engineer or developer, express interest in the role of a software architect. Your employer may offer you the opportunity for advancement without having to search for a software architect position elsewhere.

Software Architect job description example

MathCubed Software is seeking an experienced developer to fill the role of software architect for a new project we’re undertaking. The software architect needs to be able to interpret business requirements and make high-level structural decisions about the direction of the project. You will assign software engineers with their segments of the project and guide them using UML to design and communicate system specifications. In addition, you will provide preliminary quality assurance to the development team and may be required to develop elements of the project yourself. 
The optimal candidate for this role has strong technical skills and leadership abilities. A bachelor’s degree is preferred. At least four years of professional software development experience is required for this position.

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...