Search This Blog

Thursday, 31 August 2017

Export unique event log in text file using Microsoft.PowerShell

Example 1: Get event logs on the local computer

In the below give below result

  • Get the ten most recent entries from a specific event log on the local computer, This command gets the ten most recent entries from the Application event log.
  • Get error, warning events from a specific event log. E.g. "Error"
  • Get all errors in an event log that occurred during a specific time frame
  • Get the unique entries from a specific event log on the local computer.
  • Get the MachineName, Source, EntryType, Message properties from entries from a specific event log on the local computer.
  • Export the EventLog in text file to specific server location.

Script

$AfterDate = (Get-Date -Date '26/8/2017');
$Message = Get-EventLog  -LogName "Application" -EntryType Error, Warning -Newest 10  -Source "BizTalk Server" -After $AfterDate -ComputerName "localhost" 
$Message = $Message | Format-List -Property MachineName, Source, EntryType, Message 
$Message = $Message | select -uniq;
$Message >> \\ServerName\c$\Users\harshal.chaudhari\SystemErrors.txt

Result


MachineName : ServerName
Source      : BizTalk Server
EntryType   : Warning
Message     : An error occurred that requires the BizTalk service to terminate. The most common causes are the 
              following:
               1) An unexpected out of memory error.
               OR
               2) An inability to connect or a loss of connectivity to one of the BizTalk databases. 
               The service will shutdown and auto-restart in 1 minute. If the problematic database remains 
              unavailable, this cycle will repeat.

Rerefence



Thursday, 17 August 2017

Identify if IIS is Running on a Server

PowerShell Script

Identify IIS is running on Remote server.

$vm = "localhost"
$iis = get-wmiobject Win32_Service -ComputerName $vm -Filter "name='IISADMIN'"
if($iis.State -eq "Running")
{
 Write-Host "IIS is running on $vm"
}
else
{
 Write-Host "IIS is not running on $vm"
}

Friday, 11 August 2017

Bad Smells in Code

  • Duplicate code If you see the same code structure in more than one place.

  • Long Method The longer a procedure is, the more difficult it is to understand.

  • Large Class When a class is trying to do too much.

  • Long Parameter List Don't pass in everything the method needs; instead you pass enough so that the method can get to everything it needs.

  • Divergent Change When one class is commonly changed in different ways for different reasons. (You likely have a situation in which two objects are better than one.)

Heads up! When you feel the need to write a comment, first try to refactor the code .so that any comment becomes superfluous.

C# Code Review CheckList

  1. https://azure-blaze.blogspot.com/2017/08/is-renaming-worth-effort.html

  2. https://azure-blaze.blogspot.com/2017/08/bad-smells-in-code.html


Heads up! Any fool can write code that a computer can understand. Good Programmers write code that humans can understand.

Is renaming worth the effort?

  • Good code should communicate what it is doing clearly.

  • Never be afraid to change the name of things to improve clarity.

  • Code that communicates its purpose is very important.

Heads up! Any fool can write code that a computer can understand. Good Programmers write code that humans can understand.

ASP.Net Web API vs WCF, which one should I choose?

  • Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.

  • Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.

  • Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).

  • Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles and tablets.

Web Service Vs WCF

WCF Web API
It is based on SOAP and return data in XML form. It is also based on SOAP and return data in XML form.
It support only HTTP protocol. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
It is not open source but can be consumed by any client that understands xml. It is not open source but can be consumed by any client that understands xml.
It can be hosted only on IIS. It can be hosted with in the applicaion or on IIS or using window service.

WCF REST Vs Web API

WCF REST Web API
To use WCF as WCF Rest service you have to enable webHttpBindings. This is the new framework for building HTTP services with easy and simple way.
It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
It support XML, JSON and ATOM data format.
  • It can be hosted with in the application or on IIS.
  • It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  • Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

Authentication Vs Authorization

Authentication Authorization
Accepts credentials from a user. Given the authentication credentials supplied, determined the rights to access a resource.
Validates the Credentials. Can be assigned by user name or by role.

Server-Side State Vs Client-Side State

Server-Side State Management Client-Side State Management
Application state information is available to all users of a web application. CookiesTest file stores information to maintain state.
Session state information is available only to a users of a specific session. The ViewState Property Retain values between multiple requests for the same page.
Database In some cases, use database support to maintain state on your website. Query string information appended to the end of a URL.

DataSet Vs DataReader


