Tuesday, December 31, 2013

Convert a CSV file to DataTable in C#

Here is a simple code to read CSV file and convert it to a DataTable using CSharp (C#). String enclosed with double quotes will not break the convertion process. In my previous post I have converted a DataTable to CSV with it's header. Check my previous post Click Here. So I have taken the first line in CSV as DataTable column headers. C# Code:


 public static DataTable ConvertCSVtoDataTable(string strFilePath)
 {
            StreamReader sr = new StreamReader(strFilePath);
            string[] headers = sr.ReadLine().Split(','); 
            DataTable dt = new DataTable();
            foreach (string header in headers)
            {
                dt.Columns.Add(header);
            }
            while (!sr.EndOfStream)
            {
                string[] rows = Regex.Split(sr.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
                DataRow dr = dt.NewRow();
                for (int i = 0; i < headers.Length; i++)
                {
                    dr[i] = rows[i];
                }
                dt.Rows.Add(dr);
            }
            return dt;
 } 

Call the ConvertCSVtoDataTable function like below by passing path of the CSV file.
static void Main(string[] args)
{
      string filepath = "d://ConvertedFile.csv";
      DataTable res = ConvertCSVtoDataTable(filepath);
}

Monday, December 30, 2013

Print HTML Div content using JavaScript

Well it's very easy to implement the print functionality using JavaScript. I have provided two kind of code. Try it.

JavaScript Code 1:
function PrintFunction1(divId) {
    var divElements = document.getElementById(divId).innerHTML;
    var oldPage = document.body.innerHTML;
    document.body.innerHTML =  "<html><head><title></title></head><body>" +  divElements + "</body>";
    window.print();
    document.body.innerHTML = oldPage;
}
JavaScript Code 2:
function PrintFunction2(divId)
{
    var DocumentContainer = document.getElementById(divId);
    var WindowObject = window.open('', "PrintWindow", "width=800,height=600,top=45,left=45,toolbars=no,scrollbars=yes,status=no,resizable=yes");
    WindowObject.document.writeln(DocumentContainer.innerHTML);
    WindowObject.document.close();
    WindowObject.focus();
    WindowObject.print();
    WindowObject.close();
}

HTML Code:

<a href="#" onclick="javascript:PrintFunction1('DivToPrint')">Print</a>
<div id="DivToPrint">
// --------------
// -------------
//Contents to be print
//---------------
// -------------
</div>

(Solved) Error: Object doesn't support property or method 'querySelectorAll' in IE 7

I fixed this issue using the JQuery reference and JQuery selector $. Just replace the document.querySelectorAll with $. and refer the JQuery api in the html body tag.
Javascript Error code in IE 7:

var sliders = document.querySelectorAll('.slider');

Javascript Error Solution:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
var sliders = $('.slider');

Project Euler Solution using C#: Problem 3: Largest Prime Factor

Problem:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My Solution:


static void Main(string[] args)
{
            const long constantInput = 600851475143;
            long input = constantInput;
            long divider = 2;
            long multiplyList = 1;
            bool largestPrimeFound = false;
            while (largestPrimeFound == false)
            {
                if (input % divider == 0)
                {
                    long val = input / divider;
                    input = val;
                    Console.WriteLine(divider);
                    multiplyList *= divider;
                    if (multiplyList == constantInput)
                    {
                        Console.WriteLine("The largest prime factor for the number " + constantInput + " is : " + divider);
                        largestPrimeFound = true;
                    }
                }
                else
                {
                    divider += 1;
                }
            }
            Console.ReadLine();
 }
Note: You can simplifies the coding :)

Tuesday, December 17, 2013

Call JavaScript function from Silverlight Code behind

Here is a very simple code to display an Javascript alert from Silverlight code behind.
Silverlight Code behind C#:

private void Button_Click(object sender, RoutedEventArgs e)
{
      HtmlPage.Window.Invoke("showAlert", "Hello!");
}

JavaScript:

function showAlert(message) 
{
    alert(message);
}

Wednesday, December 11, 2013

(Solved) Error: HTTP Error 404.3 - Not Found in IIS 7.5

Solution: 
  • Got to Control Panel -> Programs and Features -> Turn Windows features on or off
  • A popup window will be displayed
  • Navigate through the tree view Internet Information Services -> World Wide Web Services -> Application Development Features
  • Here check the ASP.NET , .NET Extensibility, ISAPI Extensions, ISAPI Filters checkboxes
  • Click OK
  • Go to Visual Studio Command prompt
  • Run the command : %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

(Solved) Error: HTTP Error 500.19 – Internal Server Error in IIS 7.5

Solution: 
  • Just check out the the Microsoft kb articles Click Here 
  • If you still can't find the solution just comment the web.config lines that's showing error.
  • It should work.


Project Euler Solution using C#: Problem 2: Even Fibonacci Numbers

Problem:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
My Solution:


      static void Main(string[] args)         {             int val1 = 1;             int val2 = 2;             Int64 evenTerms = 2;             while (val2 < 4000000)             {                 int temp = val1;                 val1 = val2;                 val2 = temp + val2;                 if (val2 % 2 == 0)                 {                     evenTerms += val2;                 }             }             Console.WriteLine(evenTerms);             Console.ReadLine();         }
Note: You can simplifies the coding :)

Monday, December 9, 2013

Project Euler Solution using C#: Problem 1: Multiples of 3 and 5

Problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
My Solution:
       static void Main(string[] args)
        {
            int sumOfMultiples = 0;
            for (int i = 1; i < 1000; i++)
            {
                if (i % 3 == 0 || i % 5 == 0)
                {
                    sumOfMultiples += i;
                }
            }
            Console.Write("The Sum of Multiples of 3 or 5 below 1000 is :");
            Console.Write(sumOfMultiples);
            Console.ReadLine();
        }

Note: You can simplifies the coding :)

Thursday, December 5, 2013

Expression Tree sample to build Dynamic queries to query List<> with Sorting in C#

Here is a Expression Tree sample to build Dynamic queries to query List<> with Sorting in C#
C# Code:

    static void Main(string[] args)
    {
        IQueryable<Country> queryableData = GetCountries().AsQueryable();
        ParameterExpression pe = Expression.Parameter(typeof(Country));
        MemberExpression me = Expression.PropertyOrField(pe, "Id");
        MethodCallExpression orderByCallExpression = Expression.Call(
              typeof(Queryable),
              "OrderByDescending",
              new Type[] { queryableData.ElementType, typeof(Int32) },
              queryableData.Expression,
              Expression.Lambda<Func<Country, Int32>>(me, pe));
        IQueryable<Country> results = queryableData.Provider.CreateQuery<Country>(orderByCallExpression);
        foreach (var item in results)
        {
            Console.Write(item.Id);
            Console.Write(" : ");
            Console.WriteLine(item.Name);
        }
        Console.ReadLine();
    }

    public static List<Country> GetCountries()
    {
        // To get the country list in c# check my previous post Click Here
        // i have added a Id property to the above link sample to make some condition work in this post
    }
    class Country
    {
        public Int32 Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
    }
Reference: MSDN 

Expression Tree sample to build Dynamic queries to query List<> with Where condition in C#

Here is a sample program to build Dynamic queries to query List<> with Where condition
C# Code:

