Tuesday, December 18, 2018

How To Implement NLog With WebAPI In Asp.Net(C#).

What is NLog?

NLog is a flexible and free logging platform for various .NET platforms, including .NET standard. NLog is easy to apply and it includes several targets (database, file, event viewer).

Which platform support it?
.NET Framework 3.5, 4, 4.5, 4.6 & 4.7
.NET Framework 4 client profile
Xamarin Android
Xamarin iOS
Windows Phone 8
Silver light 4 and 5
Mono 4

ASP.NET 4 (NLog.Web package)
ASP.NET Core (NLog.Web.AspNetCore package)
.NET Core (NLog.Extensions.Logging package)
.NET Standard 1.x - NLog 4.5
.NET Standard 2.x - NLog 4.5
UWP - NLog 4.5
There are several log levels.
Fatal : Something terrible occurred; the application is going down
Error : Something fizzled; the application might possibly proceed
Warn : Something surprising; the application will proceed
Info : Normal conduct like mail sent, client refreshed profile and so on.
Debug : For troubleshooting; the executed question, the client confirmed, session terminated
Trace : For follow troubleshooting; start technique X, end strategy X
Where we can log?
Console
Database
Email
Event Viewer Log
Files
Network
Implementation of NLog

Step 1 : Open Visual Studio. Select File > New > Project.



Step 2 : Select Web> ASP.NET Web Application > Give your project name "NLogTestApp", and then click OK.



Step 3 : Select Web API and click OK.




Step 4 : Now, we add NLog in our project. Right-click on your project solution, click on "Manage NugGet Packages". Click on the "Browse" link button and in the search box, type nlog. It will show you NLogDll as shown below. Just install this dll.

After that, when you click "Install", you will get the following window, i.e., Preview Changes.




In this popup window, click the OK button. After it is successfully installed, you will get the Nlog dll in your project reference.

Step 5 : Now, add the following code to your config file.

<configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
        <target name="logfile" xsi:type="File" fileName="${basedir}/MyLogs/${date:format=yyyy-MM-dd}-api.log" />
        <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" My Custom Api Services" />
        <target name="database" type="Database" connectionString="Data Source=SRKSUR5085LT\SQLEXPRESS;initial catalog=NLog;user id=sa;password=OPTICAL;MultipleActiveResultSets=True;">
            <commandText> insert into ExceptionLog ([TimeStamp],[Level],Logger, [Message], UserId, Exception, StackTrace) values (@TimeStamp, @Level, @Logger, @Message, case when len(@UserID) = 0 then null else @UserId end, @Exception, @StackTrace); </commandText>
            <parameter name="@TimeStamp" layout="${date}" />
            <parameter name="@Level" layout="${level}" />
            <parameter name="@Logger" layout="${logger}" />
            <parameter name="@Message" layout="${message}" />
            <parameter name="@UserId" layout="${mdc:user_id}" />
            <parameter name="@Exception" layout="${exception}" />
            <parameter name="@StackTrace" layout="${stacktrace}" />
            <dbProvider>System.Data.SqlClient</dbProvider>
        </target>
    </targets>
    <rules>
        <!-- I am adding my 3 logging rules here -->
        <logger name="*" minlevel="Debug" writeTo="database" />
        <logger name="*" minlevel="Trace" writeTo="logfile" />
        <logger name="*" minlevel="Trace" writeTo="eventlog" />
    </rules>
</nlog>

We will targeting to log into three places.
database
txt file
Event Viewer
Your config look like below.





Step 6 : We need to create our DB Script as shown below

CREATE TABLE [dbo].[exceptionlog] 
  ( 
     [id]         [INT] IDENTITY(1, 1) NOT NULL, 
     [timestamp]  [DATETIME] NOT NULL, 
     [level]      [VARCHAR](100) NOT NULL, 
     [logger]     [VARCHAR](1000) NOT NULL, 
     [message]    [VARCHAR](3600) NOT NULL, 
     [userid]     [INT] NULL, 
     [exception]  [VARCHAR](3600) NULL, 
     [stacktrace] [VARCHAR](3600) NULL, 
     CONSTRAINT [PK_ExceptionLog] PRIMARY KEY CLUSTERED ( [id] ASC )WITH ( 
     pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF, 
     allow_row_locks = on, allow_page_locks = on) ON [PRIMARY] 
  ) 
ON [PRIMARY] 

Step 7 : Now, go to your home controller and add following code in index method.

using NLog;
using System;
using System.Web.Mvc;


namespace NLogTestApp.Controllers

    public class HomeController : Controller
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";
            logger.Info("Hello we have visited the Index view" + Environment.NewLine + DateTime.Now);         
            return View();
        }
    }
}

