Tuesday, April 25, 2023

Git Commands and Using Them in Visual Studio

 Git is a widely used version control system that allows developers to manage changes to their code and collaborate with other IDE like Visual Studio 2019, 2022.  

By understanding these basic Git commands, we can effectively collaborate on projects and keep our code organized.

In this article, we'll look at some common Git commands and how to use them in both versions of Visual Studio.

  1. git clone: Used to create a local copy of a remote repository. In Visual Studio, we can clone a repository by going to the Team Explorer window, clicking "Clone a repository," and entering the repository's URL.
  2.  git add: Used to stage changes to be committed. We can stage changes by going to the Changes window, right-clicking on the file we want to stage, and selecting "Stage."
  3. git commit: Used to commit staged changes to the local repository. We can commit changes by entering a commit message in the Changes window and clicking on the "Commit All" button.
  4. git push: Used to upload local changes to a remote repository. We can push changes by clicking on the "Push" button in the Team Explorer window.
  5. git pull: Used to download changes from a remote repository to the local repository. We can pull changes by clicking on the "Sync" button in the Team Explorer window and selecting "Pull."
  6. git branch: Used to create, delete, or list branches in the repository. In Visual Studio, We can manage branches by going to the Branches window and right-clicking on the branch we want to modify.
  7. git merge: Used to merge changes from one branch into another. In Visual Studio, We can merge branches by going to the Branches window, right-clicking on the target branch, and selecting "Merge From."

Web APIs: Enhance Testing and Debugging with .http Files in Visual Studio 2022

 The .http file extension is a new feature introduced in Visual Studio 2022, and it is used for HTTP request/response files. These files allow developers to easily test and debug web APIs by writing HTTP requests and viewing the responses directly in the IDE.

With the .http file extension, we can create a file that contains one or more HTTP requests. Each request can be specified with a specific HTTP method, headers, and request body. We can also specify the target URL for the request, making it easy to test different endpoints of an API.

One of the benefits of using .http files is that we can test and debug our API without leaving the IDE. This saves our time and makes it easier to catch errors early on in the development process. Additionally, we can easily share these files with our team members, allowing them to replicate our tests and debug issues.

To use the .http file extension in Visual Studio 2022, we will need to have the "Web Developer Tools" installed. Once installed, we can create a new .http file by selecting "File" > "New" > "File" and selecting "HTTP request file" from the list of available templates.

In summary, the .http file extension in Visual Studio 2022 is a useful tool for testing and debugging web APIs. It allows us to write and execute HTTP requests directly in the IDE, saving our time and helping us catch errors early on in the development process.

Friday, April 26, 2019

ASP.NET: Remove ASP.NET, AspNet-Version, IIS Server from HTTP Response Header using web.config

Remove Server from response header with an outboundRule URL Rewrite rule. This will work for IIS 7+ (IIS 7, 8.5, 8.0, 8.5):

<rewrite>   
  <outboundRules rewriteBeforeCache="true">
    <rule name="Remove Server header">
      <match serverVariable="RESPONSE_Server" pattern=".+" />
      <action type="Rewrite" value="" />
    </rule>
  </outboundRules>
</rewrite>

In Microsoft-IIS/8.0, we can rewrite 'Server: Microsoft-IIS/8.0' with your own text:

<action type="Rewrite"
  value="ABC custom text" />

To remove the server from response header in Microsoft-IIS 10.0, we can add this in web.config
<security>
  <requestFiltering removeServerHeader ="true" />
</security>

Remove ASP.NET X-Powered-By from response header:
<httpProtocol>
  <customHeaders>
    <remove name="X-Powered-By" />
  </customHeaders>
</httpProtocol>

Remove  X-AspNet-Version header from response header:
<httpRuntime enableVersionHeader="false" />

Tuesday, February 23, 2016

Custom Validation in MVC/Web API using ValidationAttribute

This article is to help us, how to implement custom validation and use it as Data Annotation.
Custom Validation is very useful when we are using the same Property in number of places in our application, rather than to add AddModelError in ModelState, it is a good practice to create this in a separate reusable library so that we can use this in project with very consistent way and re-use in any other project. This should be project independent library and reusable component. 
Following are the steps to create Custom Validator and use it in view model classes.

  1. Create New class DateRangeAttribute inherit from ValidationAttribute
  2. Ensure value is of type DateTime, if not throw ValidationException.
  3. Create constructor to get values dynamically from the View Model.
  4. Override IsValid method of ValidationAttribute class and write logic to validate Date range.
Example
Date Range Attribute Class
 public class DateRangeAttribute: ValidationAttribute
    {
        private int _endAge;
        private int _startAge;

        public DateRangeAttribute(int startAge, int endAge)
        {
            startAge = _startAge;
            endAge = _endAge;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if(!(value is DateTime))
            {
                throw new ValidationException("DateRange is valid for DateTime property only.");
            }
            else
            {
                var date = (DateTime)value;
                //Better to create DateTime extension method to calculate Age
                if ((Calculate.GetAge(date)< _startAge) || (Calculate.GetAge(date) < _endAge))
                {
                    return new ValidationResult(this.FormatErrorMessage(validationContext.MemberName));
                }
                else
                {
                    return ValidationResult.Success;
                }
            }
        }

    }
Usage
    public class User
    {
        [Required]
        public string FirstName { get; set; }

        [Required]
        public string LastName { get; set; }

        [DateRange(18, 100)]
        public string BirthDate { get; set; }


    }

Monday, February 22, 2016

Logging in .Net

Coming soon

Creating Windows Service in .Net with Topshelf

Creating Windows Service in .Net with Topshelf