static void Main(string[] args)
{
    IQueryable<Country> queryableData = GetCountries().AsQueryable();
    ParameterExpression pe = Expression.Parameter(typeof(Country));
    MemberExpression me = Expression.PropertyOrField(pe, "Id");
    ConstantExpression cex = Expression.Constant(10, typeof(int));
    BinaryExpression be = Expression.LessThan(me, cex);
    MethodCallExpression whereCallExpression = Expression.Call(
  typeof(Queryable),
  "Where",
          new Type[] { queryableData.ElementType },
          queryableData.Expression,
          Expression.Lambda<Func<Country, bool>>(be, pe));
   IQueryable<Country> results = queryableData.Provider.CreateQuery<Country>(whereCallExpression);
    foreach (var item in results)
    {
        Console.Write(item.Id);
        Console.Write(" : ");
        Console.WriteLine(item.Name);
    }
    Console.ReadLine();
}

public static List<Country> GetCountries()
{
    // To get the country list in c# check my previous post Click Here 
    // i have added a Id property to the above link sample to make some condition work in this post
}

class Country
{
    public Int32 Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

Reference: MSDN

Sample C# program to find Happy or Sad numbers

Here is a sample C# program to find the given number is Happy or Sad.

What is Happy or Sad Numbers?

Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are Sad numbers.

Example:

7 is a happy number: 7->49->97->130->10->1.
22 is NOT a happy number: 22->8->64->52->29->85->89->145->42->20->4->16->37->58->89
Code:
using System;
using System.Collections.Generic;

namespace HappyNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine();
                Console.WriteLine("Enter a Number : ");
                string num = Console.ReadLine();
                Console.WriteLine();
                HappyOrSad hs = new HappyOrSad();
                if (hs.IsEqulOne(num))
                {
                    Console.WriteLine();
                    Console.WriteLine("Happy :) ");
                    Console.WriteLine();
                    Console.WriteLine("----------------------");
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine("Sad :( ");
                    Console.WriteLine();
                    Console.WriteLine("----------------------");
                }
            }
        }
    }

    class HappyOrSad
    {
        public bool IsEqulOne(string numbr)
        {
            bool isOne = false;
            List<int> al = new List<int>();
            while (isOne == false)
            {
                int val = 0;
                char[] numArr = numbr.ToCharArray();
                foreach (char n in numArr)
                {
                    int nVal = Int32.Parse(n.ToString());
                    val += (nVal * nVal);
                }
                if (val == 1)
                {
                    al.Add(val);
                    isOne = true;
                    break;
                }
                else
                {
                    if (al != null)
                    {
                        if (al.Contains(val))
                        {
                            al.Add(val);
                            break;
                        }
                        else
                        {
                            al.Add(val);
                        }
                    }
                }
                numbr = val.ToString();
            }
            foreach (var item in al)
            {
                Console.Write(item + " -> ");
            }
            return isOne;
        }
    }
}

Sunday, December 1, 2013

Get the list of country code and names in c#

Here is a simple Linq code to retrive the list of country code and names
C# code:

public IEnumerable<Country> GetCountries()
{
    var countryList = from r in
                      from ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures)
                      select new RegionInfo(ci.LCID)
                      group r by r.TwoLetterISORegionName into g
                      select new Country
                      {
                          Code = g.Key,
                          Name = g.First().DisplayName
                      };
    return countryList;
}
Also you need to add the below class
class Country
{
        public string Code { get; set; }
        public string Name { get; set; }
}

Monday, June 24, 2013

Salesforce - Pass parameter value from one page to another page

Here i have provided a sample to understand how to pass parameter value from one page to another and retrieve it. I have used two pages named Books and SelectedBooks. Books page has a PageBlockTable it dispalyes only book names from the Book_c custom object. The book names are displayed as links using <apex:CommandLink>. When a user click the link the first page Book is navigate to second page SelectedBook with the parameter value that is passed using <apex:param>. The Second page then retrieves the parameter value and displays the book details in a PageBlockTable
Design code for Books page:

By default the PageBlockTable displays its value as OutputLabel but we need to click the value for navigation purpose. So here i used <apex:commandLink> to convert it as Link. Book name is passed as parameter using <apex:param>

<apex:page controller="BooksController">  
   <apex:form >  
   <apex:sectionHeader subtitle="All Books" title="Books"/>  
      <apex:pageBlock >  
       <apex:pageBlockTable value="{!allbooks}" var="a">  
           <apex:column headervalue="Name">  
                 <apex:commandLink value="{!a.Name}" action="/apex/SelectedBook?id={!a.Name}">  
                 <apex:param name="id" value="{!a.Name}"/>  
                 </apex:commandLink>  
           </apex:column>  
             </apex:pageBlockTable>  
        </apex:pageBlock>  
   </apex:form>  
 </apex:page>  

Apex Code for Books page controller:

Here the getAllBooks fuction retrive the values from the Book__c custom objects and bind it to the PageBlockTable

 public class BooksController
 {  
      public List<Book__c> allbooks;   
      public List<Book__c> getAllBooks()  
      {  
           if(allbooks==null)  
           {  
                allbooks=[SELECT Name,Book_Author__c,Book_ISBN__c from Book__c];  
           }  
      return allbooks;  
      }  
 }  

Apex Code for SelectedBook page controller:

Here in the constructor the parameter value is retrieved using its name. Using that value the getSbook function gets the specific book details and bind it to the PageBlockTable.

 public class SelectedBookController 
 {  
      public String selectedName {get;set;}  
      public Book__c sbook;  
      public SelectedBookController()  
      {  
           sbook=new Book__c();  
           selectedName = ApexPages.currentPage().getParameters().get('id');  
      }  
       
      public Book__c getSbook()  
      {  
           sbook=[Select Name,Book_ISBN__c,Book_Author__c from Book__c where Name=:selectedName];  
           return sbook;  
      } 
 } 

Design code for SelectedBook page:

<apex:page controller="SelectedBookController">  
 <apex:form >  
      <apex:pageBlock >  
           <apex:pageBlockTable value="{!sbook}" var="b">  
                <apex:column value="{!b.Name}"/>  
                <apex:column value="{!b.Book_Author__c }"/>  
               <apex:column value="{!b.Book_ISBN__c}"/>  
             </apex:pageBlockTable>  
      </apex:pageBlock>  
 </apex:form>  
 </apex:page>  

Thursday, June 20, 2013

Salesforce - Insert data into Custom object using Apex

To insert data to Custom object using Apex just understand the below code. This is the basic for all other complex apex programming. Here in the Save() function the data you have enter in the text box will be saved. After inserting the data i am refreshing the page to clear the values in the text boxes. You han find the code in that function.
Apex Design Code:
 <apex:page controller="AddUserController">  
   <apex:form >  
     <apex:sectionHeader subtitle="All Books" title="Books" />  
     <apex:pageBlock >  
       <apex:PageBlockButtons >  
         <apex:commandButton action="{!Save}" value="Save"/>  
       </apex:PageBlockButtons>  
       <apex:pageBlockSection >  
         <apex:InputField value="{!users.Name}"/><br/>  
         <apex:InputField value="{!users.Age}" /><br/>  
         <apex:InputField value="{!users.Class}" /><br/>  
       </apex:pageBlockSection>  
   </apex:pageBlock>  
   </apex:form>  
 </apex:page>  

