Thursday 28 December 2017

The basics of MS SQL (Microsoft SQL Server) & their datatype

The basics of SQL:
What are the difference between DDL, DML and DCL commands?
  1. DDL is Data Definition Language statements. 
    • CREATE - to create objects in the database 
    • ALTER - alters the structure of the database 
    • DROP - delete objects from the database
    • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed 
    • COMMENT - add comments to the data dictionary 
    • GRANT - gives user's access privileges to database 
    • REVOKE - withdraw access privileges given with the GRANT command
  2. DML is Data Manipulation Language statements. 
    • SELECT - retrieve data from the a database 
    • INSERT - insert data into a table 
    • UPDATE - updates existing data within a table 
    • DELETE - deletes all records from a table, the space for the records remain 
    • CALL - call a PL/SQL or Java subprogram 
    • EXPLAIN PLAN - explain access path to data 
    • LOCK TABLE - control concurrency
  3. DCL is Data Control Language statements.
    • COMMIT - save work done 
    • SAVEPOINT - identify a point in a transaction to which you can later roll back 
    • ROLLBACK - restore database to original since the last COMMIT
    • SET TRANSACTION - Change transaction options like what rollback segment to use

SQL Data Type
  1. Exact numerics
    • bigint 
    • numeric
    • bit
    • smallint
    • decimal
    • smallmoney
    • int
    • tinyint
    • money
  2. Approximate numerics
    • float
    • real
  3. Date and time
      • date
      • datetimeoffset
        • datetime2
        • smalldatetime
        • datetime
        • time
      1. Character strings
        • char
        • varchar
        • text
      2. Unicode character strings
        • nchar
        • nvarchar
        • ntext
      3. Binary strings
        • binary
        • varbinary
        • image
      4. Other data types
        • cursor
        • rowversion
        • hierarchyid
        • uniqueidentifier
        • sql_variant
        • xml
        • Spatial Geometry Types
        • Spatial Geography Types
        • table

      Thursday 21 December 2017

      Repeat Rows N Times According to Column Value in SQL Server

      CREATE TAblE #temp
      (
      T_Name      VARCHAR(50),
      T_Times      BIGINT
      )

      INSERT INTO #temp(T_Name,T_Times) VALUES ('ASHISH',4)
      INSERT INTO #temp(T_Name,T_Times) VALUES ('PANKAJ',3)
      INSERT INTO #temp(T_Name,T_Times) VALUES ('RUPESH',2)
      INSERT INTO #temp(T_Name,T_Times) VALUES ('MANISH',5)

      SELECT t.T_Name ,t.T_Times FROM
      (SELECT  T_Name,T_Times,CAST(('<val>'+REPLICATE(T_Name+'</val><val>',T_Times-1)
      +'</val>') AS XML )AS X FROM #temp)t CROSS APPLY t.X.nodes('/val')y(z)

      drop table #temp



      Function with no Arguments but Return Value In C

      1. /*C program to check whether a number entered by user is prime or not using function with no arguments but having return value */  
      2. #include <stdio.h>  
      3. #include <conio.h>  
      4. int input();  
      5. void main(){  
      6.     int num,i,flag = 0;  
      7.     num=input();     /* No argument is passed to input() */  
      8.     for(i=2; i<=num/2; ++i){  
      9.     if(num%i==0){  
      10.         flag = 1;  
      11.         break;  
      12.     }  
      13.     }  
      14.     if(flag == 1)  
      15.         printf("%d is not prime",num);  
      16.     else  
      17.         printf("%d is prime", num);  
      18.     getch();  
      19. }  
      20. int input(){   /* Integer value is returned from input() to calling function */  
      21.     int n;  
      22.     printf("Enter positive integer to check:\n");  
      23.     scanf("%d",&n);  
      24.     return n;  
      25. }  

      The ASCII Character Set

      Character data is represented in a computer by using standardized numeric codes which have been developed. The most widely accepted code is called the American Standard Code for Information Interchange ( ASCII). The ASCII code associates an integer value for each symbol in the character set, such as letters, digits, punctuation marks, special characters, and control characters. Some implementations use other codes for representing characters, but we will use ASCII since it is the most widely used. The ASCII characters and their decimal code values are shown in Table 4.2. Of course, the internal machine representation of characters is in equivalent binary form.


      The ASCII table has 128 characters, with values from 0 through 127. Thus, 7 bits are sufficient to represent a character in ASCII; however, most computers typically reserve 1 byte, (8 bits), for an ASCII character. One byte allows a numeric range from 0 through 255 which leaves room for growth in the size of the character set, or for a sign bit. Consequently, a character data type may optionally represent signed values; however, for now, we will assume that character data types are unsigned, i.e. positive integer values, in the range 0-127.

      Looking at the table, note that the decimal values 0 through 31, and 127, represent non-printable control characters. All other characters can be printed by the computer, i.e. displayed on the screen or printed on printers, and are called printable characters. All printable characters and many control characters can be input to the computer by typing the corresponding keys on the keyboard. The character column shows the key(s) that must be pressed. Only a single key is pressed for a printable character; however, control characters need either special keys on the keyboard or require the CTRL key pressed together with another key. In the table, a control key is shown by the symbol '136. Thus, '136A is control-A, i.e. the CTRL key kept pressed while pressing the key, A.

      Notice that the character 'A' has the code value of 65, 'B' has the value 66, and so on. The important feature is the fact that the ASCII values of letters 'A' through 'Z' are in a contiguous increasing numeric sequence. The values of the lower case letters 'a' through 'z' are also in a contiguous increasing sequence starting at the code value 97. Similarly, the digit symbol characters '0' through '9' are also in an increasing contiguous sequence starting at the code value 48. As we shall see, this feature of the ASCII code is quite useful.

      It must be emphasized that a digit symbol is a character type. Digit characters have code values that differ from their numeric equivalents: the code value of '0' is 48, that of '1' is 49, that of '2' is 50, and so forth. The table shows that the character with code value 0 is a control character, '136@, called the NULL character. Do NOT confuse it with the digit symbol '0'. Remember, a digit character and the equivalent number have different representations.

      Besides using single quotes, it is also possible to write character constants in terms of their ASCII values in a C program, using either their octal or their hexadecimal ASCII values. In writing character constants, the octal or hexadecimal value follows the escape character, , as shown in Table 4.3. At most three octal digits or at most two hexadecimal digits are needed. Note, after the escape backslash, a leading zero should not be included in writing octal or hexadecimal numbers

      Wednesday 13 December 2017

      C# Calculate Directory (Folder) & Sub Directory (Sub Folder) File Size

       public static long DirSize(DirectoryInfo d)
          {
              long size = 0;
              // Add file sizes.
              FileInfo[] fis = d.GetFiles();
              foreach (FileInfo fi in fis)
              {
                  size += fi.Length;
              }
              // Add subdirectory sizes.
              DirectoryInfo[] dis = d.GetDirectories();
              foreach (DirectoryInfo di in dis)
              {
                  size += DirSize(di);
              }
              return size;
          }



       String fldName1 = "~/" +   hfFileLocation.Value;
                  string path = Server.MapPath(fldName1);
      double fsize = 0.00;
      fsize = DirSize(new DirectoryInfo(path));
      Response.Write(fsize );
      double fsize_MB = 0.00;
       fsize_MB = fsize / (1024 * 1024);
      Response.Write("File Size in MB : "+fsize_MB );


      Tuesday 12 December 2017

      How to Integrate “No CAPTCHA reCAPTCHA” in Your Website

      Note:
      First, we need an API key, so head on over to https://www.google.com/recaptcha/admin. To gain access to this page you’ll need to be logged into a Google account. You’ll be asked to register your website, so give it a suitable name, then list domains (for example ashishsrivastava.info) where this particular reCAPTCHA will be used. Subdomains (such as blog.ashishsrivastava.info) are automatically taken into account


      Code :
      Example 1 :

      Create Class
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using Newtonsoft.Json;
      /// <summary>
      /// Summary description for ReCaptchaClass
      /// </summary>
      public class ReCaptchaClass
      {
          public static string Validate(string EncodedResponse)
          {
              var client = new System.Net.WebClient();

              string PrivateKey = "Your KEY";

              var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));

              var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptchaClass>(GoogleReply);

              return captchaResponse.Success;
          }

          [JsonProperty("success")]
          public string Success
          {
              get { return m_Success; }
              set { m_Success = value; }
          }

          private string m_Success;
          [JsonProperty("error-codes")]
          public List<string> ErrorCodes
          {
              get { return m_ErrorCodes; }
              set { m_ErrorCodes = value; }
          }


          private List<string> m_ErrorCodes;
      }

      Using webservice

      protected static string ReCaptcha_Key = "Your Key";
          protected static string ReCaptcha_Secret = "Your Secret";

          [WebMethod]
          public string VerifyCaptcha(string response)
          {
              string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + response;
              return (new WebClient()).DownloadString(url);
          }


      HTML PAGE
      JS
      <script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
      or
      <script src='https://www.google.com/recaptcha/api.js'></script>

      <div class="g-recaptcha" data-sitekey="6LfWVw8UAAAAAFioLPix8GJ4dJC83PC6V7Kb26Fd"></div>

      Validate using class

       string EncodedResponse = Request.Form["g-Recaptcha-Response"];
                 
                  bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false);

                  if (IsCaptchaValid)
                  {
      }
       else
                  {
                    /
                      ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "javascript:alert('Please verify captcha');", true);
                   
                  }

      Validate using Web Service
      using Newtonsoft.Json;

      MyService objMyService = new MyService();

       string EncodedResponse = Request.Form["g-Recaptcha-Response"];
                  String json = objMyService.VerifyCaptcha(EncodedResponse);

                  dynamic stuff = JsonConvert.DeserializeObject(json);
         if (stuff.success == "True")
      {
      }
                  else
                  {
                   
                     ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "javascript:alert('Please verify captcha');", true);
                   

                  }

      Monday 27 November 2017

      How to check your EPF balance in 6 easy steps

      Step 1

      Employees need to login the member portal by visiting the EPFO website (https://unifiedportal-mem.epfindia.gov.in/memberinterface/). You need to enter your 12 digit Activated UAN number and the password to view your account details. If you have not activated your UAN, you can do it by clicking on the tab below. Once you have entered the right credentials, it takes four days to activate your UAN.



      Step 2 
      Once you have entered into the portal, you can find all kind of online services that are available on the EPFO website. From there you can track your queries related to claim status, transferring request, which is required in case your current employer has created another UAN number to track your PF account.

      Step 3
      You can see various tabs present on the dark green ribbon above. Clicking on the ‘view’ tab will take you to visit your profile, service history, UAN card and your passbook address. This passbook address is a separate website link where you can view your PF account.



      Step 4

      To view your PF passbook, you need to visit http://www.epfindia.gov.in website. This is a different website where you can view various other details related to EPFO. You need to go to the ‘our service’ tab and under our service tab, you need to click on the ‘for employees’ link. To view the EPF contributions done by your employer every month you need to then click on the ‘member passbook’ link.




      Step 5
      Once you click on the member passbook link, you will be sent to a different tab, where you need to again enter your activated UAN and same EPFO passwords which you used for the EPFO member login portal.



      Step 6

      Once you have entered your credentials, you can visit your EPF passbook and view your PF contribution made by the company.







      The government has come up with various other benefits where they are giving special benefits to employees who had to leave their current job due to some physical incapacitation. If you want visit the office, you may even locate the nearest EPFO office through this EPFO website, you can also view the eligibility for making online claims and obtain lots more service facilities through this online portal.

      One should also know that the accumulated amount is payable on retirement, resignation or death. You can also make partial withdrawals for financing life insurance policies, acquiring a house, wedding of self or dependents, child’s education planning or any treatment of illness etc.





      Tuesday 14 November 2017

      Sunday 22 October 2017

      Distinct List Function Using SQL

      Distinct List Function Using SQL 



      CREATE FUNCTION dbo.DistinctList
      (
      @List VARCHAR(MAX),
      @Delim CHAR
      )
      RETURNS
      VARCHAR(MAX)
      AS
      BEGIN
      DECLARE @ParsedList TABLE
      (
      Item VARCHAR(MAX)
      )
      DECLARE @list1 VARCHAR(MAX), @Pos INT, @rList VARCHAR(MAX)
      SET @list = LTRIM(RTRIM(@list)) + @Delim
      SET @pos = CHARINDEX(@delim, @list, 1)
      WHILE @pos > 0
      BEGIN
      SET @list1 = LTRIM(RTRIM(LEFT(@list, @pos - 1)))
      IF @list1 <> ''
      INSERT INTO @ParsedList VALUES (CAST(@list1 AS VARCHAR(MAX)))
      SET @list = SUBSTRING(@list, @pos+1, LEN(@list))
      SET @pos = CHARINDEX(@delim, @list, 1)
      END
      SELECT @rlist = COALESCE(@rlist+',','') + item
      FROM (SELECT DISTINCT Item FROM @ParsedList) t
      RETURN @rlist
      END

      GO

      Input : SELECT dbo.DistinctList('ashish,ashish,manish',',')

      output: ashish,manish

      Thursday 28 September 2017

      Website Performance with ASP.NET - Use Cache Headers (HttpModule CacheHeader define)

      Setting Header Programatically

      You can also set the cache headers programmatically. This can be useful for generated content and allows more fine granular and flexible control of the cache headers. The example below allows clients as well as proxies to cache all responses for one hour. You can of course use different settings depending on any parameter/content/config value etc.

      using System;
      using System.Web;
      using System.Web.UI;
      using System.Web.Configuration;
      using System.Text;
      using System.Security.Cryptography;
      using System.IO;
      public class PreInitModule : IHttpModule
      {
      public void Init(HttpApplication context)
          {
           
              context.PreRequestHandlerExecute += HandlePreRequest;
          }
          private void SetDefaultCacheHeader(object sender, EventArgs eventArgs)
          {
              HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
              HttpContext.Current.Response.Cache.SetMaxAge(TimeSpan.FromSeconds(3600));
              HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddSeconds(3600));
          }
      }


      Web.config


       <system.web>

        <httpModules>
            <add name="MyPreInitModule" type="PreInitModule" />
         
          </httpModules>
       
        </system.web>

      <system.webServer>
      <modules runAllManagedModulesForAllRequests="true">
         
            <add name="MyPreInitModule" type="PreInitModule" />
          </modules>
        <staticContent>
            <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
            <mimeMap fileExtension=".otf" mimeType="application/x-font-opentype" />
            <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
            <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
           
          </staticContent>
          <caching enabled="true" enableKernelCache="true">
            <profiles>

              <add extension=".png" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".jpg" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".jpeg" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".gif" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".css" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".js" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".pdf" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".ico" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".woff2" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".eot" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
              <add extension=".ttf" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
            </profiles>
          </caching>
        </system.webServer>

      Saturday 23 September 2017

      asp.net MVC HttpModule example

      1)  First Create SessionManger class
      using System.Web;
      using System.Collections.Generic;
      namespace ManageSession
      {
          public class SessionManger
          {
             

              public static int AdminID
              {
                  get
                  {
                   
                          return (int)System.Web.HttpContext.Current.Session["AdminID"];
                   
                  }
                  set { System.Web.HttpContext.Current.Session["AdminID"] = value; }
              }
              public static int UserType
              {
                  get
                  {

                      return (int)System.Web.HttpContext.Current.Session["UserType"];

                  }
                  set { System.Web.HttpContext.Current.Session["UserType"] = value; }
              }
              public static int CompanyID
              {
                  get
                  {

                      return (int)System.Web.HttpContext.Current.Session["CompanyID"];

                  }
                  set { System.Web.HttpContext.Current.Session["CompanyID"] = value; }
              }
              public static string UserTheme
              {
                  get
                  {

                      return (string)System.Web.HttpContext.Current.Session["UserTheme"];

                  }
                  set { System.Web.HttpContext.Current.Session["UserTheme"] = value; }
              }
              public static int BranchID
              {
                  get
                  {

                      return (int)System.Web.HttpContext.Current.Session["BranchID"];

                  }
                  set { System.Web.HttpContext.Current.Session["BranchID"] = value; }
              }
          }
      }

      2) PreInitModule class 

      using System;
      using System.Web;
      using System.Web.UI;
      using System.Web.Configuration;
      using System.Text;
      using System.Security.Cryptography;
      using System.IO;

      /// <summary>
      /// Ashish Srivastava
      /// 21 Sep 2017
      /// 
      /// </summary>
      public class PreInitModule : IHttpModule
      {
          #region IHttpModule Members

          public void Dispose()
          {
              //throw new NotImplementedException();
          }

          public void Init(HttpApplication context)
          {
              context.PreRequestHandlerExecute += HandlePreRequest;
          }

          void HandlePreRequest(object sender, EventArgs e)
          {
              var page = HttpContext.Current.CurrentHandler as System.Web.Mvc.MvcHandler;
              if (page != null)
              {
                  //page.PreInit += delegate
                  //{

                      if (HttpContext.Current.Request.Path.ToLower().Contains("/admin/"))
                      {
                      if (HttpContext.Current.Session["AdminID"] != null)
                      {
                          if (HttpContext.Current.Session["CompanyID"] != null)
                          {
                              if (HttpContext.Current.Session["BranchID"] != null) return;

                              var loginPageBranch = WebConfigurationManager.AppSettings["LoginPagePath"] ?? "~/Admin/Branch";
                              if (HttpContext.Current.Request.Path.Contains(loginPageBranch.Substring(loginPageBranch.LastIndexOf("/") + 1)) == false
                                    && HttpContext.Current.Request.Path.Contains("Branch") == false
                                    && HttpContext.Current.Request.Path.Contains("BillingCompanyReport.aspx") == false
                                  && HttpContext.Current.Request.Path.Contains("UserCompanyMapping.aspx") == false
                                  && HttpContext.Current.Request.Path.Contains("AddCompany.aspx") == false
                                  && HttpContext.Current.Request.Path.Contains("AddBranch.aspx") == false
                                  && HttpContext.Current.Request.Path.Contains("InvoceHeadSettings.aspx") == false
                             //&& HttpContext.Current.Request.Path.Contains("ForgetPassword.aspx") == false

                             )
                              {
                                  HttpContext.Current.Response.Redirect(loginPageBranch, true);
                              }
                              else
                              {
                                  return;
                              }
                          }

                          var loginPageCompany = WebConfigurationManager.AppSettings["LoginPagePath"] ?? "~/Admin/Company";
                          if (HttpContext.Current.Request.Path.Contains(loginPageCompany.Substring(loginPageCompany.LastIndexOf("/") + 1)) == false
                              && HttpContext.Current.Request.Path.Contains("Company") == false
                              && HttpContext.Current.Request.Path.Contains("AddCompany.aspx") == false
                              && HttpContext.Current.Request.Path.Contains("BillingCompanyReport.aspx") == false
                              && HttpContext.Current.Request.Path.Contains("UserCompanyMapping.aspx") == false
                              && HttpContext.Current.Request.Path.Contains("AddCompany.aspx") == false
                              && HttpContext.Current.Request.Path.Contains("AddBranch.aspx") == false
                              && HttpContext.Current.Request.Path.Contains("InvoceHeadSettings.aspx") == false
                         )
                          {
                              HttpContext.Current.Response.Redirect(loginPageCompany, true);
                          }
                          else
                          {
                              return;
                          }

                      }
                      var loginPage = WebConfigurationManager.AppSettings["LoginPagePath"] ?? "~/Login?Session=Expire";

                      if (HttpContext.Current.Request.Path.Contains(loginPage.Substring(loginPage.LastIndexOf("/") + 1)) == false)
                      {
                          HttpContext.Current.Response.Redirect(loginPage, true);
                      }
                      else
                      {

                      }
                  }                
              }
          }
          #endregion     
      }
      3) Web.config
        <system.web>
      <httpModules>
            <add name="MyPreInitModule" type="PreInitModule" />
          </httpModules>
        </system.web>
       <system.webServer>
        <modules>
            <add name="MyPreInitModule" type="PreInitModule" />
          </modules>
      </system.webServer>

      Wednesday 20 September 2017

      Convert JSON String to DataTable in ASP.Net

      1. using System;
      2. using System.Collections.Generic;
      3. using System.Data;
      4. using System.Text.RegularExpressions;

      5. public class ConvertJsonStringToDataTable
      6. {
      7.    public DataTable JsonStringToDataTable(string jsonString)
      8.    {
      9.       DataTable dt = new DataTable();
      10.       string[] jsonStringArray = Regex.Split(jsonString.Replace("[""").Replace("]",""), "},{");
      11.       List<string> ColumnsName = new List<string>();
      12.       foreach (string jSA in jsonStringArray)
      13.       {
      14.          string[] jsonStringData = Regex.Split(jSA.Replace("{""").Replace("}"""),",");
      15.          foreach (string ColumnsNameData in jsonStringData)
      16.          {
      17.             try
      18.             {
      19.                int idx = ColumnsNameData.IndexOf(":");
      20.                string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"""");
      21.                if (!ColumnsName.Contains(ColumnsNameString))
      22.                {
      23.                   ColumnsName.Add(ColumnsNameString);
      24.                }
      25.             }
      26.             catch (Exception ex)
      27.             {
      28.                throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
      29.             }
      30.          }
      31.          break;
      32.       }
      33.       foreach (string AddColumnName in ColumnsName)
      34.       {
      35.          dt.Columns.Add(AddColumnName);
      36.       }
      37.       foreach (string jSA in jsonStringArray)
      38.       {
      39.          string[] RowData = Regex.Split(jSA.Replace("{""").Replace("}"""), ",");
      40.          DataRow nr = dt.NewRow();
      41.          foreach (string rowData in RowData)
      42.          {
      43.             try
      44.             {
      45.                int idx = rowData.IndexOf(":");
      46.                string RowColumns = rowData.Substring(0, idx - 1).Replace("\"""");
      47.                string RowDataString = rowData.Substring(idx + 1).Replace("\"""");
      48.                nr[RowColumns] = RowDataString;
      49.             }
      50.             catch (Exception ex)
      51.             {
      52.                continue;
      53.             }
      54.          }
      55.          dt.Rows.Add(nr);
      56.       }
      57.       return dt;
      58.    }
      59. }


      Upload valid file in C#

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