September 2011

Alert Box in Android

protected void alertbox(String title, String mymessage)
{
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){}
})
.show();
}

For more details see below link…
http://huuah.com/dialog-boxes-in-android/

How to parse json string object in Android

First of all you have understand what is jsonObject and jsonObjectArray.
ex. of jsonObject
{
“Validate”: “true”
}
if string start with “{” then it’s a only a object.
[
{
“Validate”: “true”
}
]
if string start with “[” then its array of object.

Here I describe both how to parse object or array of string as below.
Create a Class it has a one property.

public class Users {
public String Validate;
public void setUser(String Validate)
{
this.Validate = Validate;
}
public String getValidate()
{
return Validate;
}
}

—– bleow function parse json… create a new class which is parse json string
public class jsonParser {
JSONObject jsonObject;
JSONArray jsonArray;
Users objUser;

public jsonParser()
{
objUser = new Users();
}
public Users parseUser(String str)
{
try {
jsonObject = (JSONObject) new JSONObject(str);

objUser.companyId = jsonObject.getString(UserConstant.Company_Id);
objUser.FullName= jsonObject.getString(UserConstant.Full_Name);
objUser.LastLoginDate= jsonObject.getString(UserConstant.Last_Login_Date);
objUser.Password= jsonObject.getString(UserConstant.PASSWORD);
objUser.UserId = jsonObject.getString(UserConstant.User_Id);
objUser.Validate= jsonObject.getString(UserConstant.VALIDATE);
objUser.WrongPassCount= jsonObject.getInt(UserConstant.WRONGPASSCOUNT);
objUser.isActiveDirectory= jsonObject.getBoolean(UserConstant.IsActiveDirectory);

Log.d(“Json Result = ” , objUser.Validate);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
objUser=null;
}

return objUser;
}

public ArrayList parseUsers(String str)
{
ArrayList appUserList= new ArrayList();
Users user;
try {
jsonArray = (JSONArray) new JSONArray(str);
int arrayLength = jsonArray.length();

for(int i=0;i<arrayLength;i++)
{
user = new Users();
JSONObject arrayObject1 = jsonArray.getJSONObject(i);
user.setUser(arrayObject1.getString(UserConstant.Company_Id),
arrayObject1.getString(UserConstant.Full_Name),
arrayObject1.getString(UserConstant.Last_Login_Date),
arrayObject1.getString(UserConstant.PASSWORD),
arrayObject1.getString(UserConstant.User_Id),
arrayObject1.getString(UserConstant.VALIDATE),
arrayObject1.getInt(UserConstant.WRONGPASSCOUNT),
arrayObject1.getBoolean(UserConstant.IsActiveDirectory)
);
appUserList.add(user);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return appUserList;
}
}

Consume webservice in Android app

First of all give internet permission to app for that below steps.
1. Open “AndroidManifest.xml” file.
2. Copy below code under

Now make one function which is consume web service.
public String doRequest(String requestURL)
{
InputStream is = null;
String jsonString = “”;
HttpClient httpClient = null;
HttpGet request = null;

try {

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,20*1000); // Connection timeout
HttpConnectionParams.setSoTimeout(httpParameters, 20*1000); // Socket timeout

// Create a new HttpClient and Post Header
httpClient = new DefaultHttpClient(httpParameters);

request = new HttpGet(requestURL);

HttpResponse httpResponse = httpClient.execute(request);

is = httpResponse.getEntity().getContent();

byte buff[] = new byte[1024];
int c = 0;
while ((c = is.read(buff)) != -1) {
jsonString += new String(buff, 0, c);
}
// Log.d(tag, “JSON-String =” + jsonString);
} catch (Exception e) {

e.printStackTrace();
return null;

} finally {
// Close opened streams.
// FIX
try {
if (is != null)
is.close();

if (httpClient != null)
httpClient = null;

if (request != null)
request = null;

} catch (IOException e) {
e.printStackTrace();
}
}
// Log.d(“HttpRequest”, “### Returning ” + jsonString);
return jsonString;
}

— CAll this function when you want to get result of web service —
String requestStr = “http://salesbook.iglobeapps.com/json/loginservice.svc/validateuser?email=demo1&password=demo111”;
String str = doRequest(requestStr);

clear previous history in every textbox

Its a problem recently I am facing in my recent project.

So my client told me you should clear previous history in every textbox. So I just write a textbox properties in Page_Prerender event in my page(codebehind).
protected void Page_PreRender(Object sender, EventArgs e)
{
txtPassword.Attributes.Add(“autocomplete”, “off”)
txtConfirmPassword.Attributes.Add(“autocomplete”, “off”);
}

It will solve your problem.

Dynamically Add Header in Crystal Report

string amount = amountTextBox.Text;
string titleString = ” Total Sanctions above “;

List investmentList = new List();
investmentList = new InvestmentManager().CollectAmountWiseInvestment(amount);

expirySanctionCrystalReport reportDocumentObject = new expirySanctionCrystalReport();

//Set Crystal Report Header
CrystalDecisions.CrystalReports.Engine.TextObject amountText = (CrystalDecisions.CrystalReports.Engine.TextObject)reportDocumentObject.ReportDefinition.ReportObjects[“dateText”];
amountText.Text = amount;

CrystalDecisions.CrystalReports.Engine.TextObject titleText = (CrystalDecisions.CrystalReports.Engine.TextObject)reportDocumentObject.ReportDefinition.ReportObjects[“TextTitle”];
titleText.Text = titleString;

reportDocumentObject.SetDataSource(investmentList);
amountWiseCrystalReportViewer.ReportSource = reportDocumentObject;
amountWiseCrystalReportViewer.RefreshReport();
amountWiseCrystalReportViewer.Visible = true;

Get Last Day Of Month

—-Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
—-Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
—-Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth
ResultSet:
LastDay_PreviousMonth
———————–
2007-07-31 23:59:59.000

LastDay_CurrentMonth
———————–
2007-08-31 23:59:59.000

LastDay_NextMonth
———————–
2007-09-30 23:59:59.000

If you want to find last day of month of any day specified use following script.
–Last Day of Any Month and Year
DECLARE @dtDate DATETIME
SET @dtDate = ‘8/18/2007’
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
LastDay_AnyMonth
ResultSet:
LastDay_AnyMonth
———————–

Email From SQL in HTML format

declare @body1 nvarchar(MAX)
set @body1 = N’

:: Report(1-06-2011 To 30-06-2011) ::

‘ +
N’

‘ +
N” + CAST ( ( SELECT
td = FirstName, ”,
td = LastName, ”,
td = EmailId, ”
from Users
ORDER BY FirstName ASC FOR XML PATH(‘tr’), TYPE ) AS NVARCHAR(MAX) ) +
N’

First Name Last Name Email


print @body1
EXEC msdb.dbo.sp_send_dbmail @recipients=’sunil@iglobeconsulting.com’,
@subject = ‘My Mail Test’,
@body = @body1,
@profile_name = ‘Prakash Rathod’,
@body_format = ‘HTML’ ;

Use Uniqueidentifier in dynamic SQL in SQL Server 2008/2005

We used to use uniqueidentifier so many times in our database, since it is one of the unique field in table, we may need to put it in dynamic SQL quite a few times but I have seen so many times that even seasoned developer don’t know how to use UniqueIdentifier in dynamic SQL, may be in Store procedure in SQL Server. This is the reason I tempted to write something for this topic.

Let us see it practically:

–create table for testing
if OBJECT_ID(‘IDTester’) is not null drop table IDTester
create table IDTester
(
ID uniqueidentifier default newid(),
name varchar(20)
)
GO

–insert few records
insert into IDTester(name)
select ‘Ritesh’ union all
select ‘Rajan’ union all
select ‘Bihag’ union all
select ‘Abhijit’
GO

–let us see what we come up with
select * from IDTester
GO

–create simple SP
Create proc SPIDTester
@ID uniqueidentifier
as
begin
select * from IDTester where ID=@ID
end
GO

—-I got ‘7F1D8BC8-48AA-437E-B19F-4ABD139AD5E5’ for first record
—-you may get something else as a ID of first records.
exec spidtester ‘7F1D8BC8-48AA-437E-B19F-4ABD139AD5E5′
GO

–let us create another SP with dynamic SQL but it will show us an error
Create proc SPIDTester2
@ID uniqueidentifier
as
begin
declare @sql varchar(max)
set @sql=’select * from IDTester where ID=’ + @ID
exec (@sql)
end
GO
–if you will try to create above SP, you will be greeted with
–following error
–Msg 402, Level 16, State 1, Procedure SPIDTester2, Line 6
–The data types varchar and uniqueidentifier are incompatible in the add operator.

–you have to use sp_executeSQL to get rid of above error
–with additional parameter
create proc SPIDTester2
@ID uniqueidentifier
as
begin
declare @sql nvarchar(max)
set @sql=’select * from IDTester where ID=@I’
exec sp_executesql @sql,N’@I uniqueidentifier’,@I=@ID
end
GO

–let us see whether SP actually works
exec spidtester2 ‘7F1D8BC8-48AA-437E-B19F-4ABD139AD5E5′
GO

———————————– Pass more then one parameter —————————————-

DECLARE @SQL_String NVARCHAR(max)
DECLARE @Parameter_Definition NVARCHAR(max)

SET @SQL_String = N’
EXEC GetEmail2 @EmployeeId = @EmployeeId_input, @Email = @Email_out OUTPUT

SET @Parameter_Definition = N’
@EmployeeId_input uniqueidentifier,
@Email_out nvarchar(50) OUTPUT’

DECLARE @EmployeeId uniqueidentifier
DECLARE @Email nvarchar(50)

SET @EmployeeId = ‘997B3351-F876-414B-9C63-B90EC967B69B’

EXECUTE sp_executesql @SQL_String, @Parameter_Definition, @EmployeeId_input = @EmployeeId, @Email_out = @Email OUTPUT

SELECT @Email as Email

GO