Category Archives: C#

ASP.NET Core logging with NLog and Elasticsearch

Software Engineering

This article shows how to Log to Elasticsearch using NLog in an ASP.NET Core application. NLog is a free open-source logging for .NET.

Code:VS2017 RC3 csproj | VS2015 project.json

2017.02.08 Updated to NLog.Web.AspNetCore 4.3.0 and VS2017 RC3
17.12.2016 Updated to ASP.NET Core 1.1

NLog posts in this series:

  1. ASP.NET Core logging with NLog and Microsoft SQL Server
  2. ASP.NET Core logging with NLog and Elasticsearch
  3. Settings the NLog database connection string in the ASP.NET Core appsettings.json
  4. .NET Core logging to MySQL using NLog
  5. .NET Core logging with NLog and PostgreSQL

NLog.Extensions.Logging is required to use NLog in an ASP.NET Core application. This is added to the dependencies of the project. NLog.Targets.ElasticSearch is also added to the dependencies. This project is at present NOT the NuGet package from ReactiveMarkets, but the source code from ReactiveMarkets and updated to dotnetcore. Thanks to ReactiveMarkets for this library, hopefully the NuGet package will…

View original post 181 more words

Sisense SSO implementation in MVC .net core

We can find a documentation regarding what needs to be done in Sisense BI Elastic cube manager in relation to SSO using JWT.  They also have C# code to use for SSO but one may be scratching his head if he/she wants to use that sample code in MVC .net Core application.

So for that purpose I’ld suggest to make one controller with one action in it, Use that URL of that controller action to configure in Sisense SSO configuration page. The sample code would be

 

public IActionResult Index([FromQuery]string return_to)
{
TimeSpan t = (DateTime.UtcNow – new DateTime(1970, 1, 1));
int timestamp = (int)t.TotalSeconds;
var payload = new System.Collections.Generic.Dictionary<string, object>() {
{ “iat”, timestamp},
{ “sub”, CurrentUser() },
{ “jti”, Guid.NewGuid() }
// Optional properties
// { “exp”, (int)t.Add(TimeSpan.FromMinutes(30)).TotalSeconds } // Expiration time
};
string token = Jwt.JsonWebToken.Encode(payload, “secret key from sisense sso                 configuration”, Jwt.JwtHashAlgorithm.HS256);
string redirectUrl = “http://URL_of_your_sisense_web_app_with_port/jwt?jwt=&#8221; + token;

    if (return_to != null)
{
redirectUrl += “&return_to=” + UrlEncoder.Default.Encode(return_to);
}
return Redirect(redirectUrl);

  }

}

Building Single Page Applications using Web API and angularJS (Free e-book)

chsakell's Blog

Single Page Applications are getting more and more attractive nowadays for two basic reasons. Website users have always preferred a fluid user experience than one with page reloads and the incredible growth of several JavaScript frameworks such as angularJS. This growth in conjunction with all the powerful server side frameworks makes Single Page Application development a piece of cake. This post is the online version of the free e-book and describes step by step how to build a production-level SPA using ASP.NET Web API 2 and angularJS. You have two choices. Either grab a coffee and keep going on with this version or simply download the e-book and enjoy it whenever and wherever you want.
spa-webapi-angular-28
There are a lot of stuff to build in this application so I will break this post in the following sections:

View original post 9,862 more words

An element with id ‘form1’ could not be found. Script error on page load

When you use Jquery and AJAX on the same form and you included the jQuery file with the <script /> this error will be thrown by VS (specially VS 2010).  To solve this issue just replace the <script /> with <script><script/> tag and it will solve your problem.

Note: This error will only come when you use IE, with every other browser this error will not come, but the thing common on all browsers is that design view is corrupted and the events will not fire as expected or not fire at all

How to set Icon for application .exe file

We have to follow the simple steps when changing an application’s exe file icon.

  • Go to Solution Explorer
  • Right Click on the Primary Project
  • Go to Properties
  • Go to Application tab
  • In Resources groupbox select the desired icon
This will set the application icon for you.
But if you create a setup of your project and there’s a shortcut of your primary .exe file on user’s desktop, you will find that the icon of that is not changed. For that you have to do the following steps.
  • Go to setup project in Solution Explorer
  • Open File System Editor
  • Go to your User’s Desktop folder
  • Select the shortcut of the primary .exe file (if you didn’t find any file here, then you have to create a shortcut of primary .exe file and put it here)
  • Go to properties of this shortcut
  • Select the desired icon for your application.
Now compile and install the application you will find the changed icon of your shortcut file too

How To Create an ASP.NET HTTP Handler by Using Visual C# .NET

From: microsoft support

