how do i keep a parameter when servlet refreshes? - while-loop

I am trying to keep a parameter after the servlet refreshes. I tried sessions but it wont work. Can anyone help me please
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String equip = request.getParameter("name");
String qty = request.getParameter("qty");
String equipId = null;
//HttpSession session = request.getSession();
//String itemId = (String) session.getAttribute("repId");
String itemId = request.getParameter("repId");
HttpSession session = request.getSession();
session.setAttribute("id", itemId);
//System.out.println(equip);
//System.out.println(qty);
System.out.println(itemId);
String itemId1 = (String)session.getAttribute("id");
System.out.println(itemId1);
try {
DB_Connection db = new DB_Connection();
Connection conn = db.getDBconnection();
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("SELECT id from equipment where name='"+equip+"'");
while(rs1.next()){
equipId=(String)rs1.getString("id");
//System.out.println(equipId);
}
String insertString1 = "INSERT INTO used_equipment"
+ "(item_id, eqp_id, qty) VALUES"
+ "(?,?,?)";

Related

get data (single value) from ksoap to andorid through webservice

final String SOAP_ACTION = "http://tempuri.org/get_data2";
final String OPERATION_NAME = "get_data2";
final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
final String SOAP_ADDRESS = "****";
final String req_no, req_date, bolnumber, container_no, current_loc, truck_no;
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsString = (SoapObject)envelope.getResponse();
Log.d("-----------------------", resultsString.getProperty("emp_name").toString());
tv.setText(resultsString.getPropertyCount());
}
catch (Exception exception)
{
exception.printStackTrace();
tv.setText(exception.toString());
}

Stream PDF Byte array from WebAPI to browser