This article is to help us to create windows service in .Net with Topshelf and how to install it.
Microsoft Windows services/NT services, allow us to create long-running applications that run in the background repetitively without the need of any user interface or user interaction like Windows Forms Application, WPF Application, Console Application. 
There are different ways to create Windows Service applications using the .NET Framework, but the one way is to use open source project Topshelf.
Topshelf is an open source Windows service framework for the .Net platform that make it easy to create a Windows Services.
Why would I use Topshelf to create Windows service?
It makes easy to create a Windows service as well as test the service, debug the service, and install it into the Windows Service Control Manager (SCM) with simple commands.
By using Topshelf, we don’t need to understand the complex details of service classes, perform installation via InstallUtil, or learn how to attach the debugger to services for troubleshooting issues.
With Topshelf, creating a Windows service is as easy as creating a console application. Once the console application is created, we need to create a single service class with public Start and Stop methods and configure as service using Topshelf’s configuration API.
Now, we have complete Windows service that can be debugged using the debugger (just by pressing F5) and installed using the Topshelf command (install/uninstall).
Here is link of Topshelf open source project documentation https://topshelf.readthedocs.org/en/latest/.
Following are the steps to create windows service in .Net with Topshelf:
  1. Create a New Project with Console Application Template using Visual Studio.


  1. Install Topshelf using NuGet Package Manager.

  1. Create a class that contain our service logic: MyService.cs
namespace WindowsServiceWithTopshelf
{
    public class MyService
    {
        public void Start()
        {
            // write code here that runs when the Windows Service starts up.
        }
        public void Stop()
        {
            // write code here that runs when the Windows Service stops.
        }
    }
}
  1. Create a class to configure our service logic using the Topshelf project: ConfigureService.cs
using Topshelf;

namespace WindowsServiceWithTopshelf
{
    internal static class ConfigureService
    {
        internal static void Configure()
        {
            HostFactory.Run(
                configure =>
                {
                    configure.Service<MyService>(
                        service =>
                        {
                            service.ConstructUsing(s => new MyService());
                            service.WhenStarted(s => s.Start());
                            service.WhenStopped(s => s.Stop());
                        });
                    //Setup Account that window service use to run.
                    configure.RunAsLocalSystem();
                    configure.SetServiceName("MyWindowServiceWithTopshelf");
                    configure.SetDisplayName("MyWindowServiceWithTopshelf");
                    configure.SetDescription("My .Net windows service with Topshelf");
                }
                );
        }
    }
}
  1. Call configure service in Main():
namespace WindowsServiceWithTopshelf
{
    class Program
    {
        static void Main(string[] args)
        {
            ConfigureService.Configure();
        }
    }
}
  1. Build Console application
  2. Install/uninstall Console Application using Topshelf command
    1. Run Command Prompt as an Administrator and navigate to the bin/debug folder of Console Application.
> WindowsServiceWithTopshelf.exe install


    1. To uninstall windows service run this command
 > WindowsServiceWithTopshelf.exe uninstall
  1. How to Debug Window service created using Topshelf?
Just by pressing F5 like console application.


Friday, September 27, 2013

ASP.NET security

Automated Security Analyzer for ASP.NET Websites - https://asafaweb.com/

ASP.NET APP SECURITY:

The worst 5 mistakes in the web.config file:



Custom errors and stack traces:


Display Safe Error Messages:


Request validation:


Session Fixation:


Deploying-IT


Encrypting and Decrypting Configuration Sections

Using App Folder Path
Encrypting a Web Configuration Section:       aspnet_regiis -pef "connectionStrings" "AppPhysicalPath" -prov "RsaProtectedConfigurationProvider"
Decrypting a Web Configuration Section:      aspnet_regiis -pdf "connectionStrings" "AppPhysicalPath"

Where AppPhysicalPath Example: "C:\AppFolderName"
Using App Name
Encrypting a Web Configuration Section:       aspnet_regiis -pe "connectionStrings" -app "/SampleApplication" -prov "RsaProtectedConfigurationProvider"
Decrypting a Web Configuration Section:      aspnet_regiis -pd "connectionStrings" -app "/SampleApplication"


Removing Unnecessary HTTP Headers in IIS and ASP.NET
1.       ASP.NET Web.Config event and add the following:
<system.web>
  <httpRuntime enableVersionHeader="false" />
</system.web>

2.       MVC Application_Start event and add the following:
MvcHandler.DisableMvcResponseHeader = true;

3.       X-Powered-By:
This one is actually easily configurable straight out of the box in IIS 7.x, just jump right into the IIS configuration of the website and locate the “HTTP Response Headers” item. Remove X-Power-By.


Secure cookies

1.       HTTP only cookies:
ASP.NET Code:
Response.Cookies.Add(new HttpCookie("HttpOnlyCookie")
    {
      Value = "I can't be read by JavaScript",
      HttpOnly = true
    });

Web.Config
<httpCookies httpOnlyCookies="true" />

2.       Secure cookies:
ASP.NET Code:
Response.Cookies.Add(new HttpCookie("SecureCookie")
{
    Value = "I won't be sent by the browser over a non-secure connection",
    Secure = true
});

Web.Config:
<httpCookies requireSSL="true" />


CLICKJACKING

1.       From Global File
void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
}

2.       From IIS:
Open Internet Information Services (IIS) Manager.
In the Connections pane on the left side, expand the Sites folder and select the site that you want to protect.
Double-click the HTTP Response Headers icon in the feature list in the middle.
In the Actions pane on the right side, click Add.
In the dialog box that appears, type X-Frame-Options in the Name field and type SAMEORIGIN in the Value field.

Click OK to save your changes.

Git Commands and Using Them in Visual Studio

 Git is a widely used version control system that allows developers to manage changes to their code and collaborate with other IDE like Visu...