DataSet DataReader
Read/write access to data. Read only.
Includes multiple tables from different databases. Based on the one SQL statement from one database.
Disconnecteed. Connected.
Bind to multiple controls. Bind to one control only.
Forward and backward scanning of data. Forward-only.
Slower access. Faster access.
Supported by Visual Studio .NET tools Manually Coded.

HTML Server Controls Vs Web Server Controls


HTML Server Controls Web Server Controls
You prefer an HTML-like object model. You prefer a Visual Basic like programming model.
You are working with existing HTML pages and want to quickly add ASP.NET web page functionality. You are writing a page that might be used by a variety of browsers.
The control will interact with client and server script You need specific functionality such as a calendar or ad rotator.
Bandwidth is limited. Bandwidth is not a problem.

Common Language Runtime

The Common language run-time simplifies application development provides a robust and secure execution environment, support multiple language and simplifies application deployment and management.

Common Language Runtime Components


.Net Framework class Library Support
Thread Support COM Marshaler
Type Checker Exception Manager
Security Engine Debug Engine
MSIL to Native Complier Code manager Garbage Collector
Class Loader
Component Description
Class Loader Manages metadata , in addition to the loading and layout of classe.
MSIL to Native Compiler Convert MSIL to Native code (Just-in-time JIT Compilation)
Code Manager Manages code execution.
Garbage Collector Provides automatic lifetime management of all your object. This is a multiprocessor, scalable garbage collector.
Security engine Provides evidence-based security that is based on the origin of the code and the user.
Debug engine Allow you to debug your application and trace the execution of the code.
Type Checker Will not allow unsafe casts or uninitialized variables. MSIL can be verified to guarantee type safety.
Exception Manager Provides structured exception handling, which is integrated with Microsoft Windows structured exception handling.
Thread Support Provides classes and interfaces that enable multi threaded programming.
COM Marshaler Provides marshaling to and from COM
.Net Framework Class Library Support Integrates code with the runtime that supports the .NET framework class library.

WCF Vs Web API

WCF Web API
Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them. HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.
Enables building services that support multiple encodings (Text, MTOM, and Binary) of the same message type and allows switching between them. Enables building Web APIs that support wide variety of media types including XML, JSON etc.
Supports building services with WS-* standards like Reliable Messaging, Transactions, Message Security. Uses basic protocol and formats such as HTTP, WebSockets, SSL, JQuery, JSON, and XML. There is no support for higher level protocols such as Reliable Messaging or Transactions.
Supports Request-Reply, One Way, and Duplex message exchange patterns. HTTP is request/response but additional patterns can be supported through SignalRand WebSockets integration.
WCF SOAP services can be described in WSDL allowing automated tools to generate client proxies even for services with complex schemas. There is a variety of ways to describe a Web API ranging from auto-generated HTML help page describing snippets to structured metadata for OData integrated APIs.
Ships with the .NET framework. Ships with .NET framework but is open-source and is also available out-of-band as independent download.

Microsoft .NET Framework

.Net Framework

  • It is environment for developing, building, deploying and executing desktop applications, web applications and web services.
  • Major components of .NET Framework
    • The common language run time (CLR), which is the execution engine that handles running apps.
    • The .NET Framework Class Library, which provides a library of tested, reusable code that developers can call from their own apps.
    • Class libraries provides reusable code for most common tasks, including data access, XML Web service development and web and Windows form

Common Language Run-time CLR

The Common language run-time simplifies application development provides a robust and secure execution environment, support multiple language and simplifies application deployment and management.

  • The .NET Framework provides a run-time environment called the common language runtime.
  • The runtime handles runtimeservices, including language integration, security and memory management.

Related Post: https://azure-blaze.blogspot.com/2017/08/common-language-runtime.html

Common Type System

  • Support cross-language integration
  • Establishes a framework that helps enable cross-language integration, type safety, and high-performance code execution.

  • Provides an object-oriented model that supports the complete implementation of many programming languages.

  • Defines rules that languages must follow, which helps ensure that objects written in different languages can interact with each other.

  • Provides a library that contains the primitive data types (such as Boolean, Byte, Char, Int32, and UInt64) used in application development.

What Problem does .NET solve?

  • Even with the internet , most applications and devices have trouble communicating with each other.
  • Developers spend the majority of their time rewriting applications to work on each type of platform and client, rather than spending their time designing new applications.

Sunday, 6 August 2017

