Wednesday, August 1, 2018

Sample C# program to get all possible pairs in a list

This is a sample C# program to get possible pairs from a list of integer values. Duplicate and reverse pair values would be discarded in the program.
using System;
using System.Collections.Generic;

namespace PairFromList
{
    class Program
    {
        static void Main(string[] args)
        {
            var items = new List<int>() { 1, 2, 3, 4, 5 };
         
            for (var i = 0; i < items.Count - 1; i++)
            {
                for (var j = i + 1; j < items.Count; j++)
                {
                    Console.WriteLine(items[i] + "-" + items[j]);
                }
            }

            Console.Read();
        }
    }
}
Output :
1-2
1-3
1-4
1-5
2-3
2-4
2-5
3-4
3-5
4-5

Saturday, June 9, 2018

Add Authorization Header Textbox in Swagger UI for Web API Basic Authentication

I wanted to test the Web API methods using Swagger UI. The Web API has Basic authentication enabled. For each request I need to pass the username and password in the format of base64 encoded. But by default the Swagger UI doesn't have any textbox to accept Authorization credentials parameters. To enable it I had to use the below code in SwaggerConfig.cs file. It should be available inside project's App_Start folder.
internal class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();

operation.parameters.Add(new Parameter
{
name = "Authorization",
@in = "header",
type = "string",
description = "Authorization Header",
required = true
});
}
}
Then add the below code inside the ConfigureSwagger(SwaggerDocsConfig config) method to register it.
private static void ConfigureSwagger(SwaggerDocsConfig config)
{
// existing code
// ...
// ...
config.OperationFilter<AddRequiredHeaderParameter>();
}

Sunday, May 27, 2018

How to get a value from Active Directory using C# DirectoryEntry Class

Here is a sample C# program to get email id from active directory by username using DirectorySearcher class.
using System.DirectoryServices;
public string GetEmailIdFromActiveDirectory(string userName)
{

 var emailId = string.Empty;

 string activeDirectory_LDAP = "LDAP://server";

 string activeDirectory_User = "ad_username";

 string activeDirectory_Password = "ad_password";

 var directoryEntry = new DirectoryEntry(activeDirectory_LDAP, activeDirectory_User, activeDirectory_Password) { AuthenticationType = AuthenticationTypes.Secure };

 var directorySearcher = new DirectorySearcher(directoryEntry);

 directorySearcher.Filter = "sAMAccountName=" + userName;

 directorySearcher.SearchScope = SearchScope.Subtree;



 SearchResult searchResult = directorySearcher.FindOne();

 if (searchResult != null)

 {

  emailId = searchResult.GetDirectoryEntry().Properties["email"].Value.ToString();

 }



 return emailId;

}