Thursday, December 1, 2016

Sample Program to Convert String to Hex and Hex to String in CSharp (C#)

Here is the sample program to convert String to Hex and Hex to String in CSharp (C#).


String to Hex:
public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
    Byte[] stringBytes = encoding.GetBytes(input);
    StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);

    foreach (byte b in stringBytes)
    {
        sbBytes.AppendFormat("{0:X2}", b);
    }

return sbBytes.ToString();
}

Hex to String:
public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
    int numberChars = hexInput.Length;
    byte[] bytes = new byte[numberChars / 2];

    for (int i = 0; i < numberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
    }

    return encoding.GetString(bytes);
}

Sample Program to Encrypt and Decrypt string using RijndaelManaged in CSharp (C#)

Here is a class to Encrypt and Decrypt a given string using RijndaelManaged. You have to change the private variable value based on your strength requirement of the encryption.

Encryption:
public static string Encrypt(string plainText)
{
    byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
    byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
    byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
    PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
    byte[] keyBytes = password.GetBytes(keySize / 8);
    RijndaelManaged symmetricKey = new RijndaelManaged();
    symmetricKey.Mode = CipherMode.CBC;
    ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
    MemoryStream memoryStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
    cryptoStream.FlushFinalBlock();
    byte[] cipherTextBytes = memoryStream.ToArray();
    memoryStream.Close();
    cryptoStream.Close();
    string cipherText = Convert.ToBase64String(cipherTextBytes);
    return cipherText;
 }
Decryption:
public static string Decrypt(string cipherText)
{
    byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
    byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
    byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
    PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
    byte[] keyBytes = password.GetBytes(keySize / 8);
    RijndaelManaged symmetricKey = new RijndaelManaged();
    symmetricKey.Mode = CipherMode.CBC;
    ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
    MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
    CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
    byte[] plainTextBytes = new byte[cipherTextBytes.Length];
    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
    memoryStream.Close();
    cryptoStream.Close();
    string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
    return plainText;
 }
These private variables also needs to be initialized within the same class.
    private const string passPhrase = "Pas5pr@se";
    private const string saltValue = "s@1tValue";
    private const string hashAlgorithm = "MD5";
    private const int passwordIterations = 2;
    private const string initVector = "@1B2c3D4e5F6g7H8";
    private const int keySize = 256;

HttpContext.Current is null in Wcf Service

Issue:

HttpContext.Current is null in wcf service

Solution:

Set the aspNetCompatibilityEnabled is true in the Web.Config file

<system.serviceModel>
     <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>

(Solved) Error: Memory gates checking failed because the free memory (203841536 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Error: 

Memory gates checking failed because the free memory (203841536 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Solution:

  • To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.
<system.serviceModel>
    <serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0" />
</system.serviceModel>

(Solved) Error: You do not have permission to view this directory or page using the credentials you supplied (access denied due to Access Control Lists). Ask the Web server's administrator to give you access to 'C:\inetpub\wwwroot\...\Service.svc

Error:

You do not have permission to view this directory or page using the credentials you supplied (access denied due to Access Control Lists). Ask the Web server's administrator to give you access to 'C:\inetpub\wwwroot\...\Service.svc

Solution:

  • Give access permission to the "IUSR" in IIS. That should solved the problem.


Monday, August 29, 2016

(Solved) Error: Server.CreateObject Failed - Classic ASP in IIS

Error:
Server object error 'ASP 0177 : 800401f3' Server.CreateObject Failed

C:\INETPUB\WWWROOT\TestApp\AUTHENTICATION\../serverlib/global.asp, line 190

800401f3

Solution with Sample code:

  • Open the error file and go to the corresponding line (here 190)

if (!sleep.waiter) sleep.waiter = Server.CreateObject("WaitFor.Comp"); // error line
sleep.waiter.WaitForSeconds(sleepSeconds);

  • Get the Waitfor component file location.
  • Run command prompt as Administrator.
  • Execute the below command 

C:\Windows\system32> regsvr32 "C:\inetpub\wwwroot\TestApp\serverlib\components\WaitFor\waitfor.dll"

Note: WaitFor is a component used here.

Wednesday, August 24, 2016

Convert Excel file Stream to DataTable in C# .NET

Using ExcelDataReader library we can convert a file stream excel file to a DataTable. The excel file no need to be saved to the local drive. The sample code is given below.

    byte[] buffer = Convert.FromBase64String(fileData.Replace(' ', '+'));

    Stream stream = new MemoryStream(buffer);

    var result = this.ExcelStreamToDataSet(stream);
public DataSet ExcelStreamToDataSet(Stream stream)
{
    IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

    excelReader.IsFirstRowAsColumnNames = true;

    var ds = excelReader.AsDataSet();

    excelReader.Close();

    return ds;
}

Friday, July 15, 2016

(Solved) Error: Changes to the state or options of database '' cannot be made at this time. The database is in single-user mode, and a user is currently connected to it.

Error:

Changes to the state or options of database '' cannot be made at this time. The database is in single-user mode, and a user is currently connected to it.

Solution:


ALTER DATABASE [dbname] set multi_user

SELECT request_session_id FROM sys.dm_tran_locks 
WHERE resource_database_id = DB_ID('[dbname]')

KILL [session_id]

(Solved) Error: Exclusive access could not be obtained because the database is in use

Error:

Exclusive access could not be obtained because the database is in use

Solution:


USE MASTER;
ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

Friday, April 22, 2016

Avoid opening same url tab again using JavaScript

The second parameter of window.open() provides the name of the window or tab to open it in. If you use '_blank' then it will always open in a new window. If you specify a value that doesn't start with an underscore and a window or tab already exists with that name then the page will be loaded in that existing window or tab. The fourth parameter can be set to true or false to indicate how the existing history associated with that window or tab should be treated.

So here the second param I have passed is the same URL as I consider it as unique.

var url = 'http://your_url';
window.open(url, url);

Wednesday, March 2, 2016

SignOut from all opened tabs when SignOut from one window using Javascript LocalStorage events

It is one of the very important requirements in the web application development. Assume, you are opening an application in multiple browser tabs. When you do sign out in one window the authentication session will be cleared and gets signed out in that window. But all other opened window also should sign out automatically without any direct browser interaction. To do that,

keep the user's logged in state in a browser's LocalStorage. update it when you logged in or logged out. Utilize the LocalStorage events to track the status and do a refresh.

But How..? you can do it using Timer. But using local storage events it can be done without any client-side overhead. The below code will do that for you.
Initialize the below LocalStorage 'storage' event listener in the application's common load method.
window.addEventListener('storage', this.storageChange, false);

When you first Sign In, update the local storage variable isLoggedIn value to 'true'
localStorage.setItem('isLoggedIn', true);

when you sign out update the local storage variable isLoggedIn value to 'false'

and the callback method will have the logic to refresh the page based on the condition. That is, it will keep on checking the isLoggedIn value is 'false'  whenever you update the LocalStorage.
function storageChange(event) {

    if (event.key == 'isLoggedIn' && event.newValue == 'false') {

        window.location.reload();

    }

},

Wednesday, February 3, 2016

Remove HTML tags from string using JavaScript

I encountered a problem in Firefox that it doesn't support InnerText when I try to extract only text from an HTML.
    document.getElementById("mainDiv").InnerText
It works fine in chrome. So tried to remove the HTML tags from the InnerHTML string. Below is the solution for that.

    var html = document.getElementById("mainDiv");

    var text = html.replace(/<\S[^><]*>/g, '');

Setting up SMTP on IIS 7 to send mail from pickup directory

1. Start -> Administrative Tools -> Server manager

2. Go to Features, select "add features", Tick the "SMTP Server" (if it is not already installed), choose to install the required "Remote Server Administration Toos"

3. Go to Servies, Check to confirm that "Simple Mail Transfer Protocol (SMTP)" service is running, if not Start the service.



4. Start -> Administrative Tools -> Internet Information Services(iis) 6.0

5. Make sure that SMTP Virtual Server server is running, if not, right click, then choose "start"

6. Open SMTP Virtual Server properties by right clicking it.

7. On General tab, Set IP address of the Web server instead of "All Unassigned".

8. In Access tab, click on Relay button, this will open Relay Restrictions dialog.

9. In relay computers list, add the loopback IP address i.e 127.0.0.1 and IP address of the Web server, so that they can pass/relay emails through the SMTP server.

10. In IIS7,  go to website, double click "SMTP E-mail", Click on "Deliver e-mail to SMTP server", check the "Use localhost" checkmark

11. Your code should be like,

using (MailMessage message = new MailMessage())
{
    message.Subject = this.Subject;
    message.Body = this.Body;
    message.IsBodyHtml = this.BodyIsHtml;
    message.From = this.From;

    foreach (MailAddress address in this.To) message.To.Add(address);
    foreach (MailAddress address in this.CC) message.CC.Add(address);
    if (this.Bcc != null) message.Bcc.Add(this.Bcc);

    foreach (Attachment attachment in this.Attachments) message.Attachments.Add(attachment);

    SmtpClient smtp = new SmtpClient();
    smtp.Send(message);
}

12. And in Web.Config,

<system.net>
  <!-- Mail settings -->
  <mailSettings>
    <smtp deliveryMethod="SpecifiedPickupDirectory">
      <specifiedPickupDirectory pickupDirectoryLocation="C:\inetpub\mailroot\Pickup"/>
    </smtp>
  </mailSettings>
</system.net>

The above steps could solve the following common error you may encounter,
  • "Mailbox unavailable. The server response was: 5.7.1 Unable to relay for"