I'm working in C#.net in a WebAPI...
I have...
WebAPI Controller...
public class GetSMBController : ApiController
{
public HttpResponseMessage GET(int AgencyID, string UserName)
{
var Pdfs = new HttpResponseMessage();
Pdfs = Utilities.Reporting.CreateStandardMapBooklet(AgencyID,UserName);
return Pdfs;
}
}
That calls a method...
public static HttpResponseMessage CreateStandardMapBooklet(int AgencyID, string userName)
{
string baseDataPath = #"\\dvfmweb4\\arcgisserver\basedata\";
string tempDataPath = #"\\dvfmweb4\arcgisserver\tempGrowerData\";
string unitTestSession = "UnitTestSession";
int ShadeType = 1;
bool isInImagery = false;
double MaxSceneSize = 1.5;
bool ScaleBar = true;
int MapSettingID = 0;
bool OverallPage = false;
bool OverallImagery = false;
bool IsRecordKeepingSheet = false;
int RecordKeepingSheetID = 0;
int TemplateID = 1480;
RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport _Pdfs = new RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport(
baseDataPath,
tempDataPath,
unitTestSession,
AgencyID,
ShadeType,
isInImagery,
MaxSceneSize,
ScaleBar,
MapSettingID,
TemplateID,
OverallPage,
OverallImagery,
false,
RecordKeepingSheetID,
userName,
true);
PDF testPDF = new PDF();
byte[] test = null;
try
{
List<RCIS.Mapping.MapDomain.Layout.CreatePdfResponse> pdf = _Pdfs.CreateReports();
foreach (var item in pdf)
{
//PDFInfo info = new PDFInfo();
//info.PdfBytes = item.PdfBytes;
testPDF.Report = item.PdfBytes;
test = item.PdfBytes;
}
}
catch(Exception e)
{
}
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(test)
};
response.Content = new ByteArrayContent(test);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
{
FileName = String.Format(AgencyID + userName + DateTime.Now.ToString("MMMddyyyy_HHmmss"))
};
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = new TimeSpan(0, 0, 60) // Cache for 30s so IE8 can open the PDF
};
return response;
}
Sorry for some of the commented out stuff and goofy variable names...I'm just trying to see if this is a viable thing.
the test object and HttpResponse message Content ARE populated but
I'm receiving this error when I call this from a browser...
This XML file does not appear to have any style information associated with it. The document tree is shown below.
An error has occurred.
Value cannot be null. Parameter name: content
System.ArgumentNullException
at System.Net.Http.ByteArrayContent..ctor(Byte[] content) at MappingServicesWebAPI.Utilities.Reporting.CreateStandardMapBooklet(Int32 AgencyID, String userName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Utilities\Reporting.cs:line 92 at MappingServicesWebAPI.Controllers.GetSMBController.GET(Int32 AgencyID, String UserName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Controllers\MappingController.cs:line 143 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.b__c(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.b__4() at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)

SQL Server Reporting - Credentials

I have been working on SQL Server Reporting Services 2008, and i am connecting to report server from asp.net using below code:
ReportExecutionService rs = new ReportExecutionService();
System.Net.CredentialCache.DefaultNetworkCredentials.Domain = ConfigurationManager.AppSettings["Domain"].ToString();
System.Net.CredentialCache.DefaultNetworkCredentials.UserName = ConfigurationManager.AppSettings["UserName"].ToString();
System.Net.CredentialCache.DefaultNetworkCredentials.Password = ConfigurationManager.AppSettings["Password"].ToString();
rs.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
// Render arguments
byte[] result = null;
string reportpath = reportPath;
string format = "PDF";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string encoding;
string mimeType;
string extension;
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = reportParameterBidName.Trim();
parameters[0].Value = reportParameterBidValue.Trim();
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportpath, historyID);
rs.SetExecutionParameters(parameters, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
return result;
}
catch (SoapException e)
{
return null;
}
Now it works well with my local server, when i upload it to final server it does not work and throws unable to connect error. If i use VPN and use same credentials then too it is working.
Please advise on this.

Returning a specific value from a database ASP.NET/C#

My question involves returning a specific value from a table in a database. I want to have it where after you login, it displays the name of the user's first and last name.
The table looks like this.
Person
UID(PK), FName, LName, Uname, Upass
How do I return just the Fname and LName so I can place it in a label?
Here is my current code. Keep in mind this is for the master page.
string strConn = WebConfigurationManager.ConnectionStrings["cloud2"].ConnectionString;
protected void btnlogin2_Click(object sender, EventArgs e)
{
string strCmd = "Select * From Person Where uname = #uname and upass = #upass";
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand(strCmd, objConn);
objCmd.Parameters.AddWithValue("#uname", txtusername.Text);
objCmd.Parameters.AddWithValue("#upass", txtpassword.Text);
using (objConn)
{
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
if (objDR.HasRows)
{
btnlogin2.Visible = false;
txtusername.Visible = false;
txtpassword.Visible = false;
Response.Redirect("member.aspx");
lblLogin.Text = "Logged in as: Test " ; //Display login name?
}
else
{
btnlogin2.Text = "Failed";
}
}
}
First I'd refactor your logic a bit to maintain UI VS database calls a bit separate. Secondly refactor your code to retrieve first and last name that uses code for your connection string, username, password, and outputs firstname and lastname.
string firstName, lastName;
if(ValidateUser(txtusername.Text, txtpassword.Text, out firstName, out lastName)
{
//put your UI Logic and redirect in here
lblLogin.Text = "Welcome: " + firstName + " " + " lastName;
}
else
{
//login faild code
}
private bool ValidateUser(string strConn, string username, string password, out string firstName, out string lastName)
{
firstName = string.Empty;
lastName = string.Empty;
using (var con = new SqlConnection(strConn))
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "Select * From Person Where uname=#uname and upass=#upass";
cmd.Parameters.AddWithValue("#uname", username);
cmd.Parameters.AddWithValue("#upass", password);
con.Open();
using (var r = cmd.ExecuteReader())
{
if (r.Read())
{
firstName = r["FName"].ToString();
lastName = r["LName"].ToString();
return true;
}
else
{
return false;
}
}
}
}
I would do three things:
separate your UI logic from the database logic - don't access your database directly in the middle of a button_Click event handler......
if you only need first and last name, then only select those two columns from the table!
put all the disposable objects like SqlConnection, SqlCommand, SqlDataReader into using(...) {...} blocks so that they will be properly disposed after use
So my code would look something like this:
UI layer:
protected void btnlogin2_Click(object sender, EventArgs e)
{
// call the database layer to get the first and last name
FirstAndLastName data = GetFirstAndLastName(txtusername.Text, txtpassword.Text);
if (data != null) // something was returned - show it
{
lblLogin.Text = string.Format("You're logged in as {0} {1}",
data.FirstName, data.LastName);
}
else
{
lblLogin.Text = "Not logged in....";
}
}
Database layer:
string strConn = WebConfigurationManager.ConnectionStrings["cloud2"].ConnectionString;
internal class FirstAndLastName
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
protected FirstAndLastName GetFirstAndLastName(string userName, string password)
{
FirstAndLastName result = null;
// if you only need FName und LName - then only select those two columns!
// don't just use SELECT * all the time because it's easy and because you're lazy
string strCmd = "SELECT FName, LName FROM dbo.Person WHERE uname = #uname AND upass = #upass";
// wrap everything into using blocks
using(SqlConnection objConn = new SqlConnection(strConn))
using(SqlCommand objCmd = new SqlCommand(strCmd, objConn))
{
objCmd.Parameters.AddWithValue("#uname", userName);
objCmd.Parameters.AddWithValue("#upass", password);
objConn.Open();
using(SqlDataReader objDR = objCmd.ExecuteReader())
{
if (objDR.Read())
{
result = new FirstAndLastName();
result.FirstName = objDR.GetString(objDR.GetOrdinal("FName"));
result.LastName = objDR.GetString(objDR.GetOrdinal("LName"));
}
}
}
return result;
}
string Name=objDR ["FName"].ToString() + ["LName"].ToString()
lblLogin.Text = "Logged in as:"+Name
You can read the instance of SqlDataReader in following way:
WebConfigurationManager.ConnectionStrings["cloud2"].ConnectionString; protected void btnlogin2_Click(object sender, EventArgs e) {
string strCmd = "Select * From Person Where uname=#uname and upass=#upass";
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand(strCmd, objConn);
objCmd.Parameters.AddWithValue("#uname", txtusername.Text);
objCmd.Parameters.AddWithValue("#upass", txtpassword.Text);
using (objConn)
{
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
if (objDR.Read())
{
string fName= (string)objDR["FName"];
string lName= (string)objDR["LName"];
btnlogin2.Visible = false;
txtusername.Visible = false;
txtpassword.Visible = false;
Response.Redirect("member.aspx");
lblLogin.Text = "Logged in as: Test "+fName+" "+lName; //Display login name?
}
else
{
btnlogin2.Text = "Failed";
}
}
}
Is your question how to return just the data you want from the query, or how to access it from the datareader?
It sounds like you might want ExecuteScalar(), and you can combine the fname and lastname fields in the query so you can just pull the one result:
string strCmd = "Select Fname + ' ' + LName From Person Where uname=#uname and upass=#upass";
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand(strCmd, objConn);
objCmd.Parameters.AddWithValue("#uname", txtusername.Text);
objCmd.Parameters.AddWithValue("#upass", txtpassword.Text);
using (objConn)
{
objConn.Open();
var username = objConn.ExecuteScalar() as string;
if (!string.IsNullOrEmpty())
{
btnlogin2.Visible = false;
txtusername.Visible = false;
txtpassword.Visible = false;
Response.Redirect("member.aspx");
lblLogin.Text = "Logged in as: " + username ; //Display login name?
}
Edit: Just noticed a detail... you're setting lblLogin.Text after redirecting... so not thinking anyone's going to see it anyway. Could add it to the querystring though and display it on member.aspx...
You can do something like
lblLogin.Text = "Logged in as: " + objDR.GetString(dr.GetOrdinal("FName")) + " " + objDR.GetString(dr.GetOrdinal("LName"));
If memory serves, you probably also need to first call objDR.Read(); to start iterating over the datareader.

WCF Service Issues with Java Client

This is an interesting problem, and I will do my best to explain. If you have any questions, please ask.
I have written a WCF service that is suppose to communicate with a JAVA client. This service was created via contract first from a WSDL. Now, according to the WCF test client everything works, even testing on a PHP client works as well. But when it comes to the Java client, the request messages and subsequent response messages fail to return: I get a null object SOAP fault. Here is were I think the problem lies:
According to the XSD and WSDL, I have a DateTime value that I am suppose to take in. This dateTime value from the client is of form: 2012-01-01T12:00:00.00Z. Unfortunately, this input is not valid with the built in .NET datetime. So, to get around this, I changed my code to take in a string datatype, convert that string to a Datetime to send it to the database, get a response from the database in that dateTime and convert it back to a string for the response to return a value that is like the one that was inputted.
I built a logger to check to see if the messages were being sent to and from my wcf service. From that, I have identified that messages from the client were not being received. My only guess is that it is because of the datetime issue.
Is there a way to take in a dateTime datatype in the format: 2012-01-01T12:00:00.000Z? If i can, then that will mean that the request will match my datatype and maybe it will work.
Here is some code:
public partial class findSeatsRequest
{
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=0, Name="departAirport")]
public string DepartAirport;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=1, Name="arriveAirport")]
public string ArriveAirport;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=2, Name="earliestDepartTime")]
public string EarliestDepartTime;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=3, Name="latestDepartTime")]
public string LatestDepartTime;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=4, Name="minimumSeatsAvailable")]
public int MinimumSeatsAvailable;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=5, Name="maximumFlightsToReturn")]
public int MaximumFlightsToReturn;
public findSeatsRequest()
{
}
public findSeatsRequest(string departAirport, string arriveAirport, string earliestDepartTime, string latestDepartTime, int minimumSeatsAvailable, int maximumFlightsToReturn)
{
this.DepartAirport = departAirport;
this.ArriveAirport = arriveAirport;
this.EarliestDepartTime = earliestDepartTime;
this.LatestDepartTime = latestDepartTime;
this.MinimumSeatsAvailable = minimumSeatsAvailable;
this.MaximumFlightsToReturn = maximumFlightsToReturn;
}
}
public partial class findSeatsResponse
{
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=0, Name="flight")]
[XmlElementAttribute("flight")]
public System.Collections.Generic.List<flightType> Flight;
public findSeatsResponse()
{
}
public findSeatsResponse(System.Collections.Generic.List<flightType> flight)
{
this.Flight = flight;
}
}
public virtual findSeatsResponse findSeats(findSeatsRequest request)
{
string departAirport = request.DepartAirport;
string arriveAirport = request.ArriveAirport;
string earliestDepartTime = request.EarliestDepartTime;
string latestDepartTime = request.LatestDepartTime;
int minimumSeatsAvailable = request.MinimumSeatsAvailable;
int maximumFlightsToReturn = request.MaximumFlightsToReturn;
SqlCommand cmd = null;
DataSet ds = new DataSet();
List<flightType> flight = new List<flightType>();
EventLogger log = new EventLogger();
findSeatsRequest inValue = new findSeatsRequest();
inValue.DepartAirport = departAirport;
inValue.ArriveAirport = arriveAirport;
inValue.EarliestDepartTime = earliestDepartTime;
inValue.LatestDepartTime = latestDepartTime;
inValue.MinimumSeatsAvailable = minimumSeatsAvailable;
inValue.MaximumFlightsToReturn = maximumFlightsToReturn;
string latestT = inValue.LatestDepartTime.Replace("T", " ");
string latestZ = latestT.Replace("Z", "");
DateTime _latestDepartTime = DateTime.ParseExact(latestZ, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
string earliestT = inValue.EarliestDepartTime.Replace("T", " ");
string earliestZ = earliestT.Replace("Z", "");
DateTime _earliestDepartTime = DateTime.ParseExact(earliestZ, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
log.WriteToDataBase(DateTime.Now, "FindSeats", 1, "This is the request: " + inValue);
//Check Maximum Flights
if (inValue.MaximumFlightsToReturn > 100 | inValue.MaximumFlightsToReturn < 0)
{
throw new FaultException(
"You cannot select more than 100 flights to return, or the maximum flights to return is negative.",
new FaultCode("OutOfRange"));
}
// Check Minimum Seats Available.
if (inValue.MinimumSeatsAvailable < 0)
{
throw new FaultException(
"You minimum seats available cannot be negative.",
new FaultCode("OutOfRange"));
}
// Check for valid Departure Airport
if (departAirport != null && departAirport != "ANY")
{
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string check = "SELECT DepartAirport FROM Flight WHERE DepartAirport='" + departAirport + "'";
cmd = new SqlCommand(check, conn);
cmd.CommandText = check;
SqlDataReader depAirport;
depAirport = cmd.ExecuteReader();
if (depAirport.HasRows == false)
{
throw new FaultException(
"Invalid Airport code used.",
new FaultCode("Invalid Text Entry"));
}
}
finally
{
if (cmd != null)
cmd.Dispose();
}
}
// Check for valid Arrival Airport
if (arriveAirport != null && arriveAirport != "ANY")
{
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string check = "SELECT ArriveAirport FROM Flight WHERE ArriveAirport='" + arriveAirport + "'";
cmd = new SqlCommand(check, conn);
cmd.CommandText = check;
SqlDataReader arrAirport;
arrAirport = cmd.ExecuteReader();
if (arrAirport.HasRows == false)
{
throw new FaultException(
"Invalid Airport code used.",
new FaultCode("Invalid Text Entry"));
}
}
finally
{
if (cmd != null)
cmd.Dispose();
}
}
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
cmd = new SqlCommand("usp_NewFindSeats", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#DepartureAirport", inValue.DepartAirport));
cmd.Parameters.Add(new SqlParameter("#ArrivalAirport", inValue.ArriveAirport));
cmd.Parameters.Add(new SqlParameter("#EarliestDepTime", _earliestDepartTime));
cmd.Parameters.Add(new SqlParameter("#LatestDepTime", _latestDepartTime));
cmd.Parameters.Add(new SqlParameter("#minSeatsAvailable", inValue.MinimumSeatsAvailable));
cmd.Parameters.Add(new SqlParameter("#maxFlightsRequested", inValue.MaximumFlightsToReturn));
using (SqlDataReader sqlReader = cmd.ExecuteReader())
{
while (sqlReader.Read())
{
flightType Flight = new flightType();
Flight.FlightId = sqlReader.GetString(0);
Flight.DepartAirport = sqlReader.GetString(1);
Flight.ArriveAirport = sqlReader.GetString(2);
Flight.DepartTime = sqlReader.GetDateTime(3).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
Flight.ArriveTime = sqlReader.GetDateTime(4).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
Flight.FlightSeatsAvailable = sqlReader.GetInt32(5);
Flight.FlightSeatPriceUSD = sqlReader.GetDouble(6);
flight.Add(Flight);
}
}
For this particular problem, the issue wasn't anything I thought it was in the beginning. Firstly, had to use WrapperNames in my C# code's request operations and the names I used were incorrect.
Secondly, I needed to specify SOAP Body encoding which I had to do within my Interface layer.
[XmlSerializerFormatAttribute(SupportFaults=true, Style=OperationFormatStyle.Document ,Use=OperationFormatUse.Literal)]