Am trying to use Web Api to output some json within an ASP.Net web forms web application.
Below is my get method:
public string Get()
{
String paramOne = "paramOneValue";
using (var conn = new SqlConnection(sqlConStr))
{
try
{
var command = new SqlCommand("getMyList", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#paramOne", paramOne);
conn.Open();
ArrayList result = new ArrayList();
var reader = command.ExecuteReader();
while (reader.Read())
{
result.Add(new
{
id = reader[0],
val= reader[1],
val1= reader[2]
});
}
return JsonConvert.SerializeObject(result);
}
catch (SqlException sxp)
{
string msg = Resource.fetchError + " " + sxp.Message;
return "error";
}
}
}
and below is the Response from firebug when the method is called within an aspx page:
"[{\"id\":1,\"val\":\"valFromDB\",\"val1\":\"valOneFromDB\"},{\"id\":2,\"val\":\"row2ValFromDB\",\"val1\":\"row2ValOneFromDB\"}]"
but the weird thing is under JSON tab individual characters are being returned as in below:
0 "["
1 "{"
2 """
3 "i"
4 "d"
Anything am missing?
Related
Below is my j query function uploadPicOne()
$(function() {
var allVals = []; //for global check boxes
$(document).on("click", ".click-action-for-event", function(e) {
debugger;
//current i am calling this method for upload picture
uploadPicOne();
})
});
var uploadPicOne = function() {
navigator.camera.getPicture(updateProfilePicService_one, onFail, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
encodingType: navigator.camera.EncodingType.JPEG,
sourceType: navigator.camera.PictureSourceType.CAMERA
});
}
var updateProfilePicService_one = function(fileUri) {
SpinnerPlugin.activityStart("Loading...", { dimBackground: true });
var options = new FileUploadOptions();
options.fileKey = "image";
options.fileName = fileUri.substr(fileUri.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.params = {
"status": "B2",
"iTrainingId": $("#iTrainingId_currentprogramme").val(),
"session_date": $("#iTrainingDate_currentprogramme").val(),
};
options.headers = {
"X-Api-Key": localStorage.getItem("auth_key"),
};
options.chunkedMode = false;
var ft = new FileTransfer();
console.log(options);
ft.upload(fileUri, base_url + "uploadpic", win, fail, options);
}
Below is my webservice not sure its work for phone gap
[WebMethod]
public string uploadpic()
{
string msg = "";
using (SqlConnection con = new SqlConnection(strConn))
{
SqlCommand cmd = new SqlCommand("App_Service", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
var request = HttpContext.Current.Request;
IEnumerable<string> headers = request.Headers.GetValues("X-Api-Key");
var auth_key = headers.FirstOrDefault();
// HttpPostedFile file = HttpContext.Current.Request.Files["image"];
HttpPostedFile file = HttpContext.Current.Request.Files[0];
string saveFile = file.FileName;
file.SaveAs(Server.MapPath("/Trainer_Images/" + saveFile));
cmd.Parameters.AddWithValue("#Paravalue", "14");
cmd.Parameters.AddWithValue("#Value", saveFile);
cmd.Parameters.AddWithValue("#Value1", auth_key);
cmd.Parameters.AddWithValue("#Value2", "0");
cmd.Parameters.AddWithValue("#Value3", "0");
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
con.Dispose();
//Context.Response.Write(JSONResult);
//return d1.data;
/// msg = "File uploaded";
}
catch (Exception ex)
{
msg = "Could not upload file: " + ex.Message;
}
}
return msg;
}
I need to know my web service is correct or wrong. I am not able to run my webservice also, my requirement is send captured image file to my asp.net web-service and save to database, please help me to achieve my requirement or any suggestion or any examples related my need. The above jquery functions are working fine because the same app using into different application.
Today I have checked this code is not working through mobile showing loading after taking photo from mobile.
I think you are making asp.net web service (asmx).It needs ajax enabled to be called from JavaScript.
For your project i think you should use Asp.net mvc API
check this article.
https://www.c-sharpcorner.com/article/uploading-image-to-server-using-web-api-2-0/
I have a DB table with 7 columns and 10rows. Each row is provided an input parameter to a web api call, and the response returned by the api, is inserted into a table. My problem is, the Parallel.Foreach is not producing the same result as the regular ForEach.
Specifically, if 1st row has address as "123 Jump Street Arizona Us", I get a response from web api with the standardized address as "123 Jump Street Arizona USA", like that I have 10 different rows with 10 different input address. However, the output response I get from Parallel.Foreach is for the same address repeated 5 times. And the next time i run it, it is a different result altogether
Could someone please point out why this is happening and the potential solution?
Here is my code:
public void Main()
{
// TODO: Add your code here
string query = "SELECT ADDR_LINE_ONE,ADDR_LINE_TWO,ADDR_LINE_THREE,COUNTRY,PROVINCE,CITY_NAME,POSTAL_CODE FROM Addresstestpoc";
try
{
using (OleDbConnection connection = new OleDbConnection(conn))
{
OleDbCommand command = new OleDbCommand(query, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
int i = reader.FieldCount;
bool b = reader.HasRows;
Parallel.ForEach(GetFromReader(reader), record =>
{
//AddrOne = record[0].ToString();
string AddrOne = record.GetString(0);
string AddrTwo = record.GetString(1);
string AddrThree = record.GetString(2);
string Country = record.GetString(3);
string Province = record.GetString(4);
string City = record.GetString(5);
string PostalCode = record.GetString(6);
string Sender = "G";
//sqlk = (string)Dts.Variables["User::sqlconn"].Value;
standardizeAddressReturn result;
string data = string.Empty;
string queri;
MDMStandardizeAddressService web = new MDMStandardizeAddressService();
try
{
result = web.standardizeAddress(AddrOne, AddrTwo, AddrThree, City, Province, PostalCode, Country, Sender);
data = SerializeToXml(result);
queri = "insert into [CPM].[dbo].[AddressResponsetest_new] values ('" + data + "')";
//MessageBox.Show(data);
insertintosql(queri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
});
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
IEnumerable<IDataRecord> GetFromReader(IDataReader reader)
{
while (reader.Read()) yield return reader;
}
I think you need another approach. Command and DataReader are not thread safe. Even if DataReader was thread safe it is a forward only cursor so it is not going to be faster.
I recommend a producer consumer pattern (.e.g BlockingCollection). In the consumer is where you can parallel process the
MDMStandardizeAddressService web = new MDMStandardizeAddressService();
try
{
You could probably use tasks, await, asynch for producer consumer.
An easier approach might be to create a class for properties and put that in a List and then just Read that List. This will happen if a fraction of a second.
You can then parallel process the List.
Stub code:
public class WebMailer
{
public void process()
{
List<Addr> Addrs = new List<Addr>();
SqlCommand command = new SqlCommand();
using (var reader = command.ExecuteReader())
{
using (SqlDataReader r = command.ExecuteReader())
{
Addrs.Add(new Addr(r.GetString(0), r.GetString(1)));
}
}
foreach(Addr addr in Addrs) // can use parallel here
{ }
}
}
s
I want to display data from my remote sql-server in my android app. I am using web-service. I am able to connect and to insert but not to display with JSON.
This is the code from web-service
public DataTable RequestDetails(string request_name)
{
DataTable requestDetails = new DataTable();
requestDetails.Columns.Add(new DataColumn("Request ID", typeof(String)));
requestDetails.Columns.Add(new DataColumn("Date", typeof(String)));
if(dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "select ID_Requests,request_date from Requests where request_by='" + request_name + "'";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
requestDetails.Rows.Add(reader["Request ID"], reader["Date"]);
}
}
reader.Close();
dbConnection.Close();
return requestDetails;
}
This is the android code:
protected class AsyncLoadDeptDetails extends
AsyncTask<DeptTable, JSONObject, ArrayList<DeptTable>> {
ArrayList<DeptTable> deptTable = null;
#Override
protected ArrayList<DeptTable> doInBackground(DeptTable... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.RequestDetails(params[1].getName());
JSONParser parser = new JSONParser();
deptTable = parser.parseDepartment(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadDeptDetails", e.getMessage());
}
return deptTable;
}
#Override
protected void onPostExecute(ArrayList<DeptTable> result) {
// TODO Auto-generated method stub
for (int i = 0; i < result.size(); i++) {
data.add(result.get(i).getNo() + " " + result.get(i).getName());
}
adapter.notifyDataSetChanged();
Toast.makeText(context, "Loading Completed", Toast.LENGTH_SHORT).show();
}
}
And the JSONParser code:
public ArrayList<DeptTable> parseDepartment(JSONObject object)
{
ArrayList<DeptTable> arrayList=new ArrayList<DeptTable>();
try {
JSONArray jsonArray=object.getJSONArray("Value");
JSONObject jsonObj=null;
for(int i=0;i<jsonArray.length();i++)
{
jsonObj=jsonArray.getJSONObject(i);
arrayList.add(new DeptTable(jsonObj.getInt("Request ID"), jsonObj.getString("Date")));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("JSONParser => parseDepartment", e.getMessage());
}
return arrayList;
}
I would use Fiddler or something similar and have a look at the data being returned. I've always had trouble returning a .NET Datatable from a service, so if it were me I would convert the datatable to JSON before sending. This has been discussed on several posts before, but here's a great answer:
https://stackoverflow.com/a/17398078/3299157
I have an ASP.NET web api that receives web requests and returns Json data.
browsing to this URL:
http://1.2.3.4/api1/api/values/mypartname will return the following json string:
{
\"PartName\": \"mypartname\",
\"PartDes\": \"53.6X53.6APA/ALIM1NOTPAK\",
\"PartLocation\": \"A36\"
}
but when sending a part name that contains spaces or quotes like this: http://1.2.3.4/api1/api/values/my part na"me i get a 404 - File or directory not found. error.
I'm consuming the json with a .NET 4 Console application like so:
static void Main(string[] args)
{
try
{
string partName = "TAPE 56 3M 3/4\"";
WebRequest wr = WebRequest.Create("http://1.2.3.4/api1/api/values/" +
HttpUtility.UrlEncode(partName));
wr.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse hwr = (HttpWebResponse)wr.GetResponse();
Stream dataStream = hwr.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string json = reader.ReadToEnd();
//some json parsing function
des(json);
reader.Close();
dataStream.Close();
hwr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadKey();
}
}
the exception is thrown at this line:HttpWebResponse hwr = (HttpWebResponse)wr.GetResponse();
and the exception message is: The remote server returned an error: (404) Not Found.
Am i doing something wrong with the mypartname? I also tried to manually replace the problematic characters according to this: HTML URL Encoding Reference and using this function:Uri.EscapeDataString(partName) but with no luck.
EDIT
this is the routeConfig definition:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
and the api GET method:
// GET api/values/5
public string Get(string id)
{
List<dummy> dummies = new List<dummy>();
string con = "user id=sa;" +
"password=1234" +
"server=someServer\\someInstance;" +
"database=game; " +
"connection timeout=30";
//SqlConnection sqlConn = new SqlConnection(con);
using (SqlConnection sqlconn = new SqlConnection(con))
{
sqlconn.Open();
StringBuilder sb = new StringBuilder();
sb.Append("SELECT PART.PARTNAME,PART.PARTDES, PARTPARAMA.LOCATION ");
sb.Append("FROM PART LEFT JOIN PARTPARAMA ");
sb.Append("ON PART.PART = PARTPARAMA.PARTPARAM ");
sb.Append("WHERE PART.PARTNAME = #part");
using (SqlCommand cmd = new SqlCommand(sb.ToString(), sqlconn))
{
cmd.Parameters.AddWithValue("part", id);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
dummies.Add(new dummy
{
PartName = sdr.IsDBNull(0) ? "Unknown" : sdr.GetString(0),
PartDes = sdr.IsDBNull(1) ? "Unknown" : sdr.GetString(1),
PartLocation = sdr.IsDBNull(2) ? "Unknown" : sdr.GetString(2)
});
}
}
}
if (dummies.Count() > 0)
{
string json = JsonConvert.SerializeObject(dummies[0]);
return json;
}
else
{
string json = JsonConvert.SerializeObject(null);
return json;
}
EDIT 10 Apr 2015:
I am leaving this answer here for anyone who finds it in a search, however as Kevin states below and Scott Hanselman says here:
[UrlPathEncode] doesn't do what you think it does ... This method was
very specific, poorly named, and is now totally obsolete.
I think your problem has more to do with the forward slash in the part name.
You can handle the spaces and quotes using
HttpUtility.UrlPathEncode(partName)
instead of HttpUtility.UrlEncode(partName).
Handling the forward slash is more problematic. See this post for more details.
I am new to MySQL database, I am using Visual Studio C# to connect to my database. I have got a following select method. How can I run it to check if it is working?
EDITED The open and close connection methods
//Open connection to database
private bool OpenConnection()
{
try
{
// connection.open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server.");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
Select method which is in the same class as the close and open connection as shown above
public List<string>[] Select()
{
string query = "SELECT * FROM Questions";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
list[3] = new List<string>();
list[4] = new List<string>();
list[5] = new List<string>();
list[6] = new List<string>();
list[7] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["difficulty"] + "");
list[2].Add(dataReader["qustions"] + "");
list[3].Add(dataReader["c_answer"] + "");
list[4].Add(dataReader["choiceA"] + "");
list[5].Add(dataReader["choiceB"] + "");
list[6].Add(dataReader["choiceC"] + "");
list[7].Add(dataReader["choiceD"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
This method is in a separate class which has got all the database connection settings. Now that I want to call this method from my main class to test it to see if it's working, how can I do this?
You should create an object instance of that DB class and then call the Select() method.
So, supposing that this DB class is named QuestionsDB you should write something like this:
QuestionDB questionDAL = new QuestionDB();
List<string>[] questions = questionDAL.Select();
However, before this, please correct this line
List<string>[] list = new List<string>[8]; // you need 8 lists for your db query
You could check if you have any record testing if the first list in your array list has more than zero elements.
if(questions[0].Count > 0)
... // you have read records.
However, said that, I will change your code adding a specific class for questions and using a list(of Question) instead of an array of list
So, for example, create a class like this
public class Question
{
public string ID;
public string Difficulty;
public string Question;
public string RightAnswer;
public string AnswerA;
public string AnswerB;
public string AnswerC;
public string AnswerD;
}
and change your select to return a List(of Question)
List<Question> list = new List<Question>;
......
while (dataReader.Read())
{
Question qst = new Question();
qst.ID = dataReader["id"] + "";
qst.Difficulty = dataReader["difficulty"] + "";
qst.Question = dataReader["qustions"] + "";
qst.RightAnswer = dataReader["c_answer"] + "";
qst.AnswerA = dataReader["choiceA"] + "";
qst.AnswerB = dataReader["choiceB"] + "";
qst.AnswerC = dataReader["choiceC"] + "";
qst.AnswerD = dataReader["choiceD"] + "";
list.Add(qst);
}
return list;
You can test whether the method works by writing a unit test for it. A good unit testing frame work is Nunit. Before you call this you must create and open a connection to the DB:
//Open connection
if (this.OpenConnection() == true)
{
as the other person said, you will want to fix the lists up.