Tuesday, 6 December 2016

Steps to setup TypeScript in Visual Studio

How to setup the Environment for TypeScript.

Prerequisite:
Npm.

Editors:
·        Visual Studio 2013 or New Version.
Visual Studio Code extension (https://code.visualstudio.com/blogs) etc.

Steps:

·        Create a Project folder.
e.g. D:\Shrikant\typescript demo

·        Go to Project folder in Command Prompt or Node.js Prompt.
C:\Windows\System32>D:
C:\Windows\System32>cd D:\Shrikant\typescript demo

·        Create Project Meta data file Or Root file (Package.json) using below command
npm init. This will ask for project details such name, version and author etc.
 Fill the details or press enter.

e.g. D:\Shrikant\typescript demo>npm init
Result: This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.Press ^C at any time to quit.
name: (typescript demo) ShrikamtM
Sorry, name can no longer contain capital letters.
name: (typescript demo) shrikantm
version: (1.0.0)
Invalid version: "      "
version: (1.0.0) 1
Invalid version: "1"
version: (1.0.0) 1
Invalid version: "1"
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\Shrikant\typescript demo\package.json:
{
  "name": "shrikantm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "typescript": "^2.0.10"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Is this ok? (yes)
·        Enter “y” to confirm creation of Package.json file.

·        Add typescript reference to project using below command.
D:\Shrikant\typescript demo>npm install --save-dev typescript

·        Go to .bin folder.
D:\Shrikant\typescript demo>Cd node_modules\.bin

·        Create typescript config file (tsconfig.json) using below code.
D:\Shrikant\typescript demo\node_modules\.bin>tsc –init
Result: message TS6071: Successfully created a tsconfig.json file.

·        Move tsconfig.json manually to root folder where package.json file is present.

·        Start typescript Compiler Watcher for automatic conversion of typescript files to Javascript using below command.
D:\Shrikant\typescript demo\node_modules\.bin>tsc –w
Note: - It will convert all typescript files present in same folder or subfolder where tsconfig.json is present.

Or
·        If you want to manually compile the typescript file then use below command.
D:\Shrikant\typescript demo\node_modules\.bin>tsc ..\..\fileName.ts

·        Now we are ready to create typescript files.

Thursday, 10 November 2016

How to list all foreign keys in MS SQL database

How to list all foreign keys in MS SQL database


SELECT RC.CONSTRAINT_NAME FK_Name
, KF.TABLE_SCHEMA FK_Schema
, KF.TABLE_NAME FK_Table
, KF.COLUMN_NAME FK_Column
, RC.UNIQUE_CONSTRAINT_NAME PK_Name
, KP.TABLE_SCHEMA PK_Schema
, KP.TABLE_NAME PK_Table
, KP.COLUMN_NAME PK_Column
, RC.MATCH_OPTION MatchOption
, RC.UPDATE_RULE UpdateRule
, RC.DELETE_RULE DeleteRule
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KF ON RC.CONSTRAINT_NAME = KF.CONSTRAINT_NAME

JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KP ON RC.UNIQUE_CONSTRAINT_NAME = KP.CONSTRAINT_NAME

Friday, 4 November 2016

Thursday, 27 October 2016

How to close all active connections to MS SQL database


Query to close all active connections to MS SQL database:

use master
go
alter database PrimumII_LoadTest
set single_user with rollback immediate
go
alter database PrimumII_LoadTest
set multi_user
go

How to lock a table in MSSQL

Query lock a table in MSSQL:

BEGIN TRAN
SELECT 1 FROM <Table Name> WITH (TABLOCKX)
WAITFOR DELAY '00:11:00'
ROLLBACK TRAN  
GO 

Tuesday, 10 May 2016

Code to copy paste using javascript on clipboard

Working on Chrome, IE, Mozilla

 Script:

function copySelectionText(text) {
    //debugger;
    var copysuccess;
    try {
        if (window.clipboardData && clipboardData.setData) {
            clipboardData.setData('text', text);//For IE
        }
        else {//For others
            copysuccess = document.execCommand("copy");
        }
    } catch (e) {
        copysuccess = false;
    }
    return copysuccess;
}

function copyfieldvalue(e, field) {
    SelectText(field);
    var copysuccess = copySelectionText(field.innerText);
}

function SelectText(element) {
    var doc = document
        , text = element
        , range, selection
    ;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

Html Changes:

 <button data-bb-handler="ok" type="button" id="btnOtpCopy" data-dismiss="modal" onclick="copyfieldvalue(event,document.getElementById('otpValue'));" class="btn btn-primary">Copy</button>

Thursday, 19 November 2015

How to remove empty spaces from string using dotnet regex?





Use below method to remove empty spaces:


public static string RemoveEmptySpace(string inputString)
        {
            string ouputString = string.Empty;
            if (!string.IsNullOrEmpty(inputString))
            {
                ouputString = Regex.Replace(inputString, "\\s+", " ");
                ouputString = Regex.Replace(ouputString, "^\\s+|\\s+$", "");
            }
            return ouputString;

        }

How to ignore certificate validation when sending an email using SmtpClient in Dotnet


Issue:
If there is some Issue with Server certificate below error will occur,
The remote certificate is invalid according to the validation procedure


Solution:
1)      Use valid server certificates.
2)      Right code to ignore invalid certificate (refer below code lines).


Code lines:
1.      ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
2.      smtpClient.Send(mailMessage);

Add Callback handler (ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate) before sending email (before smtpClient.Send() method)


ValidateServerCertificate() definition:

private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;
            }
            //The server certificate is not valid. Continuing with sending email.;
            return true;
        }


