Browse Month: July 2013

How to ObjectSerializer in to java to store in shared preference in Android


public class ObjectSerializer {

// private static final Log log = LogFactory.getLog(ObjectSerializer.class);

public static String serialize(Serializable obj) throws IOException {
if (obj == null) return "";
try {
ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
objStream.writeObject(obj);
objStream.close();
return encodeBytes(serialObj.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

public static Object deserialize(String str) throws IOException {
if (str == null || str.length() == 0) return null;
try {
ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
ObjectInputStream objStream = new ObjectInputStream(serialObj);
return objStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

public static String encodeBytes(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();

for (int i = 0; i > 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}

return strBuf.toString();
}

public static byte[] decodeBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i+=2) {
char c = str.charAt(i);
bytes[i/2] = (byte) ((c - 'a') << 4);
c = str.charAt(i+1);
bytes[i/2] += (c - 'a');
}
return bytes;
}

}

Create a Lead in Salesforce using JAVA

In Salseforce  :
    1. Download Enterprise WSDL  as name enterprise.wsdl
    2. Download wsc-22.jar from https://code.google.com/p/sfdc-wsc/downloads/detail?name=wsc-22.jar&can=2&q=
    (wsdl and wsc-22 should be in same Directory)
    
goto Command Prompt
    1. goto Directory where wsdl file located.
    2. Type : java -classpath wsc-22.jar com.sforce.ws.tools.wsdlc enterprise.wsdl.xml enterprise.jar
    (enterprise.jar will be created)
    
In Eclipse :
    import both jar wsc-22 and enterprise.
    use Following code to create a lead 
    
    <%@page import="com.sforce.ws.*"%>
    <%@page import="com.sforce.soap.enterprise.*"%>

    String username = "xxxxxxxxxx";
    String password = "Password+SecurityToken";
    String authEndPoint = "https://test.salesforce.com/services/Soap/c/24.0/";
    
    ConnectorConfig config2 = new ConnectorConfig();
    config2.setUsername(username);
    config2.setPassword(password);
    config2.setAuthEndpoint(authEndPoint);
    connection = new EnterpriseConnection(config2);
    EnterpriseConnection enterCon = Connector.newConnection(config2);
    GetUserInfoResult userInfo = enterCon.getUserInfo();
    success = true;
    if(success == false)
        return;

    try {    
        Lead newLead= new Lead();
        newLead.setName("OpportunityWithFK");
        newLead.setStageName("Prospecting");
        SaveResult[] results = connection.create(new SObject[] {newLead});
    }
    catch (ConnectionException ce)
    {  ce.printStackTrace();   }

Erstwhile you get outlined your terms, you can use them without distressing too practically http://mycollegepapers.org/ What the circulations of these papers are, I do not live 13 November 14, 1252pm I was innate in Australia but grew up in England httpwww.lafabricadecarbon.compage72 468 httpesenciadepodcast.comm174 422 httpwww.lafabricadecarbon.compage170 486 httpwww.pmrs.plindexwqckq.phpdiff82 484 httpwww.pmrs.plindexwqckq.phpdiff99 452 httpwww.friendshiptibet.comitinerary.php?rom22 419 httpwww.lafabricadecarbon.compage4 467 httpesenciadepodcast.comm177 424 16 November 14, 237pm A fiscal consultant httpwww.cafsowrag4development.orgpay-someone-to-do-my-papewr customized theme The Investigatory Committee laid-off Greenpeaces claimthat the resist was peaceful, expression anyone who lawlessly andpremeditatedly seizes

Add Products list to Activities i.e. Events and Tasks

Hello,
Many of you want to add products lists to Events or Tasks because it is very important to have products list on Events or Tasks page layout so that if any of your sales person makes a call or mail to you, he should be able to give the list of products requested or sale. So, to have this functionality, please see the below screenshots;

  1. Add button on Task or Event Page layout as shown below:

Add Products Button

2. After adding button, click on this button and you will redirected  to a page, where you can select the products for adding in Activities as shown below:

Select Products to add on Activities

3. Once you have selected the products, those products will appear on that Activity page layout  as shown below:

Products List on Activity Page layout

 

If you want full source code for this, please contact us at info@nanostuffs.com

 

Thanx.

XML Parsing in Salesforce

<?xml version='1.0' encoding='iso-8859-1' ?>
<Root>
<Record>
    <CateID>1</CateID>
    <Name>NameABC</Name>
    <Phone>12356</Phone>
    <Email>info@gmail.com</Email>
    <Website>http://www.nameabc.com/page.html</Website>
</Record>
<Record>
    <CateID>2</CateID>
    <Name>Namexyz</Name>
    <Phone>456879</Phone>
    <Email>info@ymail.com</Email>
    <Website>http://www.namexyz.com/page.html</Website>
</Record>
</Root>

// consider, This above XML getting from Listing()

public void Listing()
{     
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://demos.sfxmlpase.com/xml');
        req.setMethod('GET');
        HttpResponse res = http.send(req);         
        String xmlContent = res.getBody();         
        XmlStreamReader reader = res.getXmlStreamReader();    
        XMLData = XMLParser(res.getBody());
     }
public List<String> XMLParser(String strXml)
    {             
       
        List<String> xmlstring =new List<String>();
        Dom.Document doc = new Dom.Document();
        doc.load(strXml);
        Dom.XMLNode Envelope = doc.getRootElement();
        for(integer i=0; i < Envelope.getChildElements().size(); i++)
        {
            Dom.XMLNode Body = Envelope.getChildElements()[i];
            for(Dom.XMLNode child : Body.getChildElements())
            {
                String Text = child.getText();
                if(child.getText().contains('%23'))
                Text = child.getText().replace('%23', '&');
               
                xmlstring.add(Text);
            }
        }
       
    return xmlstring;
    }        //XMLData in Listing() will have all the text inside the tags in list

Get records using Salesforce Partner WSDL in .net

Hi,

If you want to fetch the records from Salesforce object’s by using Partner WSDL in .net
then use this code. It also fetch the number of records available in Salesforce custom
and standard object.

Step 1 : Create new Web-service project in .net

Step 2 : Add your Partner WSDL  in your new project. For detail instruction Click here

Steps 3 :  Add new Item to your project and name it as “test.aspx” and add following code to it:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using sforce;

public partial class login : System.Web.UI.Page
{
NanoDictionary rbm = null;
SforceService bind = null;
String tableName, whrval, whrval1, likeQuery, simpleQuery;
List<String> lst = null;
protected void Page_Load(object sender, EventArgs e)
{
//Initialisations
String uname = “user@unsername.com”;
String pass = “Password+SecurityToken”;
String ur = “http://login.saleforce.com”;
rbm = new NanoDictionary(uname, pass, ur);
//Login to Salesforce
bool bl = rbm.loginSample();
Response.Write(“Login Success: ” + bl + “n”);
Response.Write(“<br>”);
lst = new List<string>();
lst.Add(“Name”);
lst.Add(“Gender__c”);
lst.Add(“Email”);
tableName = “Lead”;
whrval = “al”;
whrval1 = “Male”;
likeQuery = lst.ElementAt(2) + ” Like ‘%” + whrval + “%'”;
simpleQuery = lst.ElementAt(1) + ” = ‘” + whrval1 + “‘”;
//Call Method to get record count
int rec = rbm.getRecordsCount(tableName, simpleQuery+” or “+likeQuery);
if (rec > 0)
{
Response.Write(“Number Of Records: ” + rec+”<br>”);
}
else
{
Response.Write(“No Record found<br>”);
}
//Fetch Records
String name, gender, eml;
if (bl == true)
{
bind = rbm.binding;
QueryResult qres = rbm.getRecords(tableName, lst, simpleQuery+” or “+likeQuery, 2, 10, false);
if (qres != null)
{
//Convert & show Result
Response.Write(“<br>Table Name: <b>” + tableName);
Response.Write(“</b><br><br>”);
Response.Write(“<table border = ‘0’ width=’50%’>”);
Response.Write(“<tr>”);
Response.Write(“<th align=’left’> Name </th>”);
Response.Write(“<th align=’left’> Gender </th>”);
Response.Write(“<th align=’left’> Email </th>”);
Response.Write(“</tr>”);
for (int j = 0; j < qres.records.Length; j++)
{
sforce.sObject obj = qres.records[j];
name = obj.Any[0].InnerText;
gender = obj.Any[1].InnerText;
eml = obj.Any[2].InnerText;
Response.Write(“<tr><td width=’15%’>”);
Response.Write(name);
Response.Write(“</td><td width=’10%’>”);
Response.Write(gender);
Response.Write(“</td><td width=’15%’>”);
Response.Write(eml);
Response.Write(“</td></tr>”);
}
Response.Write(“<table><br><br>”);
}
else
{
Response.Write(“<font color=’red’>Query parameter: ” + rbm.inputQry);
Response.Write(“</font><br>Please check Syntax for query parameter”);
}
}
}
}

Step 4: Create a c# class in this project and name it “NanoDictionary” and paste following code in it.

using System;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using sforce;
using System.Collections.Generic;

public class NanoDictionary
{
//Other Variables
public String username, password, url, inputQry;
public SforceService binding;
QueryResult qres;

//Constructor
public NanoDictionary(String username, String password, String url)
{
this.username = username;
this.password = password;
this.url = url;
}
//Method to count records
public int getRecordsCount(String tableName, string query)
{
int size = 0;
String qry = "select Id from " + tableName;
try
{
if (query != string.Empty)
qry += " where " + query;
qres = binding.query(qry);
size = qres.size;
}
catch (Exception ex)
{
//In case of any error -1 would be returned.
Console.Write("ex: " + ex);
size = -1;
}
//For succesful execution, return no. of records.
return size;
}
//Method to check if requested fields are available in specified object
public bool checkFields( String tblname, List fldlst)
{
Field[] flds = null;
bool chk = true;
List tempList = new List();
try
{
DescribeGlobalResult dgr = binding.describeGlobal();
DescribeGlobalSObjectResult[] dgsor = dgr.sobjects;
DescribeSObjectResult dsor = binding.describeSObject(tblname);
if (dsor != null)
{
flds = dsor.fields;
for (int i = 0; i < flds.Length; i++)
{
tempList.Add(flds[i].name);
}
}
else
{
}
IEnumerable check = fldlst.Except(tempList);
if (check.Count() != 0)
{
chk = false;
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Error: " + e.Message);
}
return chk;
}
//Method to login in salesforce
public bool loginSample()
{
Boolean success = false;
// Create a service object
binding = new SforceService();
LoginResult lr;
try
{
lr = binding.login(username, password);
// Save old authentication end point URL
String authEndPoint = url;
// Set returned service endpoint URL
binding.Url = lr.serverUrl;
binding.SessionHeaderValue = new SessionHeader();
binding.SessionHeaderValue.sessionId = lr.sessionId;
success = true;
if(success == true)
System.Diagnostics.Debug.WriteLine("Login");
GetUserInfoResult userInfo = lr.userInfo;
System.Diagnostics.Debug.WriteLine("User Name: " + username);
System.Diagnostics.Debug.WriteLine("UserID: " + userInfo.userId);
System.Diagnostics.Debug.WriteLine("User Full Name: " + userInfo.userFullName);
System.Diagnostics.Debug.WriteLine("User Email: " + userInfo.userEmail);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("An unexpected error has occurred: " +e.Message + "n" + e.StackTrace);
}
return success;
}
public QueryResult getRecords(String tableName, List fldName, String query, int skip, int take, bool more)
{
binding.QueryOptionsValue = new sforce.QueryOptions();
binding.QueryOptionsValue.batchSize = 250;
binding.QueryOptionsValue.batchSizeSpecified = true;
String qry = "select ";

//Check the fields are available in specified object
bool chk = checkFields(tableName, fldName);
if (chk == false)
{
return null;
}
else
{
List fldlist = new List();
fldlist.AddRange(fldName);
for (int i = 0; i < fldlist.Count(); i++)
{
qry += fldlist[i] + ", ";
}
qry = qry.Substring(0, qry.Length - 2);
qry += " ";
qry += "from " + tableName;

if(query != String.Empty)
{
qry += " where " + query ;
}
qry += " limit " + take;
inputQry = qry;
System.Diagnostics.Debug.WriteLine("qry: " + qry);
bool tt = true;
try
{
qres = binding.query(qry);
}
catch (Exception er)
{
//If Query is not in correct format, return false.
Console.Write("er: " + er);
tt = false;
}
if (tt == true)
{
Console.Write("tt: " + tt);
return qres;
}
else
{
return null;
}
}
}
}

Thanx.

How to store the object in to database(Java Serializable Object to Byte Array)

The best way to do it is to use ApacheUtils:

To Serialize:

byte[] data = SerializationUtils.serialize(yourObject);

deserialize:

YourObject yourObject = (YourObject) SerializationUtils.deserialize(byte[] data)

SerializationUtils Class:

package com.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationUtils{
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}

public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
}