Sunday, August 18, 2013

How to Call C# Class Library (Dll) Method in PowerBuilder 11

If you use .NET target of PB 11, you can call C# class using .NET
Assembly.

C# class dll
-------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace ClassLibrary1
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class Calc
    {
            public int Add(int x, int y)
            {
                return x + y;
            }

            public int Sub(int x, int y)
            {
                return x - y;
            }
    }
}
-------------------------------------------------------------------------------------
In the .NET Windows form target, define the dll above as a .NET
Assembly.
Now you can call the dll.

Power Builder Script
-------------------------------------------------------------------------------------
long i,j,k
i = 5
j = 4
 #IF Defined PBDOTNET Then
         ClassLibrary1.Calc l_ClassLibrary1
     l_ClassLibrary1 = create ClassLibrary1.Calc
          k =                 l_ClassLibrary1.Add( i,j)
 #END IF
 messagebox("Add( i,j)",string(k))
-------------------------------------------------------------------------------------

Saturday, August 17, 2013

Encrypt and Decrypt Password into Session Variable, Application Variable, Global Variable etc in SQL Server/Asp.net/C#

Description : Encrypt and Decrypt Password/Session Variable/Global Variable in SQL Server using ASP.NET


There are Two Method for Encrypt and Decrypt mechanism.
1) Encode and Decode Data
2) Encryption and Decryption using Algorithm
PrjSecurity.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;


