Wednesday, 28 July 2021

Nomenclature Rules

Capitalization Rules

  1. The PascalCasing convention, used for all identifiers except parameter names, capitalizes the first character of each word (including acronyms over two letters in length), as shown in the following examples:
                PropertyDescriptor HtmlTag

                DO use PascalCasing for

  • Namespace
  • Type
  • Interface
  • Method
  • Property
  • Event
  • Field
  • Enum value

  1.  The camelCasing convention, used only for parameter names, capitalizes the first character of each word except the first word, as shown in the following examples. As the example also shows, two-letter acronyms that begin a camel-cased identifier are both lowercase.

        propertyDescriptor ioStream htmlTag

        DO use camelCasing for parameter names.

Case Sensitivity

DO NOT assume that all programming languages are case sensitive. They are not. Names cannot differ by case alone.

Word Choice

  1. DO choose easily readable identifier names.
    For example, a property named HorizontalAlignment is more English-readable than AlignmentHorizontal.
  2.  DO NOT use underscores, hyphens, or any other nonalphanumeric characters.
  3. DO NOT use Hungarian notation.
  4.  AVOID using identifiers that conflict with keywords of widely used programming languages.


 Using Abbreviations and acronyms

  1. DO NOT use abbreviations or contractions as part of identifier names.
    For example, use GetWindow rather than GetWin.
  2. X DO NOT use any acronyms that are not widely accepted, and even if they are, only when necessary.

Avoid Language Specific Names

  1. DO use semantically interesting names rather than language-specific keywords for type names.
    For example, GetLength is a better name than GetInt.
  2. DO use a generic CLR type name, rather than a language-specific name, in the rare cases when an identifier has no semantic meaning beyond its type.
Names of Classes, Structs, and Interfaces
  1. DO name classes and structs with nouns or noun phrases, using PascalCasing.
  2. DO name interfaces with adjective phrases, or occasionally with nouns or noun phrases.
  3. DO NOT give class names a prefix (e.g., "C").
  4. CONSIDER ending the name of derived classes with the name of the base class.
  5. DO prefix interface names with the letter I, to indicate that the type is an interface.
  6. DO ensure that the names differ only by the "I" prefix on the interface name when you are defining a class–interface pair where the class is a standard implementation of the interface.

Monday, 19 July 2021

LDAP integration

LDAP stands for Lightweight Directory Access Protocol, and allows usage of single user account directory to login to various applications. LDAP integration allows your knowledge base instance to use your existing LDAP server as the master source of user data. 

C# Code


