Friday, July 1, 2022

SQL query to get all column names of a table - SQL Qury

 SELECT COLUMN_NAME  
 FROM INFORMATION_SCHEMA.COLUMNS  
 WHERE TABLE_NAME = 'Your-Table-Name'  
 ORDER BY ORDINAL_POSITION  

Sunday, March 27, 2022

Validate dd/mm/yyyy on input keyup jQuery

 Format: dd/mm/yyyy

$(document).on("keyup", ".input-date-only", function () {  
   var inputVal = $(this).val();  
   let valid = /^0?$|^(?:0?[1-9]|[12]\d|3[01])(?:\/(?:(?:0$|0?[1-9]|1[012]?)(?:\/\d{0,4})?)?)?$/.test(inputVal), input = inputVal;  
   if (!valid) {  
     alert("Please enter a valid date!");  
     $(this).val(input.substring(0, input.length - 1));  
   }  
 });  

Use the below regex for checking the other formats

 Format: dd-mm-yyyy

^0?$|^(?:0?[1-9]|[12]\d|3[01])(?:-(?:(?:0$|0?[1-9]|1[012]?)(?:-\d{0,4})?)?)?$ 

 Format: mm-dd-yyyy

^0?$|^(?:0?[1-9]|1[012]?)(?:-(?:(?:0$|0?[1-9]|[12]\d|3[01])(?:-\d{0,4})?)?)?$  

 Format: yyyy-mm-dd

^\d{0,4}$|^\d{4}-0?$|^\d{4}-(?:0?[1-9]|1[012])(?:-(?:0?[1-9]?|[12]\d|3[01])?)?$ 

Tuesday, March 8, 2022

IdentityServer4 .NET Core Ajax Call not working after page is idle for several minutes #Solved

I have faced this problem while trying to implement IdentityServer4 in Microservice .net core project. I tried several codes and spend many days on this.

Finally, it's working fine. I have changed the Cookie settings in both the client-side and Identity server-side application configs.

Please try this and if anyone finds any better solutions, please let me know. Enjoy :)

Client-Side Config

 .AddCookie("Cookies", c =>  
   {  
     c.Cookie.SameSite = SameSiteMode.None;  
     c.Cookie.SecurePolicy = CookieSecurePolicy.Always;  
     c.Cookie.IsEssential = true;  
     c.SlidingExpiration = true;  
     c.ExpireTimeSpan = System.TimeSpan.FromHours(60);  
   }  

In the AddOpenIdConnect set

  options.UseTokenLifetime = false;  

IdentityServer Config

 builder.Services.Configure<CookieAuthenticationOptions>(IdentityServerConstants.DefaultCookieAuthenticationScheme, options =>  
 {  
   options.Cookie.SameSite = SameSiteMode.None;  
   options.Cookie.SecurePolicy = CookieSecurePolicy.Always;  
   options.Cookie.IsEssential = true;  
   options.SlidingExpiration = true;  
   options.ExpireTimeSpan = System.TimeSpan.FromHours(60);  
 });  

Usually, for Cookie-related problems, we don't need to adjust anything on the IdentityServer side.

But it is a little bit complex for me, that's why I have added the settings to both configs.

Monday, March 7, 2022

SocketException: An attempt was made to access a socket in a way forbidden by its access permissions.

I restarted this service: Host Network Service on windows Services program. And it worked. Open windows terminal as Admin and run the following commands one by one.

 Step 1  
 ----------------------  
 net stop hns  

 Step 2  
 ----------------------  
 net start hns  

Sunday, October 28, 2018

Search Inside a SQL Procedure

 SELECT DISTINCT  
     o.name AS Object_Name,  
     o.type_desc  
  FROM sys.sql_modules m  
     INNER JOIN  
     sys.objects o  
      ON m.object_id = o.object_id  
  WHERE m.definition Like '%YourText%'   

Tuesday, June 19, 2018

Access IIS Localhost From Another Computer


  1. Open cmd as an administrator.
  2. Allow the ports to be accessed by the firewall.
  3.  >netsh advfirewall firewall add rule name="Open Port 3000" dir=in action=allow protocol=TCP localport=3000  
    
    Here we are assuming that my project is on port 3000.
  4. Allow IIS to use your IP and machine hostnames. You can choose to use both or just one.
  5.   > netsh http add urlacl url=http://pc-hostname:3000/ user=everyone  
      > netsh http add urlacl url=http://10.0.1.10:3000/ user=everyone  
    
    Here we are assuming the IP address of my machine is 10.0.1.10
  6. Add the hostnames to your local IIS configuration.
    1. Navigate to "Documents\IISExpress\config"
    2. Open "applicationhost.config"
    3. Locate the applications you need to enable remote access for. In the case of my "RemoteAccess" project, you're looking for this:
    4.  <site name="RemoteAccess.web" id="17">  
        <application path="/" applicationPool="Clr4IntegratedAppPool">  
          <virtualDirectory path="/" physicalPath="C:\Users\Justin Walker\Documents\Visual Studio 2013\Projects\Remote Access\RemoteAccess.Web" />  
        </application>  
        <bindings>  
          <binding protocol="http" bindingInformation="*:3000:localhost" />  
        </bindings>  
       </site>  
      
    5. Add "binding" directives under "bindings." My changed configs look like this.
    6.  <site name="RemoteAccess.web" id="17">  
        <application path="/" applicationPool="Clr4IntegratedAppPool">  
          <virtualDirectory path="/" physicalPath="C:\Users\Justin Walker\Documents\Visual Studio 2013\Projects\Remote Access\RemoteAccess.Web" />  
        </application>  
        <bindings>  
          <binding protocol="http" bindingInformation="*:3000:localhost" />  
          <binding protocol="http" bindingInformation="*:3000:pc-hostname" />  
          <binding protocol="http" bindingInformation="*:3000:10.0.1.10" />  
        </bindings>  
       </site> 


Wednesday, April 11, 2018

Uncaught typeerror: cannot read property 'msie' of undefined | Solution

Solution 1


 Downloaded jquery-migrate.1.2.1.js and referenced that file in the error page  

Solution 2

Copy the code below to the page

 <script>  
 jQuery.browser = {};  
 (function () {  
 jQuery.browser.msie = false;  
 jQuery.browser.version = 0;  
 if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {  
 jQuery.browser.msie = true;  
 jQuery.browser.version = RegExp.$1;  
 }  
 })();  
 </script>  


Sunday, January 7, 2018

Encrypt and Decrypt string using SQL

Sample Code


 Declare   
 @myData nvarchar(max) = 'My data',  
 @seqKey nvarchar(20) = 'UniQKey07x@a',  
 @encryptedData varbinary(2000)  
 set @encryptedData = EncryptByPassPhrase(@seqKey, @myData)  
 print @encryptedData  
 print convert(nvarchar(max),DecryptByPassPhrase(@seqKey, @encryptedData ))--Decrypted data  

Output

 0x010000008076CB00D6FB7820D77D4B9C3768D596BA1812019E4CFCAEF9B190DAD462A3E3  
 My data  

Encrypt And Decrypt String Without Using Special Character In C#

Encrypt


 public static string Encrypt(string plainText)  
     {  
       try  
       {  
         System.Text.Encoding encoding = System.Text.Encoding.Unicode;  
         Byte[] stringBytes = encoding.GetBytes(plainText);  
         StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);  
         foreach (byte b in stringBytes)  
         {  
           sbBytes.AppendFormat("{0:X2}", b);  
         }  
         return sbBytes.ToString();  
       }  
       catch (Exception tx)  
       {  
         return "0";  
       }  
     }  