Apex Controller Code:
public class AddUserController  
 {  
   public User__c users;  
   public AddUserController()  
   {  
     users=new User__c();  
   }  
   public User__c getUsers()  
   {  
     return users;  
   }  
   public PageReference Save()  
   {  
     try  
     {  
       insert(users);  
       PageReference pagr= Page.UsersPage;  
       pagr.setRedirect(true);  
       return pagr;  
     }  
     catch(System.DMLException e)  
     {  
       return null;  
     }  
   }  
 }  

Salesforce - Display data from Custom object to PageBlockTable using Apex

Here i have provided code sample to understand, how to display data from custom objects to PageBlockTable. I have chosen pageBlocktable because it has predefined style. Don't want to use any css styles for that.
Apex Design Code:
 <apex:page controller="ViewUserController">  
   <apex:form >  
     <apex:sectionHeader subtitle="All Users" title="Users" />  
     <apex:pageBlock >  
       <apex:pageBlockTable value="{!allusers}" var="a">  
         <apex:column headervalue="Name" value="{!a.Name__c}" />  
         <apex:column headervalue="Age" value="{!a.Age__c}" />  
         <apex:column headervalue="Class" value="{!a.Class__c}" />  
       </apex:pageBlockTable>  
     </apex:pageBlock>  
   </apex:form>  
 </apex:page>  
Apex Controller Code:
 
 public class ViewUserController  
 {  
     public List<User__c> allusers;    
     public List<User__c> getAllUsers()  
     {  
         if(allusers==null)  
         {  
             allusers=[SELECT Name__c,Age__c,Class__c from User__c];  
         }  

         return allusers;  
     }  
 }  

Gridview Edit, Update, Delete sample in ASP.NET

Here is a simple and complete source code to get an idea about how to Edit, Delete, Update data in Gridview using Gridview events like RowEditing, RowDeleting, RowUpdating. To run this application you need to create a table like shown below in SQL Table section. Updating data is just a straight forward method but to delete a record you need to set the DataKeyNames properties to the column name you using as a key in table. So that in the c# code you can retrieve the Id value when you click the Delete link in Gridview. You cannot use the method like i used in the RowUpdating event to the RowDeleting event to retrieve the Id value. It will only return null. Also don't forget to use IsPostBack in the Page_Load event.
SQL Table

Id               int                      
Name         nvarchar(MAX)
Address     nvarchar(MAX)

C# Code
string constr = @"Data Source=VENKAT;Initial Catalog=Test;Integrated Security=true";  
 protected void Page_Load(object sender, EventArgs e)  
 {  
   if (!IsPostBack)  
   {  
     bindGridView();  
   }  
 }  

 protected void bindGridView()  
 {  
   try  
   {  
     string query = "SELECT * FROM Grid ";  
     SqlConnection con = new SqlConnection(constr);  
     con.Open();  
     SqlDataAdapter da = new SqlDataAdapter(query, con);  
     DataSet ds = new DataSet();  
     da.Fill(ds);  
     GridView1.DataSource = ds;  
     GridView1.DataBind();  
   }  
   catch (Exception ex)  
   {  
   }  
 }  

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
 {  
   GridView1.EditIndex = e.NewEditIndex;  
   HiddenField1.Value = e.NewEditIndex.ToString();  
   bindGridView();  
 }  

 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
 {  
   GridView1.EditIndex = -1;  
   bindGridView();  
 }  

 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
 {  
   GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];  
   int index = Convert.ToInt32(row.RowIndex);  
   TextBox tId = (TextBox)row.FindControl("txtId");  
   TextBox tName = (TextBox)row.FindControl("txtName");  
   TextBox tAddress = (TextBox)row.FindControl("txtAddress");  
   GridView1.EditIndex = -1;  
   SqlConnection conn = new SqlConnection(constr);  
   conn.Open();  
   SqlCommand cmd = new SqlCommand("UPDATE Grid set Name='" + tName.Text + "',Address='" + tAddress.Text + "' WHERE Id=" + tId.Text + "", conn);  
   cmd.ExecuteNonQuery();  
   bindGridView();  
   conn.Close();  
 }  

 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
 {  
   string id = GridView1.DataKeys[e.RowIndex].Value.ToString();  
   SqlConnection conn = new SqlConnection(constr);  
   conn.Open();  
   SqlCommand cmd = new SqlCommand("delete from Grid where Id=" + id + "", conn);  
   cmd.ExecuteNonQuery();  
   conn.Close();  
   bindGridView();  
 }  

Design Code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id"  
       onrowcancelingedit="GridView1_RowCancelingEdit"  
       onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"  
       onrowupdating="GridView1_RowUpdating" RowStyle-VerticalAlign="Top"  
       AutoGenerateColumns="False">  
       <RowStyle VerticalAlign="Top" />  
       <Columns>  
         <asp:TemplateField ShowHeader="False">  
           <EditItemTemplate>  
             <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"  
               CommandName="Update" Text="Update"></asp:LinkButton>  
             &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"  
               CommandName="Cancel" Text="Cancel"></asp:LinkButton>  
           </EditItemTemplate>  
           <ItemTemplate>  
             <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"  
               CommandName="Edit" Text="Edit"></asp:LinkButton>  
           </ItemTemplate>  
         </asp:TemplateField>  
         <asp:TemplateField ShowHeader="False">  
           <ItemTemplate>  
             <asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False"  
               CommandName="Delete" Text="Delete"></asp:LinkButton>  
           </ItemTemplate>  
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="Id">  
             <ItemTemplate>  
               <%# Eval("Id")%>  
             </ItemTemplate>  
             <EditItemTemplate>  
               <asp:TextBox ID="txtId" runat="Server" Text='<%# Eval("Id") %>' Columns="30"></asp:TextBox>  
             </EditItemTemplate>  
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="Name">  
             <ItemTemplate>  
               <%# Eval("Name")%>  
             </ItemTemplate>  
             <EditItemTemplate>  
               <asp:TextBox ID="txtName" runat="Server" Text='<%# Eval("Name") %>' Columns="30"></asp:TextBox>  
             </EditItemTemplate>  
         </asp:TemplateField>  
         <asp:TemplateField HeaderText="Address">  
             <ItemTemplate>  
               <%# Eval("Address")%>  
             </ItemTemplate>  
             <EditItemTemplate>  
               <asp:TextBox ID="txtAddress" runat="Server" Text='<%# Eval("Address") %>' Columns="30"></asp:TextBox>  
             </EditItemTemplate>  
         </asp:TemplateField>  
       </Columns>  
</asp:GridView>  

Monday, May 20, 2013

