Showing posts with label ASP DotNet MVC. Show all posts
Showing posts with label ASP DotNet MVC. Show all posts

September 30, 2023

Enable Tag Helper using @tagHelperPrefix

The @tagHelperPrefix directive allows you to specify a tag prefix string to enable Tag Helper support and to make Tag Helper usage explicit.

For example, you could add the following markup to the Views/_ViewImports.cshtml file:

@tagHelperPrefix cst:

This allows you to enable Tag Helper support by using this prefix (cst). Only those elements using the prefix cst, support the Tag Helpers (Tag Helper-enabled elements have a distinctive font/color).

In the code image below, the <label> element have the Tag Helper prefix (cst), so the Tag Helper is enabled for this element. While the <input> element doesn't have Tag Helper prefix (cst), so Tag Helper is not enabled for this element, this is just a regular HTML element.

The same hierarchy rules that apply to @addTagHelper also apply to @tagHelperPrefix.

References:

Related Post(s):

Tag Helper scope with _ViewImports file

  • The _ViewImports.cshtml can be added to any view folder, and the view engine applies the directives from both that file and the Views/_ViewImports.cshtml file.
  • The _ViewImports.cshtml file is additive, If you add an empty Views/Home/_ViewImports.cshtml file for the Home views, there would be no change because it will import all tag helpers from Views/_ViewImports.cshtml file.
  • If you add new tag helpers in Views/Home/_ViewImports.cshtml file for the Home views, it will import all tag helpers from Views/_ViewImports.cshtml file, also it will import all tag helpers from Views/Home/_ViewImports.cshtml file.
  • Any new @addTagHelper directives you add to the Views/Home/_ViewImports.cshtml file (that are not in the default Views/_ViewImports.cshtml file) would expose those Tag Helpers to views only in the Home folder.

References:

Related Post(s):

August 28, 2023

Remove Tag Helpers with @removeTagHelper

Remove Tag Helpers with @removeTagHelper

The @removeTagHelper removes a Tag Helper that was previously added by @addTagHelper.

It has the same two parameters as @addTagHelper:

@removeTagHelper *, MyApplicationTagHelpers

For example, when you want to restrict a specific Tag Helper on a particular view, you can apply the @removeTagHelper to remove the specified Tag Helper.

Using @removeTagHelper in a child folder's _ViewImports.cshtml file (e.g. Views/Folder/_ViewImports.cshtml), it removes the specified Tag Helper from all of the views in that Folder.

Opting out of individual Tags

Instead of removing the Tag Helper from a View, you can also disable a Tag Helper at the element level with the Tag Helper opt-out character ("!").

For example, we can disable the Email validation in the <span> with the Tag Helper opt-out character:

<!span asp-validation-for="Email" class="text-danger"></!span>

In this case, the Tag Helper will be disabled on a single element (<span> in this case), rather than all elements in a View.

The Tag Helper opt-out character must be applied to the both opening and closing tags.

References:

Related Post(s):

Custom Tag Helpers in ASP.NET Core

Tag Helper allows you to add or modify HTML elements from server-side code. In Razor markup, the Tag Helper looks like standard HTML elements. It provides more productive syntax than manually writing the C# Razor markup.

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files.

(Microsoft Docs - Tag Helpers in ASP.NET Core)

To create a custom Tag Helper, you need to inherit from built-in TagHelper class. For example we have this Tag Helper,

public class StringTagHelper : TagHelper
{
   public override void Process(TagHelperContext context, TagHelperOutput output)
   {
      output.TagName = "span";
      output.TagMode = TagMode.StartTagAndEndTag;

      output.Attributes.Add("data-entity", "customer");

      base.Process(context, output);
   }
}

This Tag Helper will output the span element and add a custom attribute data-entity with value customer.

In the Razor markup, we can use this Tag Helper as:

<string field="CustomerID"></string>

Ofcourse we can add any extra/custom attributes to html tags, these will not interrupt with Tag Helpers.

The browser will render the final output as:

<span field="CustomerID" data-entity="customer"></span>

To use the Tag Helpers in the views, you need to set its scope, usually we define the scope in Views/_ViewImports.cshtml file.

Tag Helpers scope is controlled by a combination of @addTagHelper, @removeTagHelper, and the "!" opt-out character.

To make the required TagHelper avialable for one or more views we use @addTagHelper.

If you create a new ASP.NET Core web app named MyApplicationTagHelpers, the following Views/_ViewImports.cshtml file will be added to your project:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MyApplicationTagHelpers

Some points for above code:

  • The code above uses the wildcard syntax ("*") to specify that all Tag Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers) will be available to every view file in the Views directory or subdirectory.
  • The first parameter after @addTagHelper specifies the Tag Helpers to load ("*" is used to load all Tag Helpers)
  • The second parameter "Microsoft.AspNetCore.Mvc.TagHelpers" specifies the source assembly from which we want to load the Tag Helpers. It can be current project's assemly or any reference to external library.

References:

Related Post(s):

October 24, 2022

.NET Core - asp-append-version tag helper

To have better user experience and improve website's performance, modern browsers used to cache the static files like css, js and images. While it helps your website to perform better but it could also lead to serve stale files. If you have made any changes to your css, js or image files, the browsers will keep showing the old images until it refreshes it cache. Sometimes the users have to do a full refresh (Ctrl + F5 or Ctrl + R) for the browser to get latest or fresh content of these files.