Error CS0121 The call is ambiguous between the following methods or properties

Compiler Error CS0121 The call is ambiguous between the following methods or properties: 'TestMethod' and 'TestMethod'

The compiler was not able to call one form of an overloaded method. In other word Compiler can not decide which overload method should use.

C# Code

public class Parent
{
    public double Add(int i, double d)
    {
        return (double)i + d;
    }

    public double Add(double d, int i)
    {
        return d + (double)i;
    }
}

Call above function from Main function

static void Main(string[] args)
{
    Parent p1 = new Parent();
    double result1 = p1.Add(1, 2.2); // result1 = 3.2
    double result2 = p1.Add(1.1, 2); // result1 = 3.1
    double result3 = p1.Add(1, 2);   // Get Compiler Error CS0121
    Console.ReadKey();
}

Why function overloading is not based on return type?

Compiler Error CS0121 The call is ambiguous between the following methods or properties: 'TestMethod' and 'TestMethod'

The compiler was not able to call one form of an overloaded method. In other word Compiler can not decide which overload method should use.

C# Code

public class Parent
{
    public void TestMethod()
    {
        Console.WriteLine("Message from Parent.TestMethod().");
    }

    public string TestMethod()
    {
        Console.WriteLine("Message from Parent.TestMethod() return type string.");
        return string.Empty;
    }
}

Observation

Here, will get 2 error for above C# sample code

Solution

You can resolve above error in the following ways:

  • Specify the method parameters in such a way that implicit conversion does not take place.
  • Remove all overloads for the method.
  • Cast to proper type before calling method.

How to convert char to int?

C# Code

Char.GetNumericValue Method Converts a specified numeric Unicode character to a double-precision floating-point number.

int result = (int)Char.GetNumericValue('1');
// Output
// result = 1

FYI,

Note: Below statement treats the argument as char and returns its ascii value. It is returning the ASCII value of character 1.

int result1 = Convert.ToInt32('1');
// Output
// result = 49

Note: Below statement treats the argument as string and converts the value into Int.

int result1 = Convert.ToInt32("1");
// Output
// result = 1

Saturday, 5 August 2017

Single swap can sort the array?

Program to check if a single swap can sort the array

Solution :
  1. Find the first left incorrect position;
  2. Find first right side incorrect position;
  3. Swap elements;
  4. Check if array is sorted , if not, return false;
public static bool SingleSwapSortArray(int[] input)
{
    int leftIndex = FindLeftIndex(input);
    int rightIndex = FindRightIndex(input);
    if (leftIndex == rightIndex || leftIndex == -1 || rightIndex == -1)
    {
        return false; // check these edge cases just to be on safe side.
    }                
    Swap(input, leftIndex, rightIndex);
    return IsSorted(input);
}

Time Complexity : O(N)

Step 1. Find the first left incorrect position;

public static int FindLeftIndex(int[] input)
{
    for (int index = 0; index < (input.Length - 1); index++)
    {
        if (input[index] > input[index + 1])
        {
            while (index > 0 && input[index] == input[index - 1])
            {
                index--;
            }
            return index;
        }
    }
    return -1;
}

Step 2. Find the first right incorrect position;

public static int FindRightIndex(int[] input)
{
    for (int index = input.Length - 1; index >= 1; index--)
    {
        if (input[index - 1] > input[index])
        {
            while (index < input.Length - 1 && input[index] == input[index + 1])
            {
                index++;
            }
            return index;
        }
    }
    return -1;
}

Step 3. Swap elements;

public static void Swap(int[] input, int leftIndex, int rightIndex)
{
    int temp = input[leftIndex];
    input[leftIndex] = input[rightIndex];
    input[rightIndex] = temp;
}

Step 4. Check if array is sorted , if not, return false;

public static bool IsSorted(int[] input)
{
    for (int index = 0; index < input.Length - 1; index++)
    {
        if (input[index] > input[index + 1])
        {
            return false;
        }
    }
    return true;
}

Complete Program

using System;