namespace Musakkhir.Code
{
    public class PrjSecurity
    {
        public  string EncodePasswordToBase64(string password)
        {
            try
            {
                byte[] encData_byte = new byte[password.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Encode" + ex.Message);
            }
        }

        public string DecodeFrom64(string encodedData)
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(encodedData);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }
        /// <summary>
        /// ///////////    Musakkhir   ///////////
        /// </summary>
        /// <param name="stringToDecrypt"></param>
        /// <param name="sEncryptionKey"></param>
        /// <returns></returns>
        public string Decrypt(string stringToDecrypt, string sEncryptionKey)
        {
            byte[] key = { };
            byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
            //Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}

            byte[] inputByteArray = new byte[stringToDecrypt.Length];
            try
            {
                key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(stringToDecrypt);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                Encoding encoding = Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        //public static string Encrypt(string stringToEncrypt,
        public string Encrypt(string stringToEncrypt,   string sEncryptionKey)
        {
            byte[] key = { };
            byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
            byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)
            try
            {
                key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                return Convert.ToBase64String(ms.ToArray());
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
    }
}


USE:

Import Namespace.
using System.Security;
using System.Security.Cryptography; 
using PrjSecurity;

Create object of PrjSecurity Class file to call Encrypt and Decrypt method.
PrjSecurity s=new PrjSecurity();

Define Variable.
string EncPassword, DecPassword;

Encrypt Password which is store in session variable, in this way u can also encrypt and decrypt global variable, static variable, application variable, etc.

EncPassword = txtPassword.Text;
Session["Password"] = s.Encrypt(EncPassword, SHA512.Create().ToString());

The session variable Password which is store in session variable is encrypted by using SHA512 algorithm and it is store in EncPassword variable.
Decrypt Session Variable which is tore in Encypted format can be decrypt in string variable DecPassword in this way.

DecPassword = s.Decrypt(Session["Password"], SHA512.Create().ToString());

Wednesday, August 14, 2013

Import MS Excel Data to SQL Server Table using C#

If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow the below steps:
Step 1: Let’s take an example to import data to SQL Server table. I am going to import student information data from an MS Excel sheet to the tStudent SQL table:
Step 2: Now design a tStudent table in SQL Server
CREATE TABLE
(
STUDENT VARCHAR(64),
ROLLNO VARCHAR(16),
COURSE VARCHAR(32),
)
Your MS Excel sheet and SQL table are ready, now it’s time to write C# code to import the Excel sheet into the tStudent table.
Step 3: Add these two namespaces in your class file:
USING SYSTEM.DATA.OLEDB;
USING SYSTEM.DATA.SQLCLIENT;
Step 4: Add below method in your class file, you can call this method from any other class and pass the Excel file path:
public void importdatafromexcel(string excelfilepath)
{
    //declare variables - edit these based on your particular situation
    string ssqltable = "tdatamigrationtable";
    // make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have
    different
    string myexceldataquery = "select student,rollno,course from [sheet1$]";
    try
    {
        //create our connection strings
        string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath +
        ";extended properties=" + "\"excel 8.0;hdr=yes;\"";
        string ssqlconnectionstring = "server=DBServerName;user
        id=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";
        //execute a query to erase any previous data from our destination table
        string sclearsql = "delete from " + ssqltable;
        sqlconnection sqlconn = new sqlconnection(ssqlconnectionstring);
        sqlcommand sqlcmd = new sqlcommand(sclearsql, sqlconn);
        sqlconn.open();
        sqlcmd.executenonquery();
        sqlconn.close();
        //series of commands to bulk copy data from the excel file into our sql table
        oledbconnection oledbconn = new oledbconnection(sexcelconnectionstring);
        oledbcommand oledbcmd = new oledbcommand(myexceldataquery, oledbconn);
        oledbconn.open();
        oledbdatareader dr = oledbcmd.executereader();
        sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring);
        bulkcopy.destinationtablename = ssqltable;
        while (dr.read())
        {
            bulkcopy.writetoserver(dr);
        }
     
        oledbconn.close();
    }
    catch (exception ex)
    {
        //handle exception
    }
}
In the above function you have to pass the MS Excel file path as a parameter. If you want to import your data by providing the client access to select the Excel file and import, then you might have to use the ASP.NET File control and upload the Excel file on the server in some temp folder, then use the file path of the uploaded Excel file and pass the path in the above function. Once data import is complete then you can delete the temporary file.
The above method first deletes the existing data from the destination table, then imports the Excel data into the same table.

Thursday, August 8, 2013

Backup your SQL Server Database using ASP.NET

Description :
When User Clicks on Button, Directory is created on D drive if it is not exist else backup database is saved in that folder.

.cs Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;

namespace Backup
{
    public partial class _Default : System.Web.UI.Page
    {
        string DbName = "CBS";
        SqlConnection conStr = new SqlConnection(ConfigurationManager.ConnectionStrings["CBSConnectionString"].ConnectionString);
        DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnBackup_Click(object sender, EventArgs e)
        {
            string DestDir = "D:\\Backupdb";
            if (!System.IO.Directory.Exists(DestDir))
            {
                System.IO.Directory.CreateDirectory("D:\\Backupdb");
                MessageBox.Show("Directory is Created.");
            }
            try
            {
                conStr.Open();
                string cmdStr = "BACKUP DATABASE CBS TO DISK='"+DestDir+"\\"+DateTime.Now.ToString("ddMMyyyy_HHmmss")+".Bak'";
                SqlCommand cmd = new SqlCommand(cmdStr,conStr);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Backup is done successfully..");
            }
            catch(SqlException exc)
            {
                MessageBox.Show(exc.Message);
            }
            finally
            {
                conStr.Close();
            }
        }
    }
}

ASPX Code :

<p>Click to Backup your database :</p>
    <asp:Button ID="btnBackup" runat="server" onclick="btnBackup_Click"
        Text="Backup" />

Screen Shot:

Zoom In/Zoom Out Website Content using JavaScript

Zoom In/Zoom Out Website using JavaScript When user clicks on  "A" the website content Zooms In and When user Clicks on "a" the website content Zooms out.

JavaScript Code:

<script type="text/javascript">
    var min = 8;
    var max = 18;
    function zoominLetter() {
        var p = document.getElementsByTagName('p');
        for (i = 0; i < p.length; i++) {
            if (p[i].style.fontSize) {
                var s = parseInt(p[i].style.fontSize.replace("px", ""));
            } else {
                var s = 12;
            }
            if (s != max) {
                s += 1;
            }
            p[i].style.fontSize = s + "px"
        }
    }
    function zoomoutLetter() {
        var p = document.getElementsByTagName('p');
        for (i = 0; i < p.length; i++) {
            if (p[i].style.fontSize) {
                var s = parseInt(p[i].style.fontSize.replace("px", ""));
            } else {
                var s = 12;
            }
            if (s != min) {
                s -= 1;
            }
            p[i].style.fontSize = s + "px"
        }
    }
</script>

ASPX Code:

<a href="javascript:zoominLetter();"><b>A</b></a>
<a href="javascript:zoomoutLetter();"><b>a</b></a>
<div style="width: 400px">
   <p>Musakkhir Sayyed is a Software Engineer working in Constraint Technologies Pvt Ltd, Pune. He has been a programmer/Software Developer for past 2 years specializing in .NET/C# development. Currently, he is a Silverlight, WPF/Sharepoint developer specializing in BCS Services. </p>
   </div>
    <asp:Label ID="lblUserBrowser" runat="server"></asp:Label>

Screen Shot 1:


Custom Validator Example


JavaScript Code:

<script type="text/javascript">
    function Check(sender, e) {
        if (isNaN(e.Value))
            e.IsValid = false;
        else
            e.IsValid = true;
    }
</script>

ASPX Code :

<asp:TextBox ID="TextBox1" runat="server" Width="150"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidator1" runat="server"
        ErrorMessage="Id Should be a Number" ClientValidationFunction="Check"
        ControlToValidate="TextBox1" Display="Dynamic" ForeColor="Red"
        SetFocusOnError="True"></asp:CustomValidator>

Wednesday, August 7, 2013

Date Textbox User Control with MaskedEditExtender, MaskedEditValidator and CompareValidator

Code :

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server" MaxLength="8" Visible="true"></asp:TextBox>
<asp:MaskedEditExtender ID="TextBox1_MaskedEditExtender" runat="server" CultureAMPMPlaceholder=""
    CultureCurrencySymbolPlaceholder="" ErrorTooltipEnabled="true" CultureDateFormat=""
    CultureDatePlaceholder="" CultureDecimalPlaceholder="" CultureThousandsPlaceholder=""
    CultureTimePlaceholder="" Enabled="True" InputDirection="RightToLeft" TargetControlID="TextBox1"
    ClearTextOnInvalid="True" Mask="99/99/9999" MaskType="Date" MessageValidatorTip="true">
    </asp:MaskedEditExtender>
<asp:MaskedEditValidator ID="MaskedEditValidator1" runat="server" ControlToValidate="TextBox1"
IsValidEmpty="false" ControlExtender="TextBox1_MaskedEditExtender" ToolTip="Enter Date Between 01/01/2000 to 01/01/2099"
EmptyValueMessage="Enter Date Value" InvalidValueBlurredMessage="Date is invalid"
    MinimumValue="01/01/2000" MaximumValue="01/01/2099" MaximumValueMessage="Date must be less than 01/01/2099"
    InvalidValueMessage="Invalid Format" MinimumValueMessage="Date must be greator than 01/01/2000">
    </asp:MaskedEditValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox1"
    ErrorMessage="Enter Correct Format" Operator="DataTypeCheck" Type="Date">
    </asp:CompareValidator>



Tab Focus of textbox in asp.net using JQuery.

Description :
When user press Enter key, the Tab focus of a textbox moves to next textbox using JQuery in asp.net.

Code :
 <script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script> 
<script type="text/javascript" language="javascript"> 
  $(document).ready(function () {

        $('input:text:first').focus();

        $('input:text').bind('keydown', function (e) {

            if (e.keyCode == 13) {

                e.preventDefault();

                var nextIndex = $('input:text').index(this) + 1;

                var maxIndex = $('input:text').length;

                if (nextIndex < maxIndex) {

                    $('input:text:eq(' + nextIndex + ')').focus();
                }
            }
        });
    });
</script>

Friday, May 3, 2013

HTTP Error 500.21 - Internal Server Error Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list. pelineHandler" in its module list.

To repair this problem I ran a full silent repair of the .NET Framework 4.0.   Here's how on either a 32 bit or 64 bit computer:
  1. Click Start -> All Programs -> Accessories -> Run
  2. In the Open textbox paste in the following line (see list of all .NET Framework version install, repair and unistall command lines ):
    For silent repair on 32 bit computer with .Net Framework version 4.0.30319 use:
    %windir%\Microsoft.NET\Framework\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart
    For silent repair on 64 bit computer with .Net Framework version 4.0.30319 use:
    %windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart
  3. Click OK to start the repair
  4. After, the repair ran for a few minutes, I restarted IIS 7.5, and things began to work correctly!
 Hopefully, that will work for you...
Some people also seem to be having success correcting this error by running aspnet_regiis.exe. I initially tried this and it did not work for me, but feel free to give it a shot. (Keep in mind for the example below I have .Net Framework version 4.0.3.0319 installed on my computer, but you may need to change directory version to what is installed on your computer):  Here's how to run aspnet_regiis.exe:
  1. Run "aspnet_regiis.exe" program from command line (within Command Prompt):
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe –i
If you want to open it using the Run program, just type in "Run" in the Windows 7 search box, then use the following line below in the Open box, then click OK:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe –i
 Note if your computer is 64 bit, then I would change the line to:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe –i
Hopefully, these solutions help get you up and running and fix the IIS7 error...  Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list.

Create Textbox and its Change Event Dynamically

.aspx Code