In this case we need to tell the browser to get the new files from server to make sure that the user will always be served with latest files without doing full refresh on the browser.

Some ways to acheive this behavior could be:

  1. Every time you make any changes in the file content, also change the file name and its references.
  2. Another way is to add a random string behind the js, css or image url.

Here we will use the second approach to add a random string for these files urls.

The good news is that ASP.NET Core has in-build feature for this issue. We can use the tag helper:

asp-append-version="true" 

To enable this feature ON for particualr static file, we just need to add the above asp-append-version tag-helper/attribute as below.

CSS
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />    
JS 
<script src="~/js/site.js" asp-append-version="true"></script>
Image
<img src="~/images/logo.png" asp-append-version="true" />

After making these changes you can check the rendered html from browser source code or inspect element using browser's developer tools. It will be found that there is a random string attached behind file name.

If you make any change within the file content for css/js etc, when the next time browser will render it, it will fetch the fresh file from server because of different random string attached to the file URL.

CSS
https://localhost:7163/css/site.css?v=1Ip96t8Xk8GevF37Kz0Wu_1tuNyEZJcH5PYrmiK1fNs

JS
https://localhost:7163/js/site.js?v=mC13cRUFjf1YiinDRFWfv-eOXac88lLptssglYLhYtQ

You will see a different random string appended each time the changes are made to the file cotent, which makes sure that the browser will fetch the latest copy from server.

May 19, 2022

Configure IIS for CORS preflight OPTIONS request

To configure IIS to allow an ASP.NET app to receive and handle OPTIONS requests, we have to add the following configuration to the app's web.config file in the system.webServer > handlers section:

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" 
       type="System.Web.Handlers.TransferRequestHandler" 
       preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

Since the default ExtensionlessUrlHandler-Integrated-4.0 module registration only allows GET, HEAD, POST, and DEBUG requests with extensionless URLs. We will replace this module by first removing it and add with different attribute values to allow OPTIONS requests to reach the app.

After making these configuration changes, if the application still not responding as expected then you need to check the IIS's Request Filtering. It might be the case that IIS disallows OPTIONS verb at the root web application level.

  • Open IIS Manager
  • Click on root application
  • Click on Request Filtering
  • If OPTIONS appears in list, remove that entry and re-add with with Allow Verb... context menu option.

References:

Related Post(s):

How Cross Origin Resource Sharing (CORS) Works

Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, which preempts a malicious site from reading sensitive data from another site. .

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to lighten the same-origin policy. Because sometimes you might want to let other sites call your web API, in this case you have to configure CORS policy as per the requirements, so that the server can accept traffic for pre-defined scenarios and reject the calls otherwise.

You might enable the CORS using [EnableCors] attribute correctly in .Net Web API Project, but still the things don't work as per the expectation. So its important to understand how CORS works.

The CORS specification introduces several new HTTP headers that enable cross-origin requests. If a browser supports CORS, it sets these headers automatically for cross-origin requests; you don't need to do manually in your JavaScript code.

Lets say you are making an AJAX call to the API http://abc.com/api/test, from the website http://localhost:4201. Since the Origin header defines the domain of the source website which is making the request, in this case the Origin is http://localhost:4201

Here is an example of a cross-origin request representation:

(In Raw Format)

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Host: http://abc.com/api/test
Origin: http://localhost:4201
Referer: http://localhost:4201/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0

If the server allows the request, it sets the Access-Control-Allow-Origin response header. The value of this header either matches the Origin header (if the given domain is allowed), or is the wildcard value * (if any origin is allowed).

(In Raw Format)

content-type: application/javascript
content-length: 678
access-control-allow-origin: *
date: Mon, 16 May 2022 09:31:51 GMT

If the response does not include the Access-Control-Allow-Origin header, the AJAX request fails, and the browser disallows the request.

Preflight Requests

For some CORS requests, the browser sends an additional request, called a "preflight request", before it sends the actual request for the resource.

Browser sends the preflight request in certain conditions. Following are conditions in which the browser will not send the preflight request:

  1. The request method is GET, HEAD, or POST
  2. The application sends only these request headers: Accept, Accept-Language, Content-Language, Content-Type, or Last-Event-ID (any other request header will cause the browser to send preflight request).
    • Note that this restriction applies to the headers which the application will add to the request by calling setRequestHeader() method on the XMLHttpRequest object. These request headers are called as author request headers in the CORS specification .
    • The headers set by the browser (like User-Agent, Host, or Content-Length) are excluded from this restriction.
  3. If the Content-Type header is set, its value could only be one of the following (any other value for this header will cause the browser to send preflight request):
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

Here is an example of a preflight OPTIONS request:

(In Raw Format)

OPTIONS http://abc.com/api/test HTTP/2
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.5
Access-Control-Request-Headers: myheader1
Access-Control-Request-Method: GET
Connection: keep-alive
Host: http://abc.com
Origin: http://localhost:4201
Referer: http://localhost:4201/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0

As seen in above example request, the pre-flight request uses the HTTP OPTIONS method. It includes two special headers:

  • Access-Control-Request-Method: The HTTP method that will be used for the actual request (GET method in this above example).
  • Access-Control-Request-Headers: A list of request headers that the application set on the actual request, myheader1 is a custom header set in above example. Note that this does not include headers that the browser sets itself.