namespace SingleSwapCanSortArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] input = { 1, 3, 2, 1 };
            Console.WriteLine("Input Array: ");
            foreach (int num in input)
            {
                Console.Write("{0} ", num);
            }
            bool result = SingleSwapSortArray(input);
            Console.WriteLine("\nCan we sort array using single swap: {0}", result);
            if (result)
            {
                Console.WriteLine("Output Array: ");
                foreach (int num in input)
                {
                    Console.Write("{0} ", num);
                }
            }
            Console.Read();
        }
        public static bool SingleSwapSortArray(int[] input)
        {
            int leftIndex = FindLeftIndex(input);
            int rightIndex = FindRightIndex(input);
            if (leftIndex == rightIndex || leftIndex == -1 || rightIndex == -1)
            {
                return false; // check these edge cases just to be on safe side.
            }
            Swap(input, leftIndex, rightIndex);
            return IsSorted(input);
        }

        public static int FindLeftIndex(int[] input)
        {
            for (int index = 0; index < (input.Length - 1); index++)
            {
                if (input[index] > input[index + 1])
                {
                    while (index > 0 && input[index] == input[index - 1])
                    {
                        index--;
                    }
                    return index;
                }
            }
            return -1;
        }

        public static int FindRightIndex(int[] input)
        {
            for (int index = input.Length - 1; index >= 1; index--)
            {
                if (input[index - 1] > input[index])
                {
                    while (index < input.Length - 1 && input[index] == input[index + 1])
                    {
                        index++;
                    }
                    return index;
                }
            }
            return -1;
        }

        public static void Swap(int[] input, int leftIndex, int rightIndex)
        {
            int temp = input[leftIndex];
            input[leftIndex] = input[rightIndex];
            input[rightIndex] = temp;
        }

        public static bool IsSorted(int[] input)
        {
            for (int index = 0; index < input.Length - 1; index++)
            {
                if (input[index] > input[index + 1])
                {
                    return false;
                }
            }
            return true;
        }
    }
}

//Output
//Input Array:
//1 3 2 1
//Can we sort array using single swap: True
//Output Array:
//1 1 2 3

In this example

  1. you will find 3
  2. you will find 1
  3. swap 3,1- > {1 1 2 3}
  4. check if the array is sorted, it's sorted so return true.

Reference

Your Turn

Now it is your turn. Take this sample and implement your own C# program. Leave a comment below telling what you accomplished.

Best wishes on your adventure learning C#!

Thursday, 3 August 2017

Cloud Design Patterns: Command and Query Responsibility Segregation (CQRS)

  • Segregate operations that read data from operations that update data by using separate interfaces.
  • This pattern can maximize performance, scalability, and security; support evolution of the system over time through higher flexibility; and prevent update commands from causing merge conflicts at the domain level.

When to use

  • Collaborative domains where multiple operations are performed in parallel on the same data. CQRS allows you to define commands with enough granularity to minimize merge conflicts at the domain level (any conflicts that do arise can be merged by the command), even when updating what appears to be the same type of data.
  • Task-based user interfaces where users are guided through a complex process as a series of steps or with complex domain models. Also, useful for teams already familiar with domain-driven design (DDD) techniques. The write model has a full command-processing stack with business logic, input validation, and business validation to ensure that everything is always consistent for each of the aggregates (each cluster of associated objects treated as a unit for data changes) in the write model. The read model has no business logic or validation stack and just returns a DTO for use in a view model. The read model is eventually consistent with the write model.
  • Scenarios where performance of data reads must be fine tuned separately from performance of data writes, especially when the read/write ratio is very high, and when horizontal scaling is required. For example, in many systems the number of read operations is many times greater that the number of write operations. To accommodate this, consider scaling out the read model, but running the write model on only one or a few instances. A small number of write model instances also helps to minimize the occurrence of merge conflicts.
  • Scenarios where one team of developers can focus on the complex domain model that is part of the write model, and another team can focus on the read model and the user interfaces.
  • Scenarios where the system is expected to evolve over time and might contain multiple versions of the model, or where business rules change regularly.
  • Integration with other systems, especially in combination with event sourcing, where the temporal failure of one subsystem shouldn't affect the availability of the others.

Tuesday, 1 August 2017

Cloud Design Patterns: Compensating Transaction

  • Undo the work performed by a series of steps, which together define an eventually consistent operation, if one or more of the operations fails.
  • Operations that follow the eventual consistency model are commonly found in cloud-hosted applications that implement complex business processes and workflows.

When to use

  • Use this pattern only for operations that must be undone if they fail. If possible, design solutions to avoid the complexity of requiring compensating transactions.

Elasticsearch - Nodes, clusters, and shards

Elastic Stack Video - Load your gun in short time.   Beginner's Crash Course to Ela...

Recent Post