Now, run the application.


data-ad-format="auto" And open your SQL. You will see the following logs inserted in your database.




You can see this in your Event Viewer.


You can see the following in your text file.






When you are working with WEPAPI that time NLog is very useful and easy to apply.

Tuesday, February 13, 2018

How to convert records in a table to XML format using T-SQL

DECLARE @stSqlString NVARCHAR(MAX) = '' DECLARE @stStrXml XML SET @stSqlString = 'set @stStrXml=(select * from TableName FOR XML AUTO, elements)' EXEC sp_executesql @stSqlString, N'@stStrXml XML OUTPUT',@stStrXml OUTPUT SELECT @stStrXml

How to get list of all Folder in network sharing path using SQL Server

IF OBJECT_ID('tempdb..#TempTableName') IS NOT NULL DROP TABLE #TempTableName ; CREATE TABLE #TempTableName ( id INT IDENTITY(1, 1) , subdirectory NVARCHAR(512) , depth INT ) ; INSERT #TempTableName ( subdirectory ) EXEC MASTER.dbo.xp_cmdshell 'dir DriveName:\ /b /o:n /ad' IF NOT EXISTS ( SELECT 1 FROM #TempTableName ) BEGIN EXEC XP_CMDSHELL 'net use DriveName: \\ServerName\DriveName /user:domain\USERNAME PASSWORD'---code for Mapping drive in local Pc END

Create Window Service Setup Using .bat file

-----------------------------For Install------------------------------------------------- @ECHO OFF echo Installing WindowsService... echo --------------------------------------------------- C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i C:\RapnetService\Debug\ImportRapnetData.exe echo --------------------------------------------------- echo Service Install Done Successfully. pause ---------------------------------For Uninstall--------------------------------------------- @ECHO OFF echo Installing WindowsService... echo --------------------------------------------------- C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil /u C:\RapnetService\Debug\ImportRapnetData.exe echo --------------------------------------------------- echo Service UnInstall Done Successfully. pause

WCF Service Web.Config File Setting

Monday, February 12, 2018

Query For Calculate CPU Usage in SQL Server

SELECT TOP 10 ObjectName = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid) ,TextData = qt.text ,DiskReads = qs.total_physical_reads -- The worst reads, disk reads ,MemoryReads = qs.total_logical_reads --Logical Reads are memory reads ,Executions = qs.execution_count ,TotalCPUTime = qs.total_worker_time ,AverageCPUTime = qs.total_worker_time/qs.execution_count ,DiskWaitAndCPUTime = qs.total_elapsed_time ,MemoryWrites = qs.max_logical_writes ,DateCached = qs.creation_time ,DatabaseName = DB_Name(qt.dbid) ,LastExecutionTime = qs.last_execution_time FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt ORDER BY qs.total_worker_time DESC -- Find queries that have the highest average CPU usage SELECT TOP 10 ObjectName = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' + OBJECT_NAME(qt.objectid, qt.dbid) ,TextData = qt.text ,DiskReads = qs.total_physical_reads -- The worst reads, disk reads ,MemoryReads = qs.total_logical_reads --Logical Reads are memory reads ,Executions = qs.execution_count ,TotalCPUTime = qs.total_worker_time ,AverageCPUTime = qs.total_worker_time/qs.execution_count ,DiskWaitAndCPUTime = qs.total_elapsed_time ,MemoryWrites = qs.max_logical_writes ,DateCached = qs.creation_time ,DatabaseName = DB_Name(qt.dbid) ,LastExecutionTime = qs.last_execution_time FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt ORDER BY qs.total_worker_time/qs.execution_count DESC

Angular Project Demo