Here is an example response, assuming that the server allows the request:

(In Raw Format)

HTTP/1.1 200 OK
Access-Control-Allow-Headers: myheader1
Access-Control-Allow-Origin: *
Content-Length: 0
Date: Mon, 16 May 2022 09:40:05 GMT

The response can include the Access-Control-Allow-Methods header that lists the allowed methods (not listed in above example). The Access-Control-Allow-Headers header lists the allowed headers. If the preflight request succeeds (as in above case), then the browser sends the actual request.

References:

Related Post(s):

August 23, 2021

HttpPostedFile vs HttpPostedFileBase

While working with posted files in .Net MVC, you might have stuck with HttpPostedFileBase and HttpPostedFile. These classes have the same properties, but are not related. You can not cast one to the other, because they are completely different objects to .net.

HttpPostedFileBase is an abstract class, used solely for the purpose of being derived from. It is used to mock certain things in sealed class HttpPostedFile. To make things consistent, HttpPostedFileWrapper was created to convert HttpPostedFile to HttpPostedFileBase.

  • HttpPostedFile is a class representing posted files, its definitation looks like this:

    public sealed class HttpPostedFile
    

    This class can't be inherited and can't be mocked for unit testing.

  • HttpPostedFileBase is a unified abstraction, enables the developer to create mockable objects.

    public abstract class HttpPostedFileBase
    
  • HttpPostedFileWrapper is an implementation of HttpPostedFileBase that wraps HttpPostedFile. It looks like this:

    public class HttpPostedFileWrapper : HttpPostedFileBase
    {
    	public HttpPostedFileWrapper(HttpPostedFile httpPostedFile) 
    	{
    		//
    	};
    	//...
    

Create HttpPostedFileBase object from HttpPostedFile:

You can use HttpPostedFileWrapper class, which will accept HttpPostedFile object as a parameter to its constructor.

//suppose httpPostedFile is an object of HttpPostedFile class
HttpPostedFileWrapper httpPostedFileWrapper = new HttpPostedFileWrapper(httpPostedFile);
HttpPostedFileBase httpPostedFileBase = httpPostedFileWrapper; //HttpPostedFileBase is the parent class

Thanks to polymorphism, you can pass an instance of derived class (HttpPostedFileWrapper), to method accepting base class(HttpPostedFileBase)

Create HttpPostedFile object from HttpPostedFileBase:

Creating HttpPostedFile object is not straight similar as it is in above case. You have to make use of System.Reflection to achieve this:

var constructorInfo = typeof(HttpPostedFile).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
var httpPostedFile = (HttpPostedFile)constructorInfo
		  .Invoke(new object[] { httpPostedFileBase.FileName, httpPostedFileBase.ContentType, httpPostedFileBase.InputStream });

April 14, 2021

Use ClosedXML to write excel file

Office Open XML (also informally known as OOXML) is a zipped, XML-based file format developed by Microsoft for representing spreadsheets, charts, presentations and word processing documents. Starting with the 2007 Microsoft Office system, Microsoft Office uses the XML-based file formats, such as .docx, .xlsx, and .pptx representing Microsoft Word, Microsoft Excel, and Microsoft PowerPoint repectively.

The OpenXML specification is a large and complicated model to implement. Trying to implement this model by your own involves a lot of time and effort. Another option is to use ClosedXML (an open source library created based on OpenXmlSdk) for manipulate OpenXML format files.

ClosedXML is a .NET library for reading, manipulating and writing Excel 2007+ (.xlsx, .xlsm) files. Having user-friendly model, it makes it easier to deal with OpenXML API.

To install ClosedXML, run the following command in the Package Manager Console:

Install-Package ClosedXML

The most important point about ClosedXML is:

ClosedXML allows you to create Excel files without the Excel application. The typical example is creating Excel reports on a web server.

First you have to import the library for Excel classes:

using ClosedXML.Excel;

In the following code snippet, we are creating a new worksheet Sheet1 and writing the text Hello World! on the cell A1, then save the file as HelloWorld.xlsx:

using (var workbook = new XLWorkbook())
{
    var worksheet = workbook.Worksheets.Add("Sheet1");
    worksheet.Cell("A1").Value = "Hello World!";
    workbook.SaveAs("HelloWorld.xlsx");
}

Change the font for the whole sheet:

worksheet.Style.Font.FontName = "Calibri";

Change the font style and color for a particular cell:

worksheet.Cells("A1").Style.Font.FontSize = 14;
worksheet.Cells("A1").Style.Font.Bold = true;
worksheet.Cells("A1").Style.Font.FontColor = XLColor.White;

Select the range and fill background color:

var range1 = worksheet.Ranges("A1:A25,B1:B25");
range1.Style.Fill.BackgroundColor = XLColor.FromHtml("#556B2F");

Adjusts the width of all columns based on its contents.

worksheet.Columns().AdjustToContents();

These are few examples which demonstrates the basic functionality ClosedXML supports for Excel files.

For official project site and Nuget Package, please visit the github and nuget sites:

References(s):

January 29, 2021

Call WCF - Set SecurityProtocol & ServerCertificateValidationCallback

.Net Applications use ServicePointManager.SecurityProtocol Property to specify the version of the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocol for new connections, existing connections aren't changed.

It is recommended that you should not specify this property manually and let it be use its default value, which will be obtained from machine configuration. Still In some scenarios, you may want to specifically define the SecurityProtocol when calling a WCF service with Https link. In this case you can define the required protocols like this:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                   | SecurityProtocolType.Tls11
                   | SecurityProtocolType.Tls12
                   | SecurityProtocolType.Ssl3;

Since these are flags, so you can use bitwise OR(|) operator to specifiy multiple protocols if your connection requires.

Another property is ServerCertificateValidationCallback, which is used by the client to perform custom validation for the server certificate. The sender parameter passed to the RemoteCertificateValidationCallback can be a host string name or an object derived from WebRequest (HttpWebRequest, for example) depending on the CertificatePolicy property.

If you trust the server and not using custom validation, you can simply return true from the callback method.

 
ServicePointManager.ServerCertificateValidationCallback =
             new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);

