I want get image from API to XAMARIN I have API connected to MYSQL if I try get image he give me nothing that is the code.
API
[HttpGet]
public string Plan(string Code, string Company, string Centrale, string Zone)
{
object imag = null;
DataSet ds = new DataSet();
try
{
MySqlConnection con = new MySqlConnection(connectionDB.ConnectionString);
MySqlCommand cmd = new MySqlCommand("select imag from photo inner join taskhis on photo.company = taskhis.company and " +
" photo.zone = taskhis.zone where taskhis.codes ='" + Code + "' and taskhis.company ='" + Company + "' " +
"and taskhis.centrale = '" + Centrale + "' and taskhis.zone = '" + Zone + "' and dates ='" + DateTime.Now.ToString("yyyy/MM/dd") + "' group by taskhis.zone", con);
con.Open();
MySqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
imag = dr[0];
}
//MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//da.Fill(ds);
dr.Close();
con.Close();
}
catch (Exception ex)
{
}
return imag.ToString() ;
}
connection method
string MainUri = "http://192.168.1.25:5873/api/C1NET/";
public async Task<string> GetRequest(string uri)
{
string Tache = "";
var client = new RestClient(MainUri);
var request = new RestRequest(uri);
var response = client.Execute(request);
return response.Content;
}
MainPage
string[] item = plan.urTask.Split(';');
VPNConnector VP = new VPNConnector();
string Result = VP.GetRequest("Plan?Code=" + item[4]+ "&Company="+item[0]+ "&Centrale="+item[1]+ "&Zone="+item[2]).Result;
byte[] image = Encoding.ASCII.GetBytes(Result);
MemoryStream ms = new MemoryStream(image);
IMAGES.Source = ImageSource.FromStream(() => ms);
please if someone can help me to fix my code that can be great thank you
Related
I created an Android app like social media app. I'm using ASP.NET web services for fetching data with JSON or process data like INSERT, UPDATE, DELETE. And I'm using MySQL database.
Number of active users is about 2,5k and daily average is 1,5k.
Anyway, when I control process list with "show processlist;" on phpMyAdmin , there are a lot of process; some processes has Sleep command value. So this situation gets errors like decreasing app speed and some times "max_user_connections".
So, I closed all connections after completing process of database on Web Service, but still have that issue or errors.
[WebMethod]
public string ABC(int x, string y)
{
using (con = new MySqlConnection(conString))
{
List<Profile> result= new List<Profile>();
result.Add(new Profile
{
posts= ""
});
List<ClassA> resultA= new List<ClassA>();
query= "SELECT COUNT(FollowId) FROM Followings WHERE FUserId = " + x;
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
string count = "0";
while (dr.Read())
{
count = dr[0].ToString();
}
dr.Close();
con.Close();
query= "SELECT COUNT(FollowId) FROM Followings WHERE FollowingUserId = " + x;
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
string count2 = "0";
while (dr.Read())
{
count2 = dr[0].ToString();
}
dr.Close();
con.Close();
query= "SELECT .... FROM Posts WHERE UserId = " + x+ " ORDER BY PostId DESC LIMIT 30";
con.Open();
cmd = new MySqlCommand(query, con);
dr = cmd.ExecuteReader();
int i;
int count3 = 0;
while (dr.Read())
{
count3++;
i = 0;
resultA.Add(new ClassA
{
postId = Convert.ToInt32(dr[i]),
postUrl = dr[++i].ToString(),
... = Convert.ToInt32(dr[++i])
});
}
dr.Close();
con.Close();
string json = "";
if (resultA.Count > 0)
{
json = JsonConvert.SerializeObject(resultA);
}
result[0].posts = json;
json = "";
if (result.Count > 0)
{
json = JsonConvert.SerializeObject(result);
}
return json;
}
}
It's any example of my web methods. Where do I mistake ?
Thanks for replies.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Data;
using System.Configuration;
Unable to correctly store the file path
public partial class UploadedFile : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=cook;Initial Catalog=MIS;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
private void StartUpLoad()
{
//get the file name of the posted image
string fileName = FileUpload1.FileName.ToString();
//now we will set the image path
string filePath = "ImageStorage/" + fileName;
//then save it to the folder
FileUpload1.SaveAs(Server.MapPath(filePath));
//now get the size in bytes of the file
//int fileSize = FileUpload1.PostedFile.ContentLength;
//validate the posted file before saving
if (FileUpload1.PostedFile != null && FileUpload1.FileName != "")
{
if (FileUpload1.PostedFile.ContentLength > 8120)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);
}
else
{
//save the file
//call the method to execute insertion of data to the database
ExecuteInsert(filePath);
Label.Text = "File" + fileName + "Successfully uploaded";
}
}
}
private string GetConnectionString()
{
//sets the connection string from web.config
return
System.Configuration.ConfigurationManager.ConnectionStrings["MyDataEntries"].ConnectionString;
}
private void ExecuteInsert(string path)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO JobPortalDatabase (FirstName,LastName,StreetAddress,EmailAddress,ContactNumber,PositionAppliedFor,NameoftheCompany,AddressofCompany,NameofSupervisor,EnterContactNumberofSupervisor,EmailAddressofSupervisor,DescribeYourDuties,NameoftheCompany1,AddressofCompany1,NameofSupervisor1,EnterContactNumberofSupervisor1,EmailAddressofSupervisor1,DescribeYourDuties1,FilePath,FileName) VALUES ('" + TextBox1.Text + "' , '" + TextBox2.Text + "' , '" + TextBox3.Text + "' , '" + TextBox4.Text + "' , '" + TextBox5.Text + "' , '" + TextBox6.Text + "' , '" + TextBox7.Text + "' , '" + TextBox8.Text + "' , '" + TextBox9.Text + "' , '" + TextBox10.Text + "' , '" + TextBox11.Text + "' , '" + TextBox12.Text + "' , '" + TextBox13.Text + "' , '" + TextBox14.Text + "' , '" + TextBox15.Text + "' , '" + TextBox16.Text + "' , '" + TextBox17.Text + "' , '" + TextBox18.Text + "' , '" + FileUpload1+ "' , '" + FileUpload1.FileName + "')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
//SqlParameter[] param = new SqlParameter[2];
//param[0] = new SqlParameter("#FilePath", SqlDbType.VarChar, 50);
//param[0].Value = path;
//for (int i = 0; i < param.Length; i++)
//{
// cmd.Parameters.Add(param[i]);
//}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert error";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
StartUpLoad();
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("PersonalInformation.aspx");
}
}
You are missing the FilePath property in your INSERT statement.
Incorrectly, you have + FileUpload1+ by itself (in the second last item)
You need a function or property call that returns a String for this item like
+ FileUpload1.FilePath +
or
+ IO.Path(FileUpload1.FileName) +
I have two tables in the database:
Login (LID,UName,UPasword,UserType_ID)
UserType(UserType_ID,UserType)
I need to validate username and usertype and create a session variable for UserName(UName).
Below is the code which I try but it shows me error
Error 58 The type or namespace name 'UserInformation' could not be found (are you missing a using directive or an assembly reference?)
CODE
public string LogOn(UserInformation objLogOnUserInformation)
{
// ConnectionManager conCm = new ConnectionManager();
try
{
MySqlConnection con = conn.Open();
MySqlCommand cmd, cmdOne;
MySqlDataReader dr;
// SqlDataReader dr;
string _str = "U";
cmd = new MySqlCommand("select LID from Credentials", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
//checking user name is present in database
if (dr.GetValue(0).ToString() == objLogOnUserInformation.UserId)
{
dr.Close();
//retriving Password for the existing user
cmd = new MySqlCommand("select Pasword from login where LID='" + objLogOnUserInformation.UserId + "'", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
//checking the password is matching with the database
if (dr.GetValue(0).ToString() == objLogOnUserInformation.Password)
{
dr.Close();
cmd = new MySqlCommand("select UserType_ID from login where LID='" + objLogOnUserInformation.UserId + "'", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
//checking user type
if (dr.GetValue(0).ToString() == _str)
{
dr.Close();
cmdOne = new MySqlCommand("select UName from login where LID='" + objLogOnUserInformation.UserId + "'", con);
dr = cmdOne.ExecuteReader();
dr.Read();
objLogOnUserInformation.SessionUserName = dr.GetValue(0).ToString();
dr.Close();
//if usertype is customer, U is returned
Response.Redirect("gallery.aspx");
}
else
{
dr.Close();
cmdOne = new MySqlCommand("select UName from login where LID='" + objLogOnUserInformation.UserId + "'", con);
dr = cmdOne.ExecuteReader();
dr.Read();
objLogOnUserInformation.SessionUserName = dr.GetValue(0).ToString();
dr.Close();
//If usertype is Admin, A is returned
Response.Redirect("Reports.aspx");
}
}
}
else
{
return " Either User Name or Password is not Valid";
}
}
}
}
}
catch
{
}
}
i try to build signup code using asp.net and mysql
code is
protected void Button2_Click(object sender, EventArgs e)
{
try
{
string MyConnection2 = "Server=xxx; Port=3306 ; Uid=xxx; pwd=xxx;Database=maintainance";
string Query = "INSERT INTO `login`(`UName`, `UPasword`,`UserTypeID`,`Email`)VALUES('" + this.TextBox1.Text + "','" + this.TextBox2.Text + this.DropDownList1.SelectedValue +this.TextBox3.Text+ "');";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
Label3.Text = ("Your Data saved successfully");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch
{
Label3.Text = ("Data saved failed");
}
}
but it shows me Data saved failed ... where is the error and how i correct this?
You have to pass value according to column before VALUES
string Query = "INSERT INTO `login`(`UName`, `UPasword`,`UserTypeID`,`Email`) VALUES ('" + this.TextBox1.Text + "','" + this.TextBox2.Text+"', '"+this.DropDownList1.SelectedValue+"' ,'"+this.TextBox3.Text+ "');";
I currently have a query string for the jQuery Autocomplete plug in but should be using a stored procedure instead. Can anyone help me convert? It seems to not be working when I do it.
Original ASHX
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["Rollup2ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
//cmd.CommandText = "select NUID from T_USER where " +
//"NUID like #SearchText + '%'";
cmd.CommandText = "select rtrim(NUID) NUID, rtrim(FNAME) FNAME, rtrim(LNAME) LNAME from T_USER where NUID like #SearchText + '%' OR FNAME like #SearchText + '%' OR LNAME like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["NUID"].ToString() + " ").Append(sdr["FNAME"].ToString() + " ").Append(sdr["LNAME"].ToString() + " ")
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
New ASHX for stored procedure:
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["Rollup2ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
//cmd.CommandText = "select NUID from T_USER where " +
//"NUID like #SearchText + '%'";
cmd.CommandText = "SP_AUTOCOMPLETE";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Parameters.Add(new SqlParameter("#SearchText", SqlDbType.VarChar));
cmd.Parameters["#SearchText"].Value = prefixText;
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["NUID"].ToString() + " ").Append(sdr["FNAME"].ToString() + " ").Append(sdr["LNAME"].ToString() + " ")
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
Stored procedure:
#SearchText VARCHAR(255)
AS
BEGIN
SET NOCOUNT ON;
SELECT RTRIM(NUID) NUID, RTRIM(FNAME) FNAME, RTRIM(LNAME) LNAME
FROM T_USER
WHERE NUID like #SearchText + '%' OR FNAME like #SearchText + '%' OR LNAME like #SearchText + '%'
Thanks!
You need to set the SqlCommand 'CommandType' to 'CommandType.StoredProcedure'.
cmd.CommandType = CommandType.StoredProcedure;
I would also recommend using a prefix other than 'sp_'. That is what Microsoft used for their system procedures and you might accidentally overwrite one you want to keep around. :)
This is how I generate parameters:
public static SqlParameter GetParameter(string parameterName, object value, SqlDbType type, int size)
{
if (value == null)
{
value = DBNull.Value;
}
if (size <= 0 && type == SqlDbType.VarChar)
{
switch (type)
{
case SqlDbType.VarChar:
size = 8000;
break;
case SqlDbType.NVarChar:
size = 4000;
break;
}
}
SqlParameter parameter = new SqlParameter(parameterName, type, size);
parameter.Value = value;
parameter.IsNullable = true;
return parameter;
}
And I just do this.
cmd.Parameters.Add(GetParameter("#SearchText", searchText, SqlDbType.VarChar));