Implement the Handler

  1. Open Microsoft Visual Studio .NET. In Visual C# .NET, create a new Class Library project named MyHandler.
  2. Set a reference to the System.Web.dll assembly.
  3. Add the following directive to the class:
    Using System.Web
  4. Rename the class SyncHandler.cs, and then change the class definition to reflect this.
  5. Implement the IHttpHandler interface. Your class definition should appear as follows:
    Public Class SyncHandler: IHttpHandler
  6. Implement the IsReusable property and the ProcessRequest method of theIHttpHandler interface. Because this is a synchronous handler, return False for theIsReusable property so that the handler is not pooled.
    public bool IsReusable
    {
    get {return true;}
    }

    public void ProcessRequest(HttpContext context)
    {
    context.Response.Write(“Hello from custom handler”);
    }

  7. Compile the Project

Deploy the Handler

  1. Create a new directory named Handler under the C:\Inetpub\Wwwroot directory.
  2. Create a subdirectory named Bin in the newly created Handler directory. The resultant path is C:\Inetpub\Wwwroot\Handler\Bin.
  3. Copy MyHandler.dll from your project’s Bin\Debug directory to the C:\Inetpub\Wwwroot\Handler\Bin directory.
  4. Follow these steps to mark the new Handler directory as a Web application:
    1. Open Internet Services Manager.
    2. Right-click the Handler directory, and then click Properties.
    3. On the Directory tab, click Create.
  5. Follow these steps to create an application mapping for the handler. For this handler, create a mapping to the Aspnet_isapi.dll file for the *.sync extension. Whenever a .sync file is requested, the request is routed to ASP.NET, and ASP.NET executes the code in the handler.
    1. Right-click on the Handler Web application, and then click Properties.
    2. On the Directory tab, click Configuration.
    3. Click Add to add a new mapping.
    4. In the Executable text box, type the following path: Microsoft Windows 2000:
      C:\WINNT\Microsoft.NET\Framework\<version#>\Aspnet_isapi.dll

      Microsoft Windows XP:

      C:\WINDOWS\Microsoft.NET\Framework\<version#>\Aspnet_isapi.dll
    5. In the Extension text box, type .sync.
    6. Make sure that the Check that file exists check box is cleared, and then clickOK to close the
      Add/Edit Application Extension Mapping dialog box.
    7. Click OK to close the Application Configuration and the Handler Propertiesdialog boxes.
  6. Close Internet Services Manager.

Configure the System

  1. In the C:\Inetpub\Wwwroot\Handler directory, create a new file named Web.config.
  2. Add the following code to Web.config: <configuration> <system.web> <httpHandlers> <add verb="*" path="*.sync" type="MyHandler.SyncHandler, MyHandler" /> </httpHandlers> </system.web> </configuration> In the verb="*" attribute, we instruct the handler to process a request that uses any verb (for example, POST, HEAD, GET, and so on). If you want this handler to process only the POST request, change this to verb="POST". In the path="*.sync" attribute, we instruct the handler to process any incoming requests for files with the .sync extension. In the type="MyHandler.SyncHandler, MyHandler" attribute, we instruct the handler that processes the request to implement in the MyHandler.SyncHandlernamespace, and this class resides in the MyHandler assembly. 

 

How to implement a WCF Service Contract

As I described how to create a Service Contract in the previous post now I will move forward and implement the Service Contract. For this I need to define a class which implements the Interface created for the service Contract.

In the previous post I created a console application for defining a service contract and in Program.cs I defined the service contract. So I am using the same file to write a class code which implements the interface.

The Interface created for the service contract in previous post is as follows.

// Define a service contract.
  [ServiceContract()]
  public interface ICalculator
  {
    // Create the method declaration for the contract.
    [OperationContract]
    double Add(double d1, double d2);
    [OperationContract]
    double Subtract(double d1, double d2);
    [OperationContract]
    double Multiply(double d1, double d2);
    [OperationContract]
    double Divide(double d1, double d2);
  }

Now I will create a class with the name of Calculator which will implement the above mentioned interface.

// Create a class that implements the service contract.
public class Calculator : ICalculator
{
     // Implement functionality for the service operations(methods).
     public double Add(double d1, double d2)
        {
            return d1 + d2;
        }

        public double Subtract(double d1, double d2)
        {
            return d1 - d2;
        }

        public double Multiply(double n1, double n2)
        {
            return d1 * d2;
        }

        public double Divide(double n1, double n2)
        {
            return d1 / d2;
        }
}

	

How to Define a WCF Service Contract

The first step required when creating a Windows Communication Foundation (WCF) service is to create a Contract for the it. The contract specifies what operations a service can perform. In normal programming terms operation can be conceived as method, so we can say operation is a method exposed in a web service. You can write code for web service in .Net compliant language like C#,VB.Net and C++.