Simple Salesforce.com Apex programming sample to call apex webservice using CSharp (C#)


Here is a very simple code to call a apex web service in salesforce using C#. It's also return a "Contact" object with values.The returning value is based on the query used in the apex web service code. From this example you can understand how to query salesforce objects, how to call apex web service, how to connect to salesforce via code and also you can understand how to retrieve salesforce object value.You can also query the custom objects.
You need to add two web reference in your application.
     1. Enterprise WSDL web reference
     2. WSDL for the webservice class you have created.

To get the Enterprise WSDL navigate to

  • Your Name -> Setup -> App Setup -> Develop -> API
  • There you can get the  Enterprise WSDL

To get the WSDL for the webservice class you have created, navigate to

  • Your Name -> Setup -> App Setup -> Develop -> Apex Class
  • There select your class. 
  • Then click generate WSDL

In the following code ApexService_WSDL is Enterprise WSDL web reference and Enterprise_WSDL is WSDL web reference for the webservice class you have created.

Apex WebService Code in SalesForce:
global class MyCustomController  
 {  
    webservice static Contact[] ReturnObject()  
    {  
      Contact[] cont=[SELECT Firstname, Lastname FROM Contact];  
      return cont;  
    }  
 }  

C# Code in Client Side Application:
SforceService binding = new SforceService();  
 private LoginResult lr;  
 binding.Timeout = 10000;  
 lr = binding.login("YOUR LOGIN EMAIL ID", "PASSWORD + SECURITY TOKEN");  
 binding.Url = lr.serverUrl;  
 binding.SessionHeaderValue = new Enterprise_WSDL.SessionHeader();  
 binding.SessionHeaderValue.sessionId = lr.sessionId;
 
 using (ApexService_WSDL.MyCustomControllerService client = new MyCustomControllerService())  
 {  
    client.SessionHeaderValue = new ApexService_WSDL.SessionHeader();   
    client.SessionHeaderValue.sessionId = lr.sessionId;                   
    ApexService_WSDL.Contact[] m = client.ReturnObject();  
 }  

Don't forget to replace you salesforce email id , password + security token ;). To get or reset your security token, navigate to the following path.

  •      Your Name -> Setup -> My Personal Information -> Reset Security Token, and click the Reset My Security Token button
  • And you will get a mail with security token.

Tuesday, May 14, 2013

Show and Hide text in ASP.NET page using JavaScript


Here JavaScript is used to Show and Hide text in ASP.NET. To do that use the below code. Replace the Sample Text inside the paragraph tag with the content u need to show hide.
JavaScript Code:
 <script type="text/javascript">  
   function ShowHide(ref) {  
     var txtArea = document.getElementById(ref);  
     var xtxtArea = document.getElementById("x" + ref);  
     if (txtArea.style.display == 'none')   
     {  
       xtxtArea.innerHTML = '<b><u>Hide Text</u></b>';  
       txtArea.style.display = '';  
     }  
     else  
     {  
       xtxtArea.innerHTML = '<b><u>Show Text</u></b>';  
       txtArea.style.display = 'none';  
     }  
   }  
 </script>  

Design Code:
 <a href="#_link" id="A1" onclick="ShowHide('txtArea');"><b><u>Show Text</u></b></a>  
 <div id="Div1" style="display: none">  
   <p>  
     Sample Text....Sample Text....Sample Text....Sample Text....  
     Sample Text....Sample Text....Sample Text....Sample Text....  
   </p>  
 </div>  

Ajax ModalPopupExtender control sample in ASP.NET


ModalPopupExtender is a very useful control in Ajax Control Toolkit. It's used to display content as a modal dialog box. Here when the user clicks the "Show" button a panel will be displayed as a modal dialog. That panel has a "Hide" button. When the user clicks the hide button the modal dialog will be closed. use your creativity to display the modal dialog box more interactively using CSS.
Namespace:
 using AjaxControlToolkit;  

Design Code:
 <asp:Button ID="btn_Show" runat="server" Text="Show" OnClick="btn_Show_Click" />  
 <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>  
 <cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" PopupControlID="Panel1" TargetControlID="HiddenField1" BackgroundCssClass="modalBackground"></cc1:ModalPopupExtender>  
 <asp:HiddenField ID="HiddenField1" runat="server" />  
 <asp:Panel ID="Panel1" runat="server">  
   <div style="width: 200px; height: 150px; background-color: yellow;">  
       <asp:Button ID="btn_Hide" runat="server" Text="Hide" OnClick="btn_Hide_Click" />  
   </div>  
 </asp:Panel>  

C# Code:
 protected void btn_Show_Click(object sender, EventArgs e)  
 {  
    this.ModalPopupExtender1.Show();  
 }  
 protected void btn_Hide_Click(object sender, EventArgs e)  
 {  
    this.ModalPopupExtender1.Hide();  
 }  

CSS code:
 .modalBackground  
 {  
   background-color: Gray;  
   filter: alpha(opacity=70);  
   opacity: 0.7;  
 }  

Note: you have to add Ajax Controll Toolkit in project.

Tuesday, May 7, 2013

XmlSerializer Serialization in CSharp (C#)


Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file.Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization. Once its serialized we can use it anywhere by using Deserialization. Here we can see a sample that serialize an object into XML format file.
 public class calculation  
 {  
     public string Name{ get; set; }  
     public string Age { get; set; }   
 }  

Serialization:
Here we converting an object into XML format file.

 calculation cal = new calculation();  
 cal.Name = "Venkadesh";  
 cal.Age = "21";  
 System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(calculation));  
 System.IO.StreamWriter swriter = new System.IO.StreamWriter(@"e:\CalculationObject.xml");  
 serializer.Serialize(swriter, cal);  
 swriter.Close();  

Deserialization:
Here we converting back from the XML format file to the object.

 
 calculation cal1 = new calculation();   
 System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(calculation));  
 System.IO.StreamReader sreader = new System.IO.StreamReader(@"e:\CalculationObject.xml");  
 cal1 = (calculation)serializer.Deserialize(sreader);  
 sreader.Close();  
 Console.WriteLine(cal1.Name);  
 Console.WriteLine(cal1.Age);  