Thursday, 9 July 2015

Changes required to be done for implementing Dependency injection in WebAPI or MVC project

Below are the changes required to be done for implementing Dependency injection in WebAPI or MVC project.

References required:

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Mvc;
using IOCLibrary;



global.asax changes:
This change is required only for Web project.

public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            #region "General settings"
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }


WebApiConfig.cs changes:

In below example, we are implementing Dependency injection on classes which are used for handling requests
(For e.g. Inspector.cs , HttpsRquestValidator.cs).
If there are no such classes in your project then these change is not required.
This change is required only for WebAPI or MVC project.


namespace WebAPITest
{

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var container = UnityConfig.GetConfiguredContainer();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

//To validate request data
            var Inspector = container.Resolve<Inspector>();
            Inspector.InnerHandler = new HttpControllerDispatcher(config);
           
//Global request handler -applicable to all the requests
            var validator = container.Resolve<HttpsRquestValidator>();

            config.DependencyResolver = new IocContainer(container);

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional }, null, Inspector);

            config.MessageHandlers.Add(validator);
        }
    }
}


//App_Start/UnityWebActivator.cs changes
This change is required only for WebAPI or MVC project.

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(UnityWebActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(UnityWebActivator), "Shutdown")]

namespace WebAPITest
{
    /// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
    public static class UnityWebActivator
    {
        /// <summary>Integrates Unity when the application starts.</summary>
        public static void Start()
        {
            var container = UnityConfig.GetConfiguredContainer();

            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
           
        }

        public static void Shutdown()
        {
            var container = UnityConfig.GetConfiguredContainer();
            container.Dispose();
        }
    }
}


// UnityConfig.cs changes
This file is used for maintaining list of all classes used in project with their mapped interface.


public class UnityConfig
    {
        #region Unity Container
        private static readonly Lazy<IUnityContainer> Container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });
        public static IUnityContainer GetConfiguredContainer()
        {
            return Container.Value;
        }
        #endregion
       
        public static void RegisterTypes(IUnityContainer container)
        {
            //load classess
            container.RegisterType<HomeController>();
            container.RegisterType<IFileSystem, FileSystem>();
        }
    }


Create IOCLibrary using below classes:
If there are more than project then this library will be useful or you could use below classes in project itself.

public class ScopeContainer : IDependencyScope
    {
        protected IUnityContainer Container;

        public ScopeContainer(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }
            Container = container;
        }

        public object GetService(Type serviceType)
        {
            if (Container.IsRegistered(serviceType))
            {
                return Container.Resolve(serviceType);
            }
            return null;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (Container.IsRegistered(serviceType))
            {
                return Container.ResolveAll(serviceType);
            }
            return new List<object>();
        }

        public void Dispose()
        {
            Container.Dispose();
        }
    }

    public class IocContainer : ScopeContainer, IDependencyResolver
    {
        public IocContainer(IUnityContainer container)
            : base(container)
        {
        }

        public IDependencyScope BeginScope()
        {
            var child = Container.CreateChildContainer();
            return new ScopeContainer(child);
        }

    }