[Route("LDAP/{UserName}/{Password}")]
        [HttpGet]
        public HttpResponseMessage LDAPDetails(string UserName = "", string Password = "")
        {
            try
            {
                var jsonString = "";
                string adServer = ConfigurationManager.AppSettings["Server"].ToString();  //"192.168.5.10";
                string adDomain = ConfigurationManager.AppSettings["Domain"].ToString(); //"headoffice.ashishsrivastava.co.in";
                string adUsername = UserName;
                string password = Password;
                string[] dc = adDomain.Split('.');
                string dcAdDomain = string.Empty;

                foreach (string item in dc)
                {
                    if (dc[dc.Length - 1].Equals(item))
                        dcAdDomain = dcAdDomain + "DC=" + item;
                    else
                        dcAdDomain = dcAdDomain + "DC=" + item + ",";
                }

                //DirectoryEntry de = new DirectoryEntry("LDAP://" + adServer + "/CN=Users," + dcAdDomain, adUsername, password);
                DirectoryEntry de = new DirectoryEntry("LDAP://" + adServer + dcAdDomain, adUsername, password);

                DirectorySearcher ds = new DirectorySearcher(de);

                ds.SearchScope = SearchScope.Subtree;

                //ds.Filter = "(&(objectClass=User)(sAMAccountName=" + UserName + "))";
                ds.Filter = "(&(objectClass=User))";

   if (ds.FindOne() != null)
   {
   jsonString = "{ "
   + JsonConvert.SerializeObject("code", Formatting.Indented) + ":" + JsonConvert.SerializeObject("-200", Formatting.Indented)
                                                   + ","
                           + JsonConvert.SerializeObject("Response", Formatting.Indented) + ":" + JsonConvert.SerializeObject("User Login Succesfully!", Formatting.Indented) + " }";
                    var response = Request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                    return response;
                }
                else
                {
                    jsonString = "{ "
                                 + JsonConvert.SerializeObject("code", Formatting.Indented) + ":" + JsonConvert.SerializeObject("-403", Formatting.Indented)
                                                      + ","
                              + JsonConvert.SerializeObject("Response", Formatting.Indented) + ":" + JsonConvert.SerializeObject("The user name or password is incorrect!" + ds.ToString(), Formatting.Indented) + " }";
                    var response = Request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                    return response;
                }
            }
            catch (Exception ex)
            {
                string jsonString;
                if (ex.ToString().Contains("The user name or password is incorrect"))
                {
                    jsonString = "{ "
                                + JsonConvert.SerializeObject("code", Formatting.Indented) + ":" + JsonConvert.SerializeObject("-403", Formatting.Indented)
                                                     + ","
                             + JsonConvert.SerializeObject("Response", Formatting.Indented) + ":" + JsonConvert.SerializeObject("The user name or password is incorrect", Formatting.Indented) + " }";
                }
                else
                {
                    jsonString = "{ "
                                + JsonConvert.SerializeObject("code", Formatting.Indented) + ":" + JsonConvert.SerializeObject("-500", Formatting.Indented)
                                                     + ","
                             + JsonConvert.SerializeObject("Response", Formatting.Indented) + ":" + JsonConvert.SerializeObject(ex.ToString(), Formatting.Indented) + " }";
                }

                var response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                return response;
            }
        }

Monday, 14 June 2021

Azure Active Directory single sign-on SSO (SAML Login)

 Step 1:  Open URL: https://portal.azure.com/#home



Step2 : Click Manage Azure Active Director


Step3: Click Enterprise Application

Step 4: New Application


Step 5: You're in the new and improved app gallery experience. Click here to switch back to the legacy app gallery experience.


Step 6: Click non-gallery application


Step 7: Put Application Name and Click ADD

Step 8: Click SSOLogin ( Application Name)
Step 9: Set UP Single sign on
Step 10: 



Step 11: put Entity ID & Assertion Consumer Service URL then click Save.

Step 12: Download Certificate & Metadata XML


Step 13:  Open Visual Studio


Step 14: Click Project
 
Step 15: put certificate file in APP_Data Folder
 
Step 16:  Manage Nuget Package 



Step 17: Browser Search Package : AS.SAMLClient then Click Install

Step 18: Add Default.aspx Page

Step 19: Web.config add AppSetting: 
<appSettings>

    <add key="SmCertificateFile" value="~/App_Data/Certicate.cer"/> // 
    <add key="SSOLoginURL" value="Login URL"/>
    <add key="SSOLogOutURL" value="Logout URL"/>
    <add key="ReturnURL" value="Return URL"/>
    <add key="Issuer" value="Application ID"/>
  </appSettings>