Decrypt


  public static string Decrypt(string encryptedText)  
     {  
       try  
       {  
         System.Text.Encoding encoding = System.Text.Encoding.Unicode;  
         int numberChars = encryptedText.Length;  
         byte[] bytes = new byte[numberChars / 2];  
         for (int i = 0; i < numberChars; i += 2)  
         {  
           bytes[i / 2] = Convert.ToByte(encryptedText.Substring(i, 2), 16);  
         }  
         return encoding.GetString(bytes);  
       }  
       catch (Exception ex)  
       {  
         return "0";  
       }  
     }  

Wednesday, October 18, 2017

Show all Date Time Formats in Sql Server

SQL Query
 DECLARE @i int=0  
 L1:  
 IF @i<200  
 BEGIN  
      BEGIN TRY  
           print convert(nvarchar(max),@i+0) +'. ' + convert(nvarchar(max),getdate(),@i)  
      END TRY  
      BEGIN CATCH  
      END CATCH  
      SET @i = @i + 1  
      GOTO L1  
 END  

Output
 0. Oct 19 2017 10:30AM  
 1. 10/19/17  
 2. 17.10.19  
 3. 19/10/17  
 4. 19.10.17  
 5. 19-10-17  
 6. 19 Oct 17  
 7. Oct 19, 17  
 8. 10:30:56  
 9. Oct 19 2017 10:30:56:513AM  
 10. 10-19-17  
 11. 17/10/19  
 12. 171019  
 13. 19 Oct 2017 10:30:56:513  
 14. 10:30:56:513  
 20. 2017-10-19 10:30:56  
 21. 2017-10-19 10:30:56.513  
 22. 10/19/17 10:30:56 AM  
 23. 2017-10-19  
 24. 10:30:56  
 25. 2017-10-19 10:30:56.513  
 100. Oct 19 2017 10:30AM  
 101. 10/19/2017  
 102. 2017.10.19  
 103. 19/10/2017  
 104. 19.10.2017  
 105. 19-10-2017  
 106. 19 Oct 2017  
 107. Oct 19, 2017  
 108. 10:30:56  
 109. Oct 19 2017 10:30:56:517AM  
 110. 10-19-2017  
 111. 2017/10/19  
 112. 20171019  
 113. 19 Oct 2017 10:30:56:517  
 114. 10:30:56:517  
 120. 2017-10-19 10:30:56  
 121. 2017-10-19 10:30:56.517  
 126. 2017-10-19T10:30:56.517  
 127. 2017-10-19T10:30:56.517  
 130. 29 محرم 1439 10:30:56:517AM  
 131. 29/01/1439 10:30:56:517AM  