  <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

.cs Code:

using System;
using System.Windows.Forms;

namespace Musakkhir
{
    public partial class WebForm8 : System.Web.UI.Page
    {
        System.Web.UI.WebControls.TextBox t = new System.Web.UI.WebControls.TextBox();
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            t.AutoPostBack = true;
            t.TextChanged+=new EventHandler(t_TextChanged);
        }
        protected void t_TextChanged(object sender, EventArgs e)
        {
            this.Controls.Add(t);
            t.Attributes.Add("runat", "sever");
            MessageBox.Show("New text change event");
        }
    }
}

Sunday, January 20, 2013

Encrypt Connection String in Web.config

There are two methods are available to provide security for the connection string in web.cofig.

1) RSAProtectedConfigurationProvider
2) DataProtectionConfigurationProvider

Include the namespace in class file
using System.Web.Configuration;
using System.Web.Security;
using System.Configuration;

 //If you want to use RSA Protection just replace "DataProtectionConfigurationProvider" to //"RSAProtectedConfigurationProvider"
       
        SqlConnection conStr = new SqlConnection(ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString);

protected void btnEncrypt_Click(object sender, EventArgs e)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            ConfigurationSection section = config.GetSection("connectionStrings");
            if (!section.SectionInformation.IsProtected)
            {
                section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                config.Save();
            }
        }

        protected void btnDecrypt_Click(object sender, EventArgs e)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            ConfigurationSection section = config.GetSection("connectionStrings");
            if (section.SectionInformation.IsProtected)
            {
                section.SectionInformation.UnprotectSection();
                config.Save();
            }
        }
    }


Saturday, January 19, 2013

Calculator in ASP.NET

Display Windows Calculator in ASP.NET on Button Click Event.

Include the name space in you webform and Write the code on Button Click. System.Diagnostics.Process.Start("Application Name");

Process.Start invokes the process from system32 directory.

using System.Diagnostics;

 protected void btnCalculator_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");
        }


Print Functionality on Button Click using JavaScript

<asp:Button ID="printButton" runat="server" Text="Print"             OnClientClick="javascript:window.print();" Width="70px"
            onclick="printButton_Click" />