Get the total size of a folder using CSharp (C#)


When the user clicks the btnCalculate button, the size of the each file inside the folder is calculated by looping through the folder.
C# Code:

 public double totalSize = 0;  
 private void btnCalculate_Click(object sender, EventArgs e)  
 {  
    GetTotalSize("ENTER YOUR FOLDER PATH HERE");  
 }      

 public void GetFileSize(string path)  
 {  
    FileInfo fi = new FileInfo(path);  
    totalSize += fi.Length;  
 }  

 public void GetTotalSize(string directory)  
 {  
    string[] files = Directory.GetFiles(directory);  
    foreach (string file in files)  
    {  
        GetFileSize(file);  
    }  

    string[] subDirs = Directory.GetDirectories(directory);  
    foreach (string dir in subDirs)  
    {  
        GetTotalSize(dir);  
    }  

    double size= totalSize / Math.Pow(1024, 2);  
    MessageBox.Show(Convert.ToString(size));  
 }  

Find SHA256 value of a File in CSharp (C#)


Use the below code to find the SHA256 value of a file. When the user clicks the btn_Generate_Click button the SHA256 value will be generated and displayed in a RichTextBox.
C# Code:
 private void btn_Generate_Click(object sender, EventArgs e)  
 {    
    hashOfFile("ENTER THE FILE PATH TO FIND SHA256");  
 }  
 
 public void hashOfFile(string fileToHash)  
 {  
    FileStream rdr = default(FileStream);  
    SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider();  
    byte[] bytes = null;  
    string rtn = "";  

    if (File.Exists(fileToHash))  
    {  
        rdr = new FileStream(fileToHash, FileMode.Open, FileAccess.Read);  
        bytes = sha.ComputeHash(rdr);  
        rtn = ByteArrayToString(bytes);  
    }  

    richTextBox1.Text=rtn;  
 } 
 private string ByteArrayToString(byte[] arrInput)  
 {  
    System.Text.StringBuilder sb = new System.Text.StringBuilder(arrInput.Length * 2);  
    for (int i = 0; i <= arrInput.Length - 1; i++)  
    {  
        sb.Append(arrInput[i].ToString("X2"));  
    } 
 
    return sb.ToString().ToLower();  
 }  

Find the Static IP of a system using CSharp (C#)


Use the below code to get the Static IP address of your local system.
C# Code:
 var html = new WebClient().DownloadString("http://checkip.dyndns.com/");  
 var ipStart = html.IndexOf(": ", StringComparison.OrdinalIgnoreCase) + 2;  
 IPAddress addr = IPAddress.Parse(html.Substring(ipStart, html.IndexOf("</", ipStart, StringComparison.OrdinalIgnoreCase) - ipStart));  
 string result = Convert.ToString(addr);  
 Console.WriteLine(result);  

Find the ASCII value of a string using CSharp (C#)


ASCII - The American Standard Code for Information Interchange. The below sample is a example for retrieving the ASCII value of a given string.
C# Code:
 String input = "ENTER YOUR INPUT STRING HERE";   
 String output = "";   
 foreach (char c in input)  
 {  
    output = output + (byte)c;  
 }  
 Console.WriteLine(output);  

Monday, May 6, 2013

BinaryFormatter Serialization in CSharp (C#)


Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file.Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization. Once its serialized we can use it anywhere by using Deserialization. Here we can see a sample that serialize an object into binary format file.
We have to specify the Serializable() above the class that is to be used as object like below.

C# Code:
[Serializable()]  
public class calc  
{  
    public string a;  
    public string b;  
    public string c;  
}  

Serialization:

Here we converting an object into binary format file.

calc c = new calc();  
c.a = "10";  
c.c = "20";  
c.b = "30";  
BinaryFormatter bfo = new BinaryFormatter();  
FileStream fs = new FileStream("c:\\file.dat", System.IO.FileMode.Create);  
bfo.Serialize(fs, c);  
fs.Close();  

Deserialization:

Here we converting back from the binary format file to the object.

calc c1 = new calc();     
BinaryFormatter bfo = new BinaryFormatter();  
FileStream fs = new FileStream("c:\\file.dat", System.IO.FileMode.Open);  
c1=(calc)bfo.Deserialize(fs);  
fs.Close();  
Console.WriteLine(c1.a);  

Thursday, May 2, 2013

Ajax AutoCompleteExtender control sample in ASP.NET

It this Auto Complete Extender sample, when you enter a cursor in the TextBox the code behind list of values will be displayed in text box as a dropdown. For this sample you need to add Ajax Controll Toolkit in your application.
Design Code:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>  
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
<cc1:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" TargetControlID="TextBox1" ServiceMethod="GetCountries()" MinimumPrefixLength="1" CompletionSetCount="12" CompletionInterval="500" EnableCaching="true">  
</cc1:AutoCompleteExtender>  

C# Code:
[WebMethod]  
[System.Web.Script.Services.ScriptMethod()]  
public static List<string> GetCountries()  
{  
    List<string> CountryNames = new List<string>();  
    CountryNames.Add("apple");  
    CountryNames.Add("orange");  
    CountryNames.Add("mango");  
    CountryNames.Add("banana");  
    return CountryNames;  
}  

Ajax Rating control sample in ASP.NET


In this post am gonna provide a simple Ajax rating control sample. When u change the rating by clicking the Star, the value will be displayed in a Label control. It will be useful when you develop a shopping cart kind of application. I have also attached the star images necessary for this sample.
Design Code:
<cc:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
</cc:ToolkitScriptManager>  

<asp:UpdatePanel ID="UpdatePanel1" runat="server">  
    <ContentTemplate>  
        <cc:Rating ID="Rating1" runat="server" MaxRating="5" CurrentRating="1" CssClass="ratingStar" StarCssClass="ratingItem" EmptyStarCssClass="Empty" AutoPostBack="True" OnChanged="Rating1_Changed1">  
        </cc:Rating>  
    </ContentTemplate>  
</asp:UpdatePanel>  

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>  

C# Code:
const int RATING1_MINIMUM = 1;  
const int RATING1_MAXIMUM = 5;  
protected void Page_Load(object sender, EventArgs e)  
{  
    if (!IsPostBack)  
    {  
        Evaluate_Rating1(Rating1.CurrentRating);  
    }  
}
  
public void Evaluate_Rating1(int value)  
{  
    Label1.Text = EvaluateRating(value, Rating1.MaxRating, RATING1_MINIMUM, RATING1_MAXIMUM);  
}  

public static string EvaluateRating(int value, int maximalValue, int minimumRange, int maximumRange)  
{  
    int stepDelta = (minimumRange == 0) ? 1 : 0;  
    double delta = (double)(maximumRange - minimumRange) / (maximalValue - 1);  
    double result = delta * value - delta * stepDelta;  
    return FormatResult(result);  
}  

public static string FormatResult(double value)  
{  
    return String.Format("{0:g}", value);  
}
  
protected void Rating1_Changed1(object sender, AjaxControlToolkit.RatingEventArgs e)  
{  
    Evaluate_Rating1(int.Parse(e.Value));  
}  

CSS Code:
.ratingStar  
{  
    white-space:nowrap;  
    margin:1em;  
    height:14px;  
} 
 
.ratingStar .ratingItem 
{  
    font-size: 0pt;  
    width: 13px;  
    height: 12px;  
    margin: 0px;  
    padding: 0px;  
    display: block;  
    background-repeat: no-repeat;  
    cursor:pointer;  
}  

.ratingStar .Filled 
{  
    background-image: url(../images/ratingStarFilled.png);  
}  

.ratingStar .Empty 
{  
    background-image: url(../images/ratingStarEmpty.png);  
}  

.ratingStar .Saved 
{  
    background-image: url(../images/ratingStarSaved.png);  
}  

Images:



Saturday, March 23, 2013

How to check whether a TextBox has value or not using JavaScript

Using JavaScript we can perform client side validation. It will improve the performance of your web application. Here i have shown a simple basic validation, how to check whether a text box has value or not.
    var username=document.getElementById("uname").value;  
    if (username==null || username=="")  
    {  
        alert("Please Enter Username");  
        document.getElementById("uname").focus();  
    }  

Here the alert is used to display a message box with the text it has. And the focus() is used to move the cursor to the corresponding text box.

Sample HTML5 Validations

Some HTML5 validation samples are here. You can use it in your project.
  • Limit the character count in text box. Here it's uses pattern attribute that is used to provide the Regular expression validation. So the ".{4,4}" is a regular expression that's allows only 4 character.
<input type="text" pattern=".{4,4}" name="username" id="username" value=""/>
  • Allow only numbers in text box. Here it's uses pattern attribute that is used to provide the Regular expression validation. So the "\d*" is a regular expression that's represents decimal.
<input type="text" pattern="\d*" name="phonenumber" id="phonenumber" value="" />
  • Required field validation for drop down list. If the selected field has no value means the validation will be triggered. In the below sample the "Select" field has empty value in the "value" attribute.
<select id="grade" name="grade"  required>
<option value="">Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
  • Email validation. The following code has the type="email". So it will allow only email.
<input type="email" name="email" id="email" value="">
  • Required field validation for text box. The following code has "required" attribute. That is used to provide this validation,
<input type="text" name="firstname" id="firstname" value="" required/>

Create a Tab control using JQuery in ASP.NET

By using the below code we can make a simple JQuery tab control. In this example i am going to create two tab. When we click a tab a table will be hide and another table will be visible.
  • Befor start coding download and add latest JQuery library and refer it in code like below inside head section.
<script src='js/common/jquery-1.9.1.js' ></script>
  •  Then add the below JQuery code inside head section in ASP.NET HTML design page

<script type="text/javascript">
    $(document).ready(function () {
        $(".tabLink").each(function () {
            $(this).click(function () {
                tabeId = $(this).attr('id');
                $(".tabLink").removeClass("activeLink");
                $(this).addClass("activeLink");
                $(".tabcontent").addClass("hide");
                $("#" + tabeId + "-1").removeClass("hide")
                return false;
            });
        });
    });
 </script>
  • Then add the below code in body section. This is actually a tab design.
<table cellpadding="0" cellspacing="0">
    <tr>
        <td class="contact_tab_box">
        <a href="javascript:;" class="tabLink activeLink" id="tab1">Tab1</a>
        <a href="javascript:;" class="tabLink " id="cont-2">Tab2</a>
        </td>
    </tr>
</table>
  • Now we have to design two tables to work with the tab when we click it
<table width="100%" class="tabcontent" id="t1">
    <tr>
        <td>
        DO YOUR DESIGN HERE
        </td>
    </tr>
</table>

<table width="100%" class="tabcontent hide" id="t2"> <tr> <td> DO YOUR DESIGN HERE </td> </tr> </table>
  • We need the below CSS for better design
.contact_tab_bar_left {
    background: #F2F2F2;
}
.contact_tab_bar_right {
    background: #F2F2F2;     border-radius:0px 6px 6px 0px; }
.contact_tab_box {     background: #EEEEEE; }
.contact_tab_box a {     font-family:Arial;     font-size:14px;     border:1px solid #797979;     color:#000;
    padding: 7px 30px;     text-decoration:none;     background-color: #eee;     border-radius: 6px 6px 0px 0px;     -moz-border-radius: 6px 6px 0px 0px;     -webkit-border-radius: 6px 6px 0px 0px; }
.contact_tab_box a.activeLink {     font-family:Arial;     font-size:14px;     font-weight: bold;     background-color: #3F3F3F;     color:#FFFFFF;     border-bottom: 0;     padding: 7px 30px;     border-radius: 6px 6px 0px 0px;     -moz-border-radius: 6px 6px 0px 0px;     -webkit-border-radius: 6px 6px 0px 0px; }
.contact_tab_content {     border: 1px solid #797979;     -moz-border-radius: 6px;     -webkit-border-radius: 6px;     border-radius: 6px; } .hide { display: none;}

Monday, March 18, 2013

How to read value from Web.Config file in ASP.NET

We can use Web.Config file to store any string value and that can be used in our ASP.NET application. After deploying the application also we can change the value in the config file. To do so,

In Web.Config file add a key and value that can be used in your application within the appSettings tags like below.
    <configuration>  
        <appSettings>  
            <add key="KEYNAME" value="KEYVALUE"/>  
        </appSettings>  
    </configuration> 
To retrieve the value use the below code,
string value = System.Configuration.ConfigurationManager.AppSettings["KEYNAME"].ToString();

Friday, March 8, 2013

How to call and pass parameter to a MS SQL Server Stored procedure


Refer the below code to call and pass parameter to a MS SQL Server Stored procedure. Replace the YOUR CONNECTION STRING text with the connection string of your database.
 Here UpdateIssueStatus_SP is the Stored Procedure name.
SqlParameter param;  
SqlCommand cmd;  
string connStr = "YOUR CONNECTION STRING";  

public void UpdateIssueStatus(int issueNo, char status)  
{  
    try  
    {  
        SqlConnection conn = new SqlConnection(connStr);  
        conn.Open();  
        cmd = new SqlCommand("UpdateIssueStatus_SP", conn);  
        cmd.CommandType = System.Data.CommandType.StoredProcedure;  
   
        param = new SqlParameter("@IssueNo", SqlDbType.Int);  
        param.Direction = ParameterDirection.Input;  
        param.Value = issueNo;  
        cmd.Parameters.Add(param);  
   
        param = new SqlParameter("@ApprovalStatus", SqlDbType.Char);  
        param.Direction = ParameterDirection.Input;  
        param.Value = status;  
        cmd.Parameters.Add(param);  
   
        cmd.ExecuteNonQuery();  
        conn.Close();  
    }  
    catch (Exception ex)  
    {  
    }  
}  

Write Javascript alert message box in ASP.NET code behind


To Write Javascript alert message box function  in ASP.NET code behind refer the below code. Just pass the error message as parameter to this function by calling it.
public void ShowAlertMessage(string error)  
{  
     Page page = HttpContext.Current.Handler as Page;  
     if (page != null)  
     {  
          error = error.Replace("'", "\'");  
          ScriptManager.RegisterStartupScript(page, page.GetType(), "errmsg", "alert('" + error + "');", true);  
     }  
}  

How to check whether a database exist or not in MS SQL Server

Using a simple SQL query we can check whether a database exist or not. Refer the below query.
Query:
SELECT database_id FROM sys.databases WHERE Name = 'DATABASE NAME'  

If the output is greater then 0 then the Database is exist else it's not exist

Replace the DATABASE NAME with the database name you going to check

Sample program to Encrypt and Decrypt string using TripleDESCryptoServiceProvider in CSharp (C#)


When we developing a .NET application there may be a need to encrypt a string before it getting stored into the database. And also it can be Decrypted when the string retrieved back from the database. To achieve that refer the below code.

To Encrypt:
public string key = "ab99";  
public string encryption(string strToEncrypt)  
{  
     try  
     {  
          TripleDESCryptoServiceProvider DescCryptoprovider = new TripleDESCryptoServiceProvider();  
          MD5CryptoServiceProvider MD5serviceprovider = new MD5CryptoServiceProvider();  
          byte[] bytehash = null;  
          byte[] bytebuff = null;  
          bytehash = MD5serviceprovider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));  
          MD5serviceprovider = null;  
          DescCryptoprovider.Key = bytehash;  
          DescCryptoprovider.Mode = CipherMode.ECB;  
          bytebuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);  
          return Convert.ToBase64String(DescCryptoprovider.CreateEncryptor().TransformFinalBlock(bytebuff, 0, bytebuff.Length));  
     }  
     catch (Exception ex)  
     {  
          throw;  
     }  
}  

To Decrypt:
public string decrypt(string strTodecrypt)  
{  
     try  
     {  
          TripleDESCryptoServiceProvider DescCryptoprovider = new TripleDESCryptoServiceProvider();  
          MD5CryptoServiceProvider MD5serviceprovider = new MD5CryptoServiceProvider();  
          byte[] bytehash = null;  
          byte[] bytebuff = null;  
          string decryptedstring = null;  
   
          bytehash = MD5serviceprovider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));  
          MD5serviceprovider = null;  
          DescCryptoprovider.Key = bytehash;  
          DescCryptoprovider.Mode = CipherMode.ECB;  
          bytebuff = System.Convert.FromBase64String(strTodecrypt);  
          decryptedstring = ASCIIEncoding.ASCII.GetString(
               DescCryptoprovider.CreateDecryptor().TransformFinalBlock(bytebuff, 0, bytebuff.Length)); 
 
          return decryptedstring;  
     }  
     catch (Exception ex)  
     {  
          throw;  
     }  
}  

How to Get MD5 hash value of a file using CSharp (C#)

When transferring a file through internet there is no guarantee that the file will be secured till it reach the receiver. It may be attacked by any virus or hacker. So the receiver should ensure whether the received file is secured or it attacked. To ensure that before transfer the file we have to get the MD5 hash value of the file. Then after receiving that file the receiver should get the MD5 hash value. If the both hash value is same means the file is secured one. Else it’s an attacked one.
Below is the CSharp code to find the MD5 hash value of a file,
public string GetMD5HashOfAFile(string file)  
{  
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();  
    FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 8192);  
    md5.ComputeHash(stream);  
    stream.Close();  

    byte[] hash = md5.Hash;  
    StringBuilder sb = new StringBuilder(); 
 
    foreach (byte b in hash)  
    {  
        sb.Append(string.Format("{0:X2}", b));  
    }  

    return sb.ToString();  
}  

Wednesday, March 6, 2013

Default Web Site not found in IIS 7

I recently had a problem that i couldn't find the "Default Web Site" under Sites tree view in IIS 7 and i found the solution too.

To Solve this we have to re install the IIS and WAS (Windows Process Activation Service)
To do this,

  • Go to Control Panel
  • Make sure the View By filter is set to "Category"
  • Click the Program link
  • Under the Programs and Features click "Turn windows features on or off link"
  • A window will popup
  • There uncheck the Internet Information Services and Windows Process Activation Services checkbox
  • Restart the system
  • Then recheck the check box you have unchecked(IIS & WAS)
  • Now check the Default Web Site in IIS, that will be there!

Friday, March 1, 2013

(Solved) Error: 503 Service Unavailable in IIS7

Solution:

  • Go to IIS
  • Select the Application Pool in the left side
  • Select the application pool that you are using for your application
  • Start the application pool if its stopped

Tuesday, February 26, 2013

Set up ASP.NET web application default start up page in IIS 7.0

It's essential you need to set the starting page of your ASP.net application in IIS 7.0. hear i have provided the solution to do that

  • Go to IIS 7.0
  • Select the Published ASP.NET application
  • In the right side double click the Default document
  • There add your Start up page


(Solved) Error: HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.


When you publish a ASP.NET application in IIS 7.0 you may getting this error.

HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
To Solve this,

  • Add a Start up page for your published application in IIS.





(Solved) Error: Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format.

When you publish a ASP.NET application in IIS you may getting this error.

"Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format." To Solve this,


  • Go to IIS
  • Double click the Application Pool
  • Right click the application pool you are using for your application
  • Select Advanced Settings
  • There you can see Enable 32 bit Application set to False
  • Change that to True 
  • It will work now

Saturday, February 9, 2013

Encrypt a Password string in C Sharp (C#)

When you develop a secured ASP.NET web application you need to encrypt the password before it getting stored in database. Encryption means converting input data into an unreadable format.

Here is a simple code to encrypt a given string. You can use it in your project.
public string EncryptIt(string inputString)  
{  
    try  
    {  
        byte[] encryptedByteData= new byte[inputString.Length];  
        encryptedByteData= System.Text.Encoding.UTF8.GetBytes(inputString);  
        string encryptedData= Convert.ToBase64String(encryptedByteData);  
        return encryptedData;  
    }  
    catch (Exception ex)  
    {  
        throw ex;  
    }  
}  

Friday, February 8, 2013

Create CSV file from a DataTable in CSharp (C#)

While working as a .net programmer you may getting a requirement to convert a DataTable to CSV file format.

CSV - Comma Separated Value. Tabular format data are converted into comma separated values text file with the extension of csv. See sample below

Name, Age, Eid, Native
Raj, 27, E0025, Chennai 
Kumar, 20, E0032, Nagercoil
Balu, 22, E0024, Mumbai
Raj, 25, E0026, Bangalore

To achieve this in C#

public void CreateCSVFile(DataTable dt, string strFilePath)  
{  
    try  
    {  
        StreamWriter sw = new StreamWriter(strFilePath, false);  
        int columnCount = dt.Columns.Count; 
 
        for (int i = 0; i < columnCount ; i++)  
        {  
            sw.Write(dt.Columns[i]); 
 
            if (i < columnCount - 1)  
            {  
                sw.Write(",");  
            }  
        }  

        sw.Write(sw.NewLine);  
         
        foreach (DataRow dr in dt.Rows)  
        {  
            for (int i = 0; i < columnCount ; i++)  
            {  
                if (!Convert.IsDBNull(dr[i]))  
                {  
                    sw.Write(dr[i].ToString());  
                }  

                if (i < columnCount - 1)  
                {  
                    sw.Write(",");  
                }  
            }  

            sw.Write(sw.NewLine);  
        }  

        sw.Close();  
        }  
        catch (Exception ex)  
        {  
            throw ex;  
        }  
}  
Call the CreateCSVFile function like below by passing the DataTable to convert and the path of the CSV file to be saved.
static void Main(string[] args)
{
    CreateCSVFile(dt,"D://ConvertedFile.csv");
}

Alter a table column that has primary key and foreign key


We may getting error when we try to alter a column in SQLServer table. To handle that situation we need to delete the Primary Key and Foreign Key from the table before alter. Below is a sample code to alter datatype of a column name id from int to bigint in a table PaymentsType.

ALTER TABLE PaymentsType drop CONSTRAINT PK_PaymentsType  
ALTER TABLE PaymentsType ALTER COLUMN id bigint not null  
ALTER TABLE PaymentsType ADD CONSTRAINT PK_PaymentsType PRIMARY KEY (id)  

Friday, January 25, 2013

Remember password functionality in ASP.NET

In the Login button click write the below code

protected void btn_Login_Click(object sender, EventArgs e)  
{  
     if (cb_Remember.Checked)  
     {  
          HttpCookie prCookie = new HttpCookie("PRCOOKIE");  
          prCookie["EID"] = txt_EmpId.Text;  
          prCookie["PWD"] = txt_Password.Text;  
          Response.Cookies.Add(prCookie);  
          Response.Cookies["PRCOOKIE"].Expires = DateTime.Now.AddDays(30);  
     }  
     else  
     {  
          Response.Cookies["PRCOOKIE"].Expires = DateTime.Now.AddDays(-1);  
     }  
}  
Here,
cb_Remember is a CheckBox
txt_EmpId.Text is a Login Name TextBox
txt_Password.Tex is a Password TextBox


then in the Page_Load function add the below code

protected void Page_Load(object sender, EventArgs e)  
{  
     HttpCookie cookie = Request.Cookies["PRCOOKIE"];  
     if (cookie != null)  
     {  
          txt_EmpId.Text = Convert.ToString(cookie["EID"]);  
          txt_Password.Attributes["Value"] = Convert.ToString(cookie["PWD"]);  
     }  
}  

Thursday, January 24, 2013

How to Bind DataTable to ASP.NET Pie Chart


To Bind DataTable to ASP.NET Pie Chart, refer the below code.
 DataTable dt=new DataTable();  
   
 dt.Columns.Add("Name");  
 dt.Columns.Add("Percentage");  
   
 DataRow dr=dt.NewRow();  
 dr["Name"]="Name1";  
 dr["Percentage"]="80";  
 dt.Rows.Add(dr);  
   
 DataRow dr1=dt.NewRow();  
 dr1["Name"]="Name2";  
 dr1["Percentage"]="75";  
 dt.Rows.Add(dr1);  
   
 DataRow dr2=dt.NewRow();  
 dr2["Name"]="Name3";  
 dr2["Percentage"]="90";  
 dt.Rows.Add(dr2);  
   
 DataRow dr3=dt.NewRow();  
 dr3["Name"]="Name4";  
 dr3["Percentage"]="100";  
 dt.Rows.Add(dr3); 
   
 Dictionary<string, int> chartData = new Dictionary<string, int>();  
 foreach (DataRow r in dt.Rows)  
 {  
     string key = r["Name"].ToString();  
     int value = Convert.ToInt32(r["Percentage"]);  
     chartData.Add(key, value);  
 }  
   
 Chart1.Series["Series1"].Points.DataBind(chartData , "Key", "Value", string.Empty);  

How to count days between two dates except Saturday and Sunday in CSharp (C#)


To count days between two dates except Saturday and Sunday use the below C# code
public int CountDays(fromDate,toDate)  
{  
     int noOfDays = 0;  
     DateTime fDate = Convert.ToDateTime(fromDate);  
     DateTime tDate = Convert.ToDateTime(toDate);  
     while (DateTime.Compare(fDate, tDate) <= 0)  
     {  
          if (fDate.DayOfWeek != DayOfWeek.Saturday && fDate.DayOfWeek != DayOfWeek.Sunday)  
          {  
               noOfDays += 1;  
          }  

          fDate = fDate.AddDays(1);  
     }  
     
     return noOfDays;  
}  

Compare two date in CSharp (C#)

Some times you may have a situation to compare two dates for the date validation. You can do this easily using the DateTime.Compare method.
public bool ValidateDate(string from,string to)  
{  
     bool isValid = false;  
     if (from != string.Empty && to != string.Empty)  
     {  
          if (DateTime.Compare(Convert.ToDateTime(txt_From.Text), Convert.ToDateTime(txt_To.Text)) == 1)  
          {  
               isValid = false;  
          }  
          else  
          {  
               isValid = true;  
          } 
 
          if (DateTime.Compare(Convert.ToDateTime(to), DateTime.Now) > 0)  
          {  
          isValid = false;  
          }  
     } 
 
     return isValid;  
}  

Move ListBox selected Items to another ListBox in ASP.NET CSharp (C#)

Assume you have two  ListBoxes ListBox1 and ListBox2 in your ASP.NET application. You like to move selected items from ListBox1 to ListBox2. Usee the below code.
if (ListBox.Items.Count > 0 && ListBox.SelectedItem != null)  
{  
    while (ListBox.Items.Count > 0 && ListBox.SelectedItem != null)  
    {  
        ListItem selectedItem = new ListItem();  
        selectedItem = ListBox.SelectedItem;  
        selectedItem.Selected = false;  
        ListBox2.Items.Add(selectedItem);  
        ListBox1.Items.Remove(selectedItem);  
    }  
}  

you can move multiple items by selecting multiple items in list box. To do that you have to set the ListBox "SelectionMode" properties to "Multiple"

Display online users in in ASP.NET application

To display online users in ASP.NET application u need to add a Global.asax file. Global.ascx is the ASP.NET application file. It has some application level events raised by ASP.NET application. In the below code whenever a user log in to your application a count will increase in Application["CurrentUsers"] state. The count will decrease when he Log Out.
void Application_Start(object sender, EventArgs e)  
{  
    // Code that runs on application startup  
    Application["CurrentUsers"] = 0;  
}  

void Application_End(object sender, EventArgs e)  
{  
    // Code that runs on application shutdown  
}  

void Application_Error(object sender, EventArgs e)  
{  
    // Code that runs when an unhandled error occurs  
}  

void Session_Start(object sender, EventArgs e)  
{  
    // Code that runs when a new session is started  
    Application.Lock();  
    Application["CurrentUsers"] = (int)Application["CurrentUsers"] + 1;  
    Application.UnLock();  
}  

void Session_End(object sender, EventArgs e)  
{  
    // Code that runs when a session ends.  
    // Note: The Session_End event is raised only when the sessionstate mode  
    // is set to InProc in the Web.config file. If session mode is set to StateServer  
    // or SQLServer, the event is not raised.  
    Application.Lock();  

    if ((int)Application["CurrentUsers"] > 0)  
    {  
        Application["CurrentUsers"] = (int)Application["CurrentUsers"] - 1;  
    }  

    Application.UnLock();  
}  
Then in the Code behind add the below code
Label1.Text = Convert.ToString(Application["CurrentUsers"]);  

Add a new event to server control in asp.net

Server controls in asp.net may not have all required events. But we can add additional javaScript events. So here i have provided a example to add a "Double Click" event in ListBox control.
protected void Page_Load(object sender, EventArgs e)  
{  
    ListBox1.Attributes.Add("ondblclick", ClientScript.GetPostBackEventReference(ListBox1, "doubleClickEvent"));  
    if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "doubleClickEvent")  
    {  
        //Write your code to handle the Double Click Event  
    }  
}  

Wednesday, January 23, 2013

Set up ASP.NET web application default page in IIS

It's essential to set the starting page of your ASP.net application in IIS. Here I have provided the solution to do that
  • Go to Start -> Run
  • Type "inetmgr" then press Enter
  • In the Default Web Site right click your web application then select Properties
  • Navigate to Documents tab
  • Add the page name with extension by clicking the add button
  • Press Apply

It will work now!

Expand or collapse displaying text in asp.net label using more/less link button

To Expand or collapse displaying text in asp.net label using more/less link button use the below code
 <script type="text/javascript">  
   $(document).ready(function () {  
     var showChar = 200;  
     var ellipsestext = "...";  
     var moretext = "more";  
     var lesstext = "less";  
     $('.more span').each(function () {  
       var content = $(this).html();  
       if (content.length > showChar) {  
         var c = content.substr(0, showChar);  
         var h = content.substr(showChar - 1, content.length - showChar);  
         var html = c + '<span class="moreelipses">' + ellipsestext + '</span>&nbsp;<span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';  
         $(this).html(html);  
       }  
     });  
     $(".morelink").click(function () {  
       if ($(this).hasClass("less")) {  
         $(this).removeClass("less");  
         $(this).html(moretext);  
       } else {  
         $(this).addClass("less");  
         $(this).html(lesstext);  
       }  
       $(this).parent().prev().toggle();  
       $(this).prev().toggle();  
       return false;  
     });  
   });  
 </script>  
  • Add the above code in asp.net page
  • Cover the label with div tags and use a class "more" like showing in below code

 <div class="more">  
 <asp:Label ID="Label1" runat="server" Text=""></asp:Label>  
 </div>  

The JavaScript code will search the more class in asp.net design page and apply the more / less functionality.

(Solved) Error: Unrecognized attribute 'targetFramework'.

Error:

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive.

Source Error:
</controls>  
    </pages>  
    <compilation debug="true" targetFramework="4.0" />    
<authentication mode="Forms">  
Solution:
In IIS 5.1
  • Go to Start -> Run
  • Type "inetmgr" then press Enter
  • In the Default Web Site right click your web application then select Properties
  • Navigate to ASP.NET tab
  • Change the ASP.NET version to 4.0
  • Press Apply
  • It will work now

(Solved) Error: Invalid temp directory in chart handler configuration [c:\TempImageFiles\]

Solution for this error is,
  • Go the the Web.config file in your ASP.NET application
  • Navigate to the below line
<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;">
</add>
  • Just remove the dir element from the add attribute like below
<add key="ChartImageHandler" value="storage=file;timeout=20;">
</add>
  • Publish your app.