Wednesday, July 19, 2017

Prevent default form action and do another one

Some time we need to perform an action rather than default form action. For this use the script given below.

 $('#YourformID').on('keyup keypress', function (e) {  
     var keyCode = e.keyCode || e.which;  
     if (keyCode === 13) {  
       e.preventDefault();  
       $(this).find('#YourActionButtonID').click();  
     }  
   });  

Tuesday, July 11, 2017

How to check a temporary table exists in SQL Server

Use this sql query
 IF OBJECT_ID('[Your_DB_Name..#[Temp_Table_Name]') IS NOT NULL   
 BEGIN  
      --Action--
 END  

Example
 IF OBJECT_ID('tempdb..#tempDoc') IS NOT NULL   
 BEGIN  
      Drop Table #tempDoc  
 END  


Monday, July 3, 2017

Modal popup over modal popup

Use the given jQuery code in document_ready block.
  var modal_lv = 10000;  
     $('.modal').on('shown.bs.modal', function (e) {  
       $('.modal-backdrop:last').css('zIndex', 1051 + modal_lv);  
       $(e.currentTarget).css('zIndex', 1052 + modal_lv);  
       modal_lv++  
     });  
     $('.modal').on('hidden.bs.modal', function (e) {  
       modal_lv--  
     });  

Sample

Wednesday, June 7, 2017

Function for validating email format using jQuery

 function ValidateEmail(emaliID) {  
     var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");  
     return (emaliID.match(r) == null) ? false : true;  
   }  


Function for validate dd/MM/yyyy date using jQuery

 function VaidateDate(dateValue)  
   {  
     var dateRegex = new RegExp(/^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/);  
     return dateRegex.test(dateValue);  
   }  

If function return true then it is valid else it is invalid.

Tuesday, March 14, 2017

Validating date format using java script


 // Validates that the input string is a valid date formatted as "mm/dd/yyyy"  
 function isValidDate(dateString)  
 {  
   // First check for the pattern  
   if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))  
     return false;  
   // Parse the date parts to integers  
   var parts = dateString.split("/");  
   var day = parseInt(parts[1], 10);  
   var month = parseInt(parts[0], 10);  
   var year = parseInt(parts[2], 10);  
   // Check the ranges of month and year  
   if(year < 1000 || year > 3000 || month == 0 || month > 12)  
     return false;  
   var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];  
   // Adjust for leap years  
   if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))  
     monthLength[1] = 29;  
   // Check the range of the day  
   return day > 0 && day <= monthLength[month - 1];  
 };  

Thursday, January 26, 2017

Simple encryption and decryption using key value in C#

Encryption

 public string Encrypt(string plainText)  
     {  
       try  
       {  
         string key = "abcd123xyz" + DateTime.Now.Year.ToString() + "#";  
         byte[] EncryptKey = { };  
         byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };  
         EncryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));  
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
         byte[] inputByte = Encoding.UTF8.GetBytes(plainText);  
         MemoryStream mStream = new MemoryStream();  
         CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(EncryptKey, IV), CryptoStreamMode.Write);  
         cStream.Write(inputByte, 0, inputByte.Length);  
         cStream.FlushFinalBlock();  
         return Convert.ToBase64String(mStream.ToArray());  
       }  
       catch (Exception)  
       {  
         return "0";  
       }  
     }  

Decryption

 public string Decrypt(string encryptedText)  
     {  
       try  
       {  
         string key = "abcd123xyz" + DateTime.Now.Year.ToString() + "#";           byte[] DecryptKey = { };  
         byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };  
         byte[] inputByte = new byte[encryptedText.Length];  
         DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));  
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
         inputByte = Convert.FromBase64String(encryptedText);  
         MemoryStream ms = new MemoryStream();  
         CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write);  
         cs.Write(inputByte, 0, inputByte.Length);  
         cs.FlushFinalBlock();  
         System.Text.Encoding encoding = System.Text.Encoding.UTF8;  
         return encoding.GetString(ms.ToArray());  
       }  
       catch (Exception)  
       {  
         return "0";  
       }  
     }  


Wednesday, January 25, 2017

Area registration OR Area routing in MVC C#

Sample
 public override void RegisterArea(AreaRegistrationContext context)   
     {  
       context.MapRoute(  
         "Cpanel_default",  
         "Cpanel/{controller}/{action}/{id}",  
         new { controller="Home", action = "Index", id = UrlParameter.Optional },  
         new [] {"NT.Areas.Cpanel.Controllers"}  
       );  
     }  

Manage css dynamically in razor view based on condition - MVC

Sample
  <div class="col-lg-4 col-md-3 @(app.AppPath=="#"?"disableDiv":"")">  
 Your data  
 </div>  

Redirect to an action in another area in MVC

Sample
 <a href="@Url.Action("Index", "Home",new {area="Cpanel"})">