Here is the definition of IgnoreCertificateErrorHandler, which will always return true.

private static bool IgnoreCertificateErrorHandler(object sender,
   X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{​​​​​​​
	return true;
}​​​​​​​

You can also replace the above callback method definition with a short-hand delegate syntax.

ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

References:

January 23, 2021

When to set ServicePointManager.SecurityProtocol Property

When communicating with external services using TLS/SSL through APIs (such as HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream), .Net application uses ServicePointManager.SecurityProtocol Property as the version of the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocol for new connections, existing connections aren't changed.

Summary points

  • No default value is listed for this property for .Net Framework versions prior to 4.6.2.
  • Since default protocols and protection levels are changed over time in order to avoid known weaknesses. Therefore defaults vary depending on individual machine configuration, installed software, and applied patches.
  • When developing custom applications, avoid the assumption that a given security level is used by default. Only if you are sure that a particular application connection requires an specific security level (SSL/TLS) then you can explicitly specify the matching level in your code.

Review the following points for TLS support in different .Net Frameworks.

  • Starting with the .NET Framework 4.7, the default value of this property is SecurityProtocolType.SystemDefault. Which means the default security protocols from the operating system (or from any custom configurations performed by a system administrator) will be inherited by .NET Framework's networking APIs based on SslStream (such as FTP, HTTP, and SMTP).
  • For .NET 4.6 and above: Includes a new security feature that blocks insecure cipher and hashing algorithms for connections. TLS 1.2 is supported by default.
  • For .NET 4.5: TLS 1.2 is supported, but it’s not a default protocol. You need set manually. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    
  • For .NET 4.0: TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still set for TLS 1.2 even if your application framework doesn’t support it. The problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so you would have to use a numeric value and cast it to SecurityProtocolType enum:
        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
    
  • For .NET 3.5 or below: TLS 1.2 is not supported. Upgrade your application to more recent version of the framework.

References:

HTTP Error 500.19 - Internal Server Error - HRESULT: 0x8007000d

I added URL rewrite section in web.config file in .Net Core 2.2 Application, and it starts generating the error HTTP Error 500.19 - Internal Server Error.

Error Details:

    Server Error in Application "application name"
    HTTP Error 500.19 – Internal Server Error
    HRESULT: 0x8007000d
    Description of HRESULT
    The requested page cannot be accessed because the related configuration data for the page is invalid.

Cause

As per MSDN:

This problem occurs because the ApplicationHost.config or Web.config file contains a malformed XML element.

Resolution

As per MSDN:

Delete the malformed XML element from the ApplicationHost.config or Web.config file.

But since URL rewrite config section is not malformed as these are all valid config xml. In my case I found that URL rewrite module was not installed on the server, so installing the missing module fixed my issue.

You can download URL Rewrite Extension from Official Microsoft IIS Site:

Or use Direct MSI link for winx64

It should start working at this point.

Install .Net Core Hosting Bundle and reset IIS:

If it still not works, try to install / repair the .Net Core Hosting Bundle. e.g You can download version 6.0 from Download .NET 6.0

Finally, reset IIS by running the following command:

iisreset

You need to open the command prompt with Run as administrator option.

References:

July 22, 2020

How to include external files/folders in Publish Profile

Often we need to include external files/folders in publish profile to deploy on published site. We have two ways to achieve this:

General file inclusion

In this method we use the DotNetPublishFiles tag, which is provided by a publish targets file in the Web SDK.

The following example's demonstrates how to copy a folder located outside of the project directory to the published site.

<ItemGroup>
    <MyCustomFiles Include="$(MSBuildProjectDirectory)/../ExternalContent/**/*" />
    <DotNetPublishFiles Include="@(MyCustomFiles)">
      <DestinationRelativePath>wwwroot/ExternalContent/%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
    </DotNetPublishFiles>
  </ItemGroup>
  • Declares a MyCustomFiles(it can be any custom name) tag to cover files matching the globbing pattern specified in Include attribute. The ExternalContent folder referenced in the pattern is located outside of the project directory. We are using a reserved property $(MSBuildProjectDirectory), which resolves the project file's absolute path.

  • In DotNetPublishFiles tag, we provide our custom tag name MyCustomFiles in the Include attribute, whih serves as a source path for files/folders. In DestinationRelativePath tag, we specified the target path(with respect to published folder) where we want to copy the files. In this example, we are copying ExternalContent folder's content to wwwroot/ExternalContent folder. We have also used item metadata such as %(RecursiveDir), %(Filename), %(Extension). This represents the wwwroot/ExternalContent folder of the published site.

If you don't want to specify source path relative to the project file's absolute path, you can also specific local absolute path, like:

  <ItemGroup>
    <MyCustomFiles Include="C:\Test\ExternalContent\*" />
    <DotNetPublishFiles Include="@(MyCustomFiles)">
      <DestinationRelativePath>wwwroot/ExternalContent/%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
    </DotNetPublishFiles>
  </ItemGroup>

Here we have changed the source relative path from $(MSBuildProjectDirectory)/../ExternalContent/**/* to C:\Test\ExternalContent\*.

Selective file inclusion

In this method we will use the ResolvedFileToPublish tag, which is provided by a publish targets file in the .NET Core SDK. Because the Web SDK depends on the .NET Core SDK, either item can be used in an ASP.NET Core project.

The following exmaple demonstrates how to copy a file located outside of the project into the published site's wwwroot folder. The file name of externalfile.txt is maintained.

  <ItemGroup>
    <ResolvedFileToPublish Include="..\externalfile.txt">
      <RelativePath>wwwroot\externalfile.txt</RelativePath>
    </ResolvedFileToPublish>
  </ItemGroup>
  • In ResolvedFileToPublish tag, we are using Include attribute to specify the file we want to copy. This file resides in the parent directory of the project file's container directory.

  • RelativePath represent the relative path for the published directory.

The default behavior of ResolvedFileToPublish is to always copy the files provided in the Include attribute to the published site. We can override this default behavior by including a CopyToPublishDirectory child tag with inner text of either Never or PreserveNewest. For example:

 <ResolvedFileToPublish Include="..\externalfile.txt">
   <RelativePath>wwwroot\externalfile.txt</RelativePath>
   <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
 </ResolvedFileToPublish>

Again, if you don't want to specify source path relative to the project file's absolute path, you can also specific local absolute path, like:

  <ItemGroup>
    <ResolvedFileToPublish Include="C:\Test\externalfile.txt">
      <RelativePath>wwwroot\externalfile.txt</RelativePath>
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </ResolvedFileToPublish>
  </ItemGroup>

References:

July 21, 2020

How to exclude files from Publish Profile

When publishing ASP.NET Core web apps, it will publish/deploy the:

  • Build artifacts
  • files with .config extension
  • files with .json extension
  • everything inside wwwroot folder

At certain times you may need to exclude some specific file or folder from deployment content.

There are two ways you can exclude files from publishing.

Content Tag

If you need to prevent multiple files from being copied to deployed folder, you can use globbing patterns to cover a range of matching files.

Content tag will be used to specify the action on the file. For example, the following Content element will exclude all (.txt) files in the wwwroot\content folder and its subfolders.

<ItemGroup>
  <Content Update="wwwroot/content/**/*.txt" CopyToPublishDirectory="Never" />
</ItemGroup>

Note that it will delete all (.txt) files that are already exists at the deployed site within specified folder path.

You can specify different globbing patterns as per your requirement. Another version of pattern coud be like this:

<ItemGroup>
  <Content Update="wwwroot/content/Site*.css" CopyToPublishDirectory="Never" />
</ItemGroup>

This will match all css files in wwwroot/content folder with file name starts with Site e.g. SiteAdmin.css, SiteCustomer.css, etc...

You can add this markup to a publish profile (.pubxml file) or the .csproj file. Since .csproj file operates at the global level, if you add this tag to the .csproj file, the rule will be applied to all publish profiles in the project.

MsDeploySkipRules Tag

Another way to exclude file or folder is to use MsDeploySkipRules tag.

The following tag excludes all files/folders from the wwwroot\content folder:

<ItemGroup>
  <MsDeploySkipRules Include="CustomSkipFolder">
    <ObjectName>dirPath</ObjectName>
    <AbsolutePath>wwwroot\\content</AbsolutePath>
  </MsDeploySkipRules>
</ItemGroup>

Note that unlike Content tag, this will not delete the targeted file or folder if that are already exists on the deployed site.

Similarly you can specify a single file in AbsolutePath tag, but you need to change the ObjectName tag to filePath rather than dirPath, and also change the value of Include attribute from CustomSkipFolder to CustomSkipFile.

<ItemGroup>
  <MsDeploySkipRules Include="CustomSkipFile">
    <ObjectName>filePath</ObjectName>
    <AbsolutePath>wwwroot\\content\\Site.css</AbsolutePath>
  </MsDeploySkipRules>
</ItemGroup>

References:

June 25, 2020

Visual Studio 2017 - Create a Publish Profile

In Visual Studio you can create Publish profiles to simplify the publishing process. You can add any number of profiles within a single project to publish the application for different scenarios or environments. Once the profile is created, you can use that profile to publish the application from Visual Studio or from command line.

You can create a publish profile by right click on the project and click Publish option.

Note that you need to launch the Visual Studio under Administrator mode in order to create/save a profile.

It will open a dialog and ask you to Pick a Publish target. In this example I am selecting the option IIS, FTP, etc.

Select the IIS, FTP, etc option and click Publish button on the bottom. It will open a new dialog allow you to configure profile. Fill in the required information. In this example, I am publishing MyApp on the server localhost.

Click the Next button, it will allow you to configure more settings, like Configuration, Target Framework, Remove additional files at destination etc.

After you are satisfied with the configuration settings click on the Save button. Visual Studio's publish tool creates an xml file at Properties/PublishProfiles/{PROFILE NAME}.pubxml describing the publish profile. This file contains configuration settings that will be consumed by the publishing process. You can easily edit this xml file to customize the publish process. When you click on the Save button, it will close this dialog and returns back to the project's publish screen. It will start publishing your project first time on the target server. In IIS it will create a new website with the name you provided during publish profile, and sets the Application pool to the DefaultAppPool

If everything goes fine, after successful publishing it will open the target URL in the default browser.

April 18, 2020

How to build query string for System.Net.HttpClient GET Request

In this post I will explain multiple ways to use parameters for HTTP GET Request using System.Net.HttpClient. You don't need to build parameters string by concatenating different values from a name-value collection.

  • First method is to use HttpUtility.ParseQueryString() function.

    var query = HttpUtility.ParseQueryString(string.Empty);
    query["p1"] = "value1";
    query["p2"] = "value2";
    string queryString = query.ToString();
      

    queryString variable contains the parameters in query string format.

  • Another way could be to use UriBuilder class.

    var builder = new UriBuilder("http://example.com");
    builder.Port = -1;
    
    var query = HttpUtility.ParseQueryString(builder.Query);
    query["p1"] = "value1";
    query["p2"] = "value2";
    builder.Query = query.ToString();
    
    string url = builder.ToString();
      

    The url variable will contain both the page URL and query string parameters.

  • If you do not want to include a reference to System.Web in your project, you can use FormDataCollection class by adding reference to System.Net.Http.Formatting.

    var parameters = new Dictionary()
    {
     { "p1", "value1" },
     { "p2", "value2 + SomeOtherValue?" },
    }; 
    
    var queryString = new FormDataCollection(parameters).ReadAsNameValueCollection().ToString();
      

    queryString variable now contains the parameters in query string format.

  • If you are using ASP.Net Core, you can use the QueryHelpers class by first adding reference to Microsoft.AspNetCore.WebUtilities.

    var query = new Dictionary
    {
     ["p1"] = "value1",
     ["p2"] = "value2",
    };
    
    var response = await client.GetAsync(QueryHelpers.AddQueryString("/api/", query));
      

November 6, 2018

Unhandled exception of type ‘StackOverflowException’

While working on website project using Visual Studio 2015, I encountered this strange error message:

 An unhandled exception of type ‘System.StackOverflowException’ 
 occurred in System.Runtime.Serialization.dll
StackOverFlow exception

You may notice that if you click on View Detail... link of the exception message, there is no more information is available like stack trace etc.

StackOverFlow exception

I know there is no any complex logic defined in my code-base that could fall in infinite loop and cause StackOverflowException. After searching, I found the real cause of this error, and is not related to my code-base but a feature by Visual Studio know as Browser Link.

From MSDN blog:

Browser Link is just a channel between your Visual Studio IDE and any open browser. This will allow dynamic data exchange between your web application and Visual Studio.

Visual Studio uses this channel to exchange data between web application and Visual Studio, since it will serialze data before exchange, that was leading to StackOverflowException. The solution is just disable this feature.

There are two ways to disable this feature:

  1. From Visual Studio, click on the small down arrow near Refresh Linked Browsers button, from the drop-down options listed, just un-check Enable browser link.

    Enable browser link
  2. Add the following key in web.config appSettings tag.

     <add key=”vs:EnableBrowserLink” value=”false” />
    

Resources:

October 11, 2018

ASP.NET Health Monitoring with Custom Events

In the last post we have created a custom provider to send log data to WCF service client using ASP.NET Health Monitoring feature. We have seen that there are multiple events which we can map to the provider in order to log information about that events. Just to recap here is the list of default events available by ASP.Net Health Monitoring feature.

  • All Events
  • Heartbeats
  • Application Lifetime Events
  • Request Processing Events
  • Infrastructure Errors
  • Request Processing Errors
  • All Audits
  • Failure Audits
  • Success Audits

These events could provide plenty of useful information which can help us to analyze application state if there comes any problem while running in production environment. But there may be the case where you might want to log your own custom event. For example, I want to log a hit event for specific page using this feature rather than use some other logging library or write my own, which further may require extra configuration steps or wrapper classes. Writing your own custom event helps you to log event information with ASP.Net Health Monitoring feature and saves you from that extra effort.

Lets start writing the custom event.

First we have to inherit base class WebRequestEvent found in the namespace System.Web.Management. While calling the base constructor we have to provide eventCode. Note that for custom events we have available event codes starting from 100000. You may find full list of event codes defined as constant fields in WebEventCodes sealed class. The Last EventCode constant defined is:

public const int WebExtendedBase = 100000;

For custom events we have to use codes starting from this number. In this exmaple I am using constant event code variable by adding to 10 to the WebExtendedBase event code value, as:

private const int EVENT_CODE = System.Web.Management.WebEventCodes.WebExtendedBase + 10;

10 is just an arbitrary value, you can pick any number.

If you want to add extra information then you have to write an override of Raise() function, which is not necessary, but in this example I am writing this override to add my custom message, in a class level private variable I am using this variable to add information about current UserId from session variable if present:

private string defaultLocalMessage = "";

Which I want to log alongwith other fields. But this variable could not be directly accessible from WebBaseEvent object's properties which we see in last example, in ProcessEvent() method of custom provider. If we can not directly access additional variables then what is the benefit of using this variable? Well, There is a workaround!

Any additional information holding by custom variables, can be used in another overriden function FormatCustomEventDetails. Although this function returns void, it will not directly return any value but this function is interally called when the provider invokes one of the ToString() methods. So, finally when you call ToString() function for WebBaseEvent object in the function ProcessEvent(), you will get that additional information that you holded in local variables and added to the WebEventFormatter object in another overriden method FormatCustomEventDetails(). When you see the code you will get it more clear.

Here is the complete code listing for custom event class PageHitRequestEvent.

public class PageHitRequestEvent : System.Web.Management.WebRequestEvent
{
    private string defaultLocalMessage = "";
    private const int EVENT_CODE = System.Web.Management.WebEventCodes.WebExtendedBase + 10;

    public PageHitRequestEvent(string eventMessage, object eventSource)
        :
        base(eventMessage, eventSource, EVENT_CODE)
    {
        
    }

    // Raises the PageHitRequestEvent.
    public override void Raise()
    {
        // prepare custom message.
        defaultLocalMessage = "";
        if(HttpContext.Current == null)
        {
            defaultLocalMessage = ", LocalMessage: {Request Context is null";
        }
        else
        {
            defaultLocalMessage += "SessionID: " + HttpContext.Current.Session.SessionID;

            string userId = HttpContext.Current.Session["UserId"] as string;
            if (string.IsNullOrEmpty(userId))
            {
                defaultLocalMessage += ", UserId: (Anonymous)";
            }
            else
            {
                defaultLocalMessage += ", UserId: " + HttpContext.Current.Session["UserId"];
            }
            defaultLocalMessage += "}";
        }
        
        // raise the event. 
        base.Raise();
    }

    public override void FormatCustomEventDetails(WebEventFormatter formatter)
    {
        base.FormatCustomEventDetails(formatter);

        // Add custom data.
        formatter.AppendLine("");

        formatter.IndentationLevel += 1;

        formatter.TabSize = 4;

        formatter.AppendLine("* PageHitRequestEvent Start *");

        // Display custom event information.
        formatter.AppendLine(defaultLocalMessage);
              
        formatter.AppendLine("* PageHitRequestEvent End *");

        formatter.IndentationLevel -= 1;
    }   
    
}

The second step is to raise this event from the source we want to log information about. Lets say we have some critical page in WebForms application or Contoller/Action in MVC Application, and we want to log data every time user hit that URL. Only we have to create the object of custom event class and simply call the Raise() method, which will just trigger the event and any related provider will handle this event as usual.

PageHitRequestEvent myEventObject = new PageHitRequestEvent("some logging message", this);
// raise the event.
myEventObject.Raise();

If you are using the custom provider from my previous post, where I logged detailed information from ToString() method, you will also get the information which you have written to the WebEventFormatter object in FormatCustomEventDetails method.

Finally comes the configuration part. Although in custom provider example, we have mapped eventName="All Events" in rules section, which will allow the corresponding provider to handle all events, so also our custom event we have created in this example.

But also if you want you can separately add custom event and its mapping with the desired provider.

First add the following line in eventMappings tag to define custom event name.

 <add name="My Event" type="PageHitRequestEvent" />

Second add following line in rules tag to map this event to the desired provider.

 <add name="My Event Rule" eventName="My Event" provider="FailedAuthenticationProvider2"
            minInstances="1" maxLimit="Infinite" minInterval="00:00:00" custom="" />
 

Now the given provider should be able to handle the custom event when triggered.

Resources:

October 4, 2018

ASP.NET Health Monitoring using Custom Provider

ASP.NET Health Monitoring is a useful tool for logging error information that could ease diagnosing problems in a deployed application.

I have found this great article at Microsoft for configuring health monitoring feature in web projects.
Logging Error Details with ASP.NET Health Monitoring (C#)

Although builtin providers are more than enough to provide a rich information about the state of application. But there could be a chance you need to create custom provider to log additional information or additional storage option. Like in my case we need to log data in separate database which our application do not have direct access, but we have to call WCF service which would store data in target database. For this requirement I have written my custom provider.

Before proceeding to write code for custom provider, I recommend you to review the above mentioned article for health monitoring which will give you a strong background information.

Lets start writing custom provider class.

public class WCFCustomWebEventProvider : WebEventProvider
{
 //WCF service's client object.
    MiddleWare.ServiceClient _client = new MiddleWare.ServiceClient();
 
    public override void Initialize(String name, System.Collections.Specialized.NameValueCollection config)
    {
        base.Initialize(name, config);
    }

    public override void Flush()
    {

    }

    public override void ProcessEvent(WebBaseEvent raisedEvent)
    {
  //prepare StringBuilder with required information from WebBaseEvent object
        StringBuilder sb = new StringBuilder();
        sb.Append("EventId: " + raisedEvent.EventID + ", ");
        sb.Append("EventTime: " + raisedEvent.EventTime + ", ");
        sb.Append("EventTimeUtc: " + raisedEvent.EventTimeUtc + ", ");
        sb.Append("EventType: " + raisedEvent.GetType().Name + ", ");
        sb.Append("EventSource: " + raisedEvent.EventSource + ", ");
        sb.Append("EventSequence: " + raisedEvent.EventSequence + ", ");
        sb.Append("EventOccurrence: " + raisedEvent.EventOccurrence + ", ");
        sb.Append("EventCode: " + raisedEvent.EventCode + ", ");
        sb.Append("EventDetailCode: " + raisedEvent.EventDetailCode + ", ");
        sb.Append("Message: " + raisedEvent.Message + ", ");
        sb.Append("ApplicationPath: " + WebBaseEvent.ApplicationInformation.ApplicationPath + ", ");
        sb.Append("ApplicationVirtualPath: " + WebBaseEvent.ApplicationInformation.ApplicationVirtualPath + ", ");
        sb.Append("MachineName: " + WebBaseEvent.ApplicationInformation.MachineName + ", ");
        sb.Append("RequestUrl: " + HttpContext.Current.Request.Url.AbsoluteUri + ", ");
        sb.Append("Details: " + raisedEvent.ToString());

  //pass the string to WCF client object.
        _client.CreateLog(sb.ToString());
    }

    public override void Shutdown()
    {

    }
}

I have tried to keep it simpler to meet basic requirements, and avoid additional changes which you may need for performance requirements like make use of buffering.

Here, in the ProcessEvent override method, I prepared a string variable build up the required information from argument WebBaseEvent raisedEvent. Then the final string message containing all required logging details is then passed to the WCF client. Putting all the logging information in a single string variable is obviously not a good approach, I did here only to keep things simple and try to focus on the logic to add custom provider. A better approach could be to split data of our interest in separate variables and update the WCF method to accept multiple parameters.

Here we are done with custom provider's C# code.

I assumed that you have read the above mentioned article, so now I will move to the web.config part.

Add the following healthMonitoring tag inside system.web.

<healthMonitoring enabled="true">
   <providers>
  <add name="WCFCustomWebEventProvider_1" type="WCFCustomWebEventProvider" />
   </providers>
   <rules>
   <add name="All Events Rule" eventName="All Events" provider="WCFCustomWebEventProvider_1"
    minInstances="1" maxLimit="Infinite" minInterval="00:00:00" custom="" />
   </rules>
   <eventMappings>
  <add name="All Events" type="System.Web.Management.WebBaseEvent,System.Web,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
   startEventCode="0" endEventCode="2147483647" />
   </eventMappings>
</healthMonitoring>

For simplicity, I am logging All Events, and also removed the configuration sections for bufferModes and profiles which you can add if you need more control over logging. Note that I have mentioned the custom provider WCFCustomWebEventProvider in the type attribute while adding provider.

At-minimum, health monitoring needs you to configure three basic elements.

  1. Providers: You have to specify a provider which will decide the storage target and do the work to store logging information. You can also define multiple providers like for some critical errors, you need to log information in the database and also want to generate an email to the system administrator. In our exmaple, we have used only one custom provider which will store information by calling WCF client method.

  2. EventMappings: It contains all the events names we are interested to log information about. In our example I placed a single event name All Events, which enables the application to log data about all events. If you dont need to log data about all events, you can define the desired events according to the requirements.

    Some other available events are:

    • All Events
    • Heartbeats
    • Application Lifetime Events
    • Request Processing Events
    • Infrastructure Errors
    • Request Processing Errors
    • All Audits
    • Failure Audits
    • Success Audits
  3. Rules: Rule is basically a mapping you have to define, to decide which event should mapped to which provider. In our example, I have defined that eventName="All Events" should be handled by provider="WCFCustomWebEventProvider_1".

February 24, 2018

ASP.NET MVC - DateTime format for each request

I was being asked this question by one of my colleague, if we can set a DateTime format at some global level so that if we need to display/process date at multiple controllers or views, we should not be worried about a specific format. I came up with this solution, I am sharing here, and welcome your suggestion or comments for any improvements or alternative solutions.

Lets say we need to display and save date in yyyy/MM/dd format. Since our server default format is set to dd/MM/yyyy, and we could not change it because some other applications might get affected, so we decided to set the required format at request level in our ASP.Net MVC application. For this we have to set the date format for current culture for each request, i.e. inside Global.asax.cs, in Application_BeginRequest() event.

Here is the real code which will set the format for current culture with the required one.

protected void Application_BeginRequest(Object sender, EventArgs e) 
{
 CultureInfo newCultureInfo = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
        newCultureInfo.DateTimeFormat.ShortDatePattern = "yyyy/MM/dd";
        //newCultureInfo.DateTimeFormat.LongDatePattern = "yyyy/MM/dd";
        //newCultureInfo.DateTimeFormat.FullDateTimePattern = "yyyy/MM/dd";
        newCultureInfo.DateTimeFormat.DateSeparator = "/";
        Thread.CurrentThread.CurrentCulture = newCultureInfo;
}

Here I am setting the DateTimeFormatInfo object's ShortDatePattern property to "yyyy/MM/dd", in CurrentCulture. Similarly you can set other required properties like LongDatePattern, FullDateTimePattern, ShortTimePattern or LongTimePattern etc. In this way you don't have to set the required date pattern in multiple places.