1) create Two Folder :- Controllers and Factory (WebApplication2 is project name) -----------------------------------------MytestConroller.js--------------------------------------------------------- angular.module('WebApplication2.Controllers').controller('MytestController', MytestController); MytestController.$inject = ['$scope', 'MyButtonClickEvent', '$http']; function MytestController($scope, MyButtonClickEvent, $http) { var vm = this; $scope.username = 'World'; $scope.sayHello = function () { //First Code //$scope.greeting = MyButtonClickEvent.BtnClick($scope.username); //MyButtonClickEvent.GetData($scope.username).then(function (result) { // $scope.greeting = result.data.aaData; //}) ///Second Code var item = { 'msgName': $scope.username } MyButtonClickEvent.GetDataClass(item).then(function (result) { debugger $scope.greeting = result.data.aaData.msgName; }) // third code //var item = []; //item.push({ msgName: $scope.username }); //MyButtonClickEvent.GetDataList(item).then(function (result) { // $scope.greeting = result.data.aaData[0].msgName; //}) }; } -----------------------------------------MytestFactory.js--------------------------------------------------------- angular.module('WebApplication2.Services').service('MyButtonClickEvent', MyButtonClickEvent); MyButtonClickEvent.$inject = ['$http']; function MyButtonClickEvent($http) { var list = {}; list.BtnClick = function (data) { return 'Hello ' + data; } list.GetData = function (data) { return $http({ url: '/Mytest/GetMsg', method: "GET", params: { MyData: data }, }); }; list.GetDataClass = function (data) { return $http({ url: '/Mytest/GetMsgClass', method: "GET", params: data }); }; list.GetDataList = function (myObject) { return $http({ url: '/Mytest/GetMsgList', method: "post", data: myObject }); }; return list; } -----------------------------------App.js-------------------------------------------------------------------- angular.module('WebApplication2', ['WebApplication2.Controllers', 'WebApplication2.Services']); angular.module('WebApplication2.Controllers', []); angular.module('WebApplication2.Services', []); -----------------------------------Index.cshtml----------------------------------------------------------
Your name:

{{greeting}}
-------------------------------------Controller.cs-------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApplication2.Controllers { public class MytestController : Controller { // GET: Mytest public ActionResult Index() { return View(); } [HttpGet] public JsonResult GetMsg(string MyData) { var JsonResult = Json(new { aaData = MyData }, JsonRequestBehavior.AllowGet); JsonResult.MaxJsonLength = Int32.MaxValue; return JsonResult; } [HttpGet] public JsonResult GetMsgClass(myList MyData) { var JsonResult = Json(new { aaData = MyData }, JsonRequestBehavior.AllowGet); JsonResult.MaxJsonLength = Int32.MaxValue; return JsonResult; } [HttpPost] public JsonResult GetMsgList(List MyData) { var JsonResult = Json(new { aaData = MyData }, JsonRequestBehavior.AllowGet); JsonResult.MaxJsonLength = Int32.MaxValue; return JsonResult; } } } public class myList { public string msgName { get; set; } } ----------------------------------Layout.cshtml-------------------------

File Upload in Angular 2

****************Change Event ************* onChange(event: EventTarget) { let formData = new FormData(); let eventObj: MSInputMethodContext = event; let target: HTMLInputElement = eventObj.target; let files: FileList = target.files; this.file = files[0]; let formData = new FormData(); formData.append('FileDocument', this.file); return this.http.post(`UrlPath`, formData) .map((res: Response) => { }); } ******************WEB API****************** [HttpPost] public void GetImage() { var ImageData= System.Web.HttpContext.Current.Request.Files["FileDocument"]; ImageData.SaveAs(Path); }

Input Only Number in Iput Type in Angular 2

Input Only Number in Input Type in Angular 2 -- Html Code here First Create Directive.ts File and Put Code Inside *************************onlynumber.directive.ts*************************** import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[OnlyNumber]' }) export class OnlyNumber { constructor(private el: ElementRef) { } @Input() OnlyNumber: boolean; @HostListener('keydown', ['$event']) onKeyDown(event) { let e = event; if (e.which == 13) { e.preventDefault(); var $next = $('[tabIndex=' + (+ parseInt(e.target['tabIndex']) + 1) + ']'); if (!$next.length) { $next = $('[tabIndex=1]'); } $next.focus(); } else if (this.OnlyNumber) { if ([46, 8, 9, 27, 13, 190].indexOf(e.keyCode) !== -1 || (e.keyCode == 65 && e.ctrlKey === true) || (e.keyCode == 67 && e.ctrlKey === true) || (e.keyCode == 88 && e.ctrlKey === true) || (e.keyCode >= 35 && e.keyCode <= 39)) { return; } if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); } } } }

Passing Data To Component in Agular2 With Using Service

-------------Create First Service--------------- import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class ProgressSpinner { public _subject = new Subject(); public event = this._subject.asObservable(); public SpinnerLoader(data: any) { this._subject.next(data); } } ------------Create Object in AppComponent-------------- import { Component } from '@angular/core'; import { alertservice, ProgressSpinner } from './shared' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; loading: boolean = false; constructor(public _ProgressSpinner: ProgressSpinner) { _ProgressSpinner.event.subscribe((data) => { this.loading = data }); } } ***************Second Component*************** import { Component, OnInit, ViewEncapsulation, ElementRef } from '@angular/core' import { MenuItem, Message, Shape_Master, Shape_Col } from '../../shared' import { DepartmentGroupervice, GenericClass, Pagination, ProgressSpinner } from '../../shared' import { ConfirmationService, GrowlModule } from 'primeng/primeng'; @Component({ selector: 'app-shape', templateUrl: './shape.component.html', styleUrls: ['./shape.component.css'] }) export class ShapeComponent implements OnInit { constructor( private _ProgressSpinner: ProgressSpinner) { this._ProgressSpinner.SpinnerLoader(false); } }

Sunday, January 21, 2018

Not Empty Table List In Sql Server


WITH TableName AS
(
   SELECT
      SUM(row_count) AS [row_count],
      OBJECT_NAME(OBJECT_ID) AS TableName
   FROM
      sys.dm_db_partition_stats
   WHERE
      index_id = 0 OR index_id = 1
   GROUP BY
      OBJECT_ID
)

SELECT *
FROM TableName
WHERE [row_count] > 0

Wednesday, January 10, 2018

Get Hour And minute, Second From Second in Sql Server

DECLARE @Second1 BIGINT=5401
SET @Second1=ABS(@Second1)
DECLARE @ETIME AS VARCHAR(20)
SELECT @ETIME = RIGHT(CAST(@Second1 / 3600 AS VARCHAR(10)),7) + '.' +
RIGHT('0' + CAST((@Second1 / 60) % 60 AS VARCHAR(10)),2) + ':' + RIGHT('0' + CAST(@Second1 % 60 AS VARCHAR(2)),2)
SELECT @ETIME

Convert Minute To Hour in SQL Server function

CREATE FUNCTION [dbo].[MinToHour]
(
@Second1 BIGINT=0
)
RETURNS TIME
AS
BEGIN
DECLARE @Res TIME =NULL

SET @Second1=ABS(@Second1)
DECLARE @ETIME AS VARCHAR(20)
SELECT @ETIME = RIGHT(CAST(@Second1 / 60 AS VARCHAR(10)),7) + '.' + RIGHT('0' + CAST((@Second1) % 60 AS VARCHAR(10)),2)
SELECT @RES= CAST(REPLACE(@ETIME,'.',':') AS TIME)
RETURN @RES
END

Convert Second to Hour in Sql Server function

CREATE FUNCTION [dbo].[SecTOHour]
(
@Second1 BIGINT=0
)
RETURNS TIME
AS
BEGIN
DECLARE @Res TIME =NULL

SET @Second1=ABS(@Second1)
DECLARE @ETIME AS VARCHAR(20)
SELECT @ETIME = RIGHT(CAST(@Second1 / 3600 AS VARCHAR(10)),7) + '.' +
RIGHT('0' + CAST((@Second1 / 60) % 60 AS VARCHAR(10)),2) + ':' + RIGHT('0' + CAST(@Second1 % 60 AS VARCHAR(2)),2)
SELECT @RES= CAST(REPLACE(@ETIME,'.',':') AS TIME)
RETURN @RES
END

Tuesday, January 9, 2018

Rotate image in asp.net

public void FlipImage(string Filename, string FileNameNew)
 {
      System.Drawing.Image img = System.Drawing.Image.FromFile(System.Web.Hosting.HostingEnvironment.MapPath("/images/") + Filename);
      //Rotate the image in memory
      img.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
      System.IO.File.Delete(System.Web.Hosting.HostingEnvironment.MapPath("/images/" + FileNameNew));
      //save the image out to the file
      img.Save(System.Web.Hosting.HostingEnvironment.MapPath("/images/" + FileNameNew));
      //release image file
      img.Dispose();
 }