step 20: Default .aspx Code:

 
using System;
using System.Configuration;
 protected void Page_Load(object sender, EventArgs e)
        {
            AccountSettings accountSettings = new AccountSettings
            {
                idp_sso_target_url = ConfigurationManager.AppSettings["SSOLoginURL"]
            };
            string certificatePath = ConfigurationManager.AppSettings["SmCertificateFile"];
            accountSettings.smCertificatePath = Server.MapPath(certificatePath);
            try
            {
                if (Request.Form["SAMLResponse"] == null)
                {
                    AppSettings appSettings = new AppSettings();
                    appSettings.assertionConsumerServiceUrl = ConfigurationManager.AppSettings["ReturnURL"];
                    appSettings.issuer = ConfigurationManager.AppSettings["Issuer"];
                    AS.SAMLClient.Saml.AuthRequest req = new AS.SAMLClient.Saml.AuthRequest(appSettings, accountSettings);
                    Response.Redirect(accountSettings.idp_sso_target_url + "?SAMLRequest=" + System.Web.HttpUtility.UrlEncode(req.GetRequest(AS.SAMLClient.Saml.AuthRequest.AuthRequestFormat.Base64)));
                }
                else
                {
                    AS.SAMLClient.Saml.Response samlResponse = new AS.SAMLClient.Saml.Response(accountSettings);
                    samlResponse.LoadXmlFromBase64(Request.Form["SAMLResponse"]);

                    var response = samlResponse.getAllAttributes();
                    foreach (var assert in response)
                    {
                        Response.Write("<b>" + assert.Key + "</b>:" + assert.Value + "<br>");
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }















Saturday, 6 February 2021

List table triggers in SQL Server database

 select schema_name(tab.schema_id) + '.' + tab.name as [table],
    trig.name as trigger_name,
    case when is_instead_of_trigger = 1 then 'Instead of'
        else 'After' end as [activation],
    (case when objectproperty(trig.object_id, 'ExecIsUpdateTrigger') = 1 
            then 'Update ' else '' end
    + case when objectproperty(trig.object_id, 'ExecIsDeleteTrigger') = 1 
            then 'Delete ' else '' end
    + case when objectproperty(trig.object_id, 'ExecIsInsertTrigger') = 1 
            then 'Insert ' else '' end
    ) as [event],
    case when trig.[type] = 'TA' then 'Assembly (CLR) trigger'
        when trig.[type] = 'TR' then 'SQL trigger' 
        else '' end as [type],
    case when is_disabled = 1 then 'Disabled'
        else 'Active' end as [status],
    object_definition(trig.object_id) as [definition]
from sys.triggers trig
    inner join sys.objects tab
        on trig.parent_id = tab.object_id
order by schema_name(tab.schema_id) + '.' + tab.name, trig.name;

Saturday, 16 January 2021

Install windows service command line with different name

Install windows service command line with different name

Install Service
SC create MyService binPath= "MyService.exe" DisplayName= "MyService"  

Stop Service
SC STOP MyService

Delete Service
SC DELETE MyService

Tuesday, 5 January 2021

SSRS export to excel/Pdf in console application in C#

SSRS (SQL Server Reporting Services) export to excel in console application in C#


Namespace:

using RestSharp;
using RestSharp.Authenticators;
using System;
using System.IO;


   private static void GenerateReport(string strReportPath,string _parameters, string FileName, string FileType = "Excel")
        {
            try
            {
                string strReportPath = strReportPath;//"UserDetails"
                //string FileType = "Excel";
                string URL = ConfigurationManager.AppSettings["ReportServerPath"].ToString() + "?" + strReportPath + "&rs:Command=Render&rs:Format=" + FileType + _parameters;
 
                var client = new RestClient(URL);                
                client.Authenticator = new NtlmAuthenticator(ConfigurationManager.AppSettings["ReportUser"].ToString(), ConfigurationManager.AppSettings["ReportPwd"].ToString());
                var request = new RestRequest(Method.GET);
                Byte[] FileByte = client.DownloadData(request);
 
                ByteToFile(FileName, FileByte, FileType);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        static void ByteToFile(string FileName, Byte[] bytes, string FileType)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Data";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = AppDomain.CurrentDomain.BaseDirectory + "\\Data\\" + System.DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if (FileType == "Excel")
            {
                FileName += ".xls";
            }
            else
            {
                FileName += ".pdf";
            }
            File.WriteAllBytes(path + "\\"+ FileName, bytes);
        }

Excel Export Example:

GenerateReport("UserDetails", "&From=11-Aug-2020&UpTo=01-Jan-2021", "UserDetails","Excel');

PDF Export Example:

GenerateReport("UserDetails", "&From=11-Aug-2020&UpTo=01-Jan-2021", "UserDetails","Pdf');

Monday, 9 November 2020

Try cleaning-up your local repository with

 Try cleaning-up your local repository with:

$ git gc --prune=now

$ git remote prune origin



git diff --name-only "@{3 days ago}" "@{2 days ago}"

Upload valid file in C#

    protected bool CheckFileExtandLength(HttpPostedFile HtmlDocFile)     {         try         {             Dictionary<string, byte[]...