Normally we need to create a interface to define the service contract and this contract contains the operations (methods) a service can perform.

Each interface must have the ServiceContract attribute associated with it and the each operation (method) with in the interface should have the OperationContract attribute associated with it. If any operation (method) without OperationContract attribute defined with in the interface that has the ServiceContract attribute, than that funciton will not be exposed to the outer world.

For practice we will create a Console application in the VS 2008 that will contain a interface to show you how to create a service contract. VS 2008 should be run as an administrator and after you create the console application you need to add the reference for System.ServiceModel.

When you create a console application than by default the solution has one file with the name of Program.cs and the code written in it would be like this

namespace Service
{
class Program
{
static void Main(string[] args)
{
}
}
}

I have named the project as Service that’s why the namespace name is also Service.

After adding the reference for System.ServiceModel we also need to add one line of code on top of the file and that line will be a using statement as follows

Using System.ServiceModel;

This line will help the coders to use the classes with in this namespace without writing the full hierarchy of classes.

Now we will create a sample contract for a Web Service which will perform basic arithmetic function like Add,Subtract,Multiply and Division. So the code for this contract should be something like this:

using System;

// Add the using statment for System.ServiceModel 
using System.ServiceModel;
namespace Service
{
  // Define a service contract.
  [ServiceContract()]
  public interface ICalculator
  {
    // Create the method declaration for the contract.
    [OperationContract]
    double Add(double d1, double d2);
    [OperationContract]
    double Subtract(double d1, double d2);
    [OperationContract]
    double Multiply(double d1, double d2);
    [OperationContract]
    double Divide(double d1, double d2);
  }
}

There are many parameter options available for both ServiceContract and OperationContract attribute. We can use them according to our need.

Compile the code and if there is no error than we are succeeded in creating our first Service Contract, which will be used in creating WCF Web Service.

How to Export data from DataTable to Excel

You can find many articles on internet that will provide a solution for exporting data from DataGrid to Excel sheet. i searched many articles on websites and from many articles which provide a solution to this problem but from all those articles the article found at this site.

you may need to change it little according tou your requirements.

private void ExportToExcel(DataTable dt)
{
Microsoft.Office.Interop.Excel.Application objApp;
Microsoft.Office.Interop.Excel._Workbook objBook;

Microsoft.Office.Interop.Excel.Workbooks objBooks;
Microsoft.Office.Interop.Excel.Sheets objSheets;
Microsoft.Office.Interop.Excel._Worksheet objSheet;
Microsoft.Office.Interop.Excel.Range range;

try
{
// Instantiate Excel and start a new workbook.
objApp = new Microsoft.Office.Interop.Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Add(Type.Missing);
objSheets = objBook.Worksheets;
objSheet = (Microsoft.Office.Interop.Excel._Worksheet)objSheets.get_Item(1);

//Get the range where the starting cell has the address
//m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
range = objSheet.get_Range(“A1”, Type.Missing);
range = range.get_Resize(dt.Rows.Count +1 , dt.Columns.Count +1);

//Create an array.
string[,] saRet = new string[dt.Rows.Count+1 ,dt.Columns.Count +1];

for (int col = 0; col <= dt.Columns.Count – 1; col++)
{
saRet[0, col] = dt.Columns[col].ColumnName.ToUpper();
}
bool val = false;
//Fill the array.
for (int iRow = 0; iRow < dt.Rows.Count; iRow++)
{
for (int iCol = 0; iCol < dt.Columns.Count; iCol++)
{
//Put the row and column address in the cell.
if (iCol == 0)
{
saRet[iRow+1, 0] = Convert.ToDateTime(dt.Rows[iRow].ItemArray[0].ToString()).ToShortDateString();
continue;
}

saRet[iRow+1, iCol] = dt.Rows[iRow].ItemArray[iCol].ToString();
}
}

//Set the range value to the array.
range.set_Value(Type.Missing, saRet);

//Return control of Excel to the user.
objApp.Visible = true;
objApp.UserControl = true;
objBook.SaveAs(FileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,       Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
}
catch (Exception theException)
{
String errorMessage;
errorMessage = “Error: “;
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, ” Line: “);
errorMessage = String.Concat(errorMessage, theException.Source);

MessageBox.Show(errorMessage, “Error”);
}
}

This code  included to format date

public static bool IsDate(string anyString)
{
DateTime dummyDate;
if (anyString == null)
anyString = “”;

if (anyString.Length > 0)
{
try
{
dummyDate = DateTime.Parse(anyString);
}
catch
{
return false;
}
return true;
}
else
{
return false;
}
}
You can also add other checks to insert values as you want to.