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: