Json Deserialization - c#

I want to use json to my android project. I am having some problem how to use json with .net. My code :
string stroutput = "";
try
{
string conStr = #"data source=.;database=Kelepir;Integrated Security=True;";
SqlConnection connection = new SqlConnection(conStr);
connection.Open();
string myquery = "select ProductID,ProductName,CategoryName,UnitPrice from Products";
SqlCommand cmd = new SqlCommand(myquery, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var nes = new
{
ProductID = reader["ProductID"].ToString(),
ProductName = reader["ProductName"].ToString(),
CategoryName = reader["CategoryName"].ToString(),
UnitPrice = reader["UnitPrice"].ToString()
};
stroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(nes);
Response.Write(stroutput);
}
}
catch (Exception ex)
{
stroutput = "ERROR : " + ex.Message;
}
But my json has not this marks : ",", and "[ ]".
My output :
{"ProductID":"1","ProductName":"Şeker","CategoryName":"Tatlı","UnitPrice":"20"}
{"ProductID":"2","ProductName":"Kuruyemiş","CategoryName":"Tuzl","UnitPrice":"200"}
{"ProductID":"3","ProductName":"Baklagil","CategoryName":"Sebze","UnitPrice":"100"}
{"ProductID":"4","ProductName":"Bulgur","CategoryName":"Sebze","UnitPrice":"10"}
I want this format to my code :
{ "table_name":
[
{"ProductID":"1","ProductName":"Şeker","CategoryName":"Tatlı","UnitPrice":"20"}, {"ProductID":"2","ProductName":"Kuruyemiş","CategoryName":"Tuzl","UnitPrice":"200"},
{"ProductID":"3","ProductName":"Baklagil","CategoryName":"Sebze","UnitPrice":"100"},
{"ProductID":"4","ProductName":"Bulgur","CategoryName":"Sebze","UnitPrice":"10"}]
}
How I can do this ? Thanks...

give this a shot:
var rowList = new List<object>();
while (reader.Read())
{
var nes = new
{
ProductID = reader["ProductID"].ToString(),
ProductName = reader["ProductName"].ToString(),
CategoryName = reader["CategoryName"].ToString(),
UnitPrice = reader["UnitPrice"].ToString()
};
rowList.Add(nes);
}
var serializeMe = new {table_name = rowList }
stroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(serializeMe );
Response.Write(stroutput);
You are serializing each row. What you want to do is pacakge each row into a colleciton and then serialize the collection as a whole.

Related

ExecuteNonQuery Violation of Primary Key after putting value?

I'm trying to write a CRUD app and I have a problem with the Create method. Program is crashing with error
System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK_Pracownicy'. Cannot insert duplicate key in object 'dbo.Pracownicy'. The duplicate key value is (11).
The statement has been terminated.'
But I can see in my SQL Server that this position is added to Pracownicy table, so I don't know where is a problem. Its look like the error is generated after I put new values to table
class SqlHelper
{
public int RowsLenght { get; set; }
private SqlConnection sqlConnection;
public string Command { get; set; }
public SqlHelper(string connectionString)
{
sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
}
public int Create(string command, SqlParameter []parameters)
{
//wykonanie polecenia na bazie
using var cmd = new SqlCommand(command, sqlConnection);
cmd.Parameters.AddRange(parameters);
ShowTable(cmd);
return cmd.ExecuteNonQuery();
}
public int Read(string command)
{
//wykonanie polecenia na bazie
using var cmd = new SqlCommand(command, sqlConnection);
ShowTable(cmd);
return cmd.ExecuteNonQuery();
}
private int ShowTable(SqlCommand command)
{
var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + "\t" + reader.GetString(2) + " " +
reader.GetString(1) + "\t" + reader.GetString(3));
RowsLenght++;
}
reader.Close();
return RowsLenght;
}
}
class Program
{
static void Main()
{
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder
{
DataSource = #"HAL\MSSERVER",
InitialCatalog = "ZNorthwind",
IntegratedSecurity = true,
ConnectTimeout = 30,
Encrypt = false,
TrustServerCertificate = false,
ApplicationIntent = 0,
MultiSubnetFailover = false
};
var connectionS = connectionString.ConnectionString;
SqlHelper sql = new SqlHelper(connectionS);
var command = "SELECT * FROM dbo.Pracownicy";
sql.Read(command);
command = "INSERT INTO dbo.Pracownicy (IDpracownika, Nazwisko, Imię, Stanowisko) VALUES (#IDpracownika, #Nazwisko, #Imie, #Stanowisko)";
var parameters = SetUpParameters(sql.RowsLenght);
sql.Create(command, parameters);
}
private static SqlParameter[] SetUpParameters(int lenght)
{
//inicjalizacja zmiennych:
Console.WriteLine("Podaj imie nowego pracownika: ");
var fname = Console.ReadLine();
Console.WriteLine("Podaj nazwisko pracownika: ");
var lname = Console.ReadLine();
Console.WriteLine("Podaj stanowisko pracownika: ");
var position = Console.ReadLine();
SqlParameter []param = new SqlParameter[4];
param[0] = new SqlParameter("IDpracownika", lenght + 1);
param[1] = new SqlParameter("Imie", fname);
param[2] = new SqlParameter("Nazwisko", lname);
param[3] = new SqlParameter("Stanowisko", position);
return param;
}
}
Thanks

SQLDataReader bugging while using .Nest() or .Read()

I'm retrieving some information from an MSSQL via SQLDataReader, but while debugging it I notice in some cases the reader clears the result view with the error "Enumeration yielded no results" see the screenshot Before Running passing Read(),
After passing read()
this is my code,the error happens on getActiveUsers() method.
getDatabases() works just fine. could someone help me? cheers
public partial class automation : System.Web.UI.Page
{
SqlConnection con;
static List<ActiveUsers> activeUsers = new List<ActiveUsers>();
protected void Page_Load(object sender, EventArgs e)
{
ASPxGridView1.DataSource = activeUsers.ToList();
}
public List<ActiveUsers> getDatabases()
{
//passing query
string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
//creating connection
string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
con = new System.Data.SqlClient.SqlConnection(sqlconn);
var cmd = new SqlCommand(SqlQuery, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<ActiveUsers> results = new List<ActiveUsers>();
if (reader.Read())
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
con.Close();
return results;
}
public void getActiveUsers()
{
activeUsers.Clear();
List<ActiveUsers> Databases= getDatabases();
SqlConnection conn = new SqlConnection();
string SqlQuery = "select [disabled], [ADMN_Users1].[Record_Id] ,[ADMN_Users].[User_Id] from admn_Users1 inner join [ADMN_Users] on [ADMN_Users1].[record_Id] = [ADMN_Users].[Record_Id] Where [disabled] & 0x2 = 0 ";
for (int i = 0;i < Databases.Count;i++)
{
conn.ConnectionString =
"Data Source=MAXSQLCLUS01;" +
"Initial Catalog=" + Databases[i].ToString()+";"+
"User id=sa;" +
"Password=Max1m1zer;";
var cmd = new SqlCommand(SqlQuery, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int NumberOfUsersCounter = 0 ;
//TODO Select Enabled users
if (reader.Read())
{
while (reader.Read())
{
string user = String.Format("{0}", reader["User_Id"]);
//logic to remove system users
if (user.Equals("master", StringComparison.CurrentCultureIgnoreCase))
{
}
else
if (user.Equals("emailuser", StringComparison.CurrentCultureIgnoreCase))
{
}
else
if (user.Equals("webuser", StringComparison.CurrentCultureIgnoreCase))
{
}
else
{
NumberOfUsersCounter++;
}
}
ActiveUsers newEntry = new ActiveUsers();
newEntry.NumberActiveUsers = NumberOfUsersCounter.ToString();
newEntry.DatabaseName = Databases[i].DatabaseName.ToString();
newEntry.ClientName = Databases[i].ClientName.ToString();
activeUsers.Add(newEntry);
}
conn.Close();
//Add to ActiveUsers list
}
ASPxGridView1.AutoGenerateColumns = true;
ASPxGridView1.DataSource = activeUsers.ToList();
ASPxGridView1.DataBind();
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
getActiveUsers();
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
ASPxGridView1.DataBind();
ASPxGridViewExporter1.Landscape = true;
ASPxGridViewExporter1.FileName = "User Count Report";
ASPxGridViewExporter1.WriteXlsToResponse();
}
}
}
if (reader.Read())
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
use this
if (reader.HasRows)
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
your if Condition is wrong
if(reader.Read()) ==> is Wrong
Read() is not return boolean Value
use HasRows to check rows in SQLDataReader
You are skipping the first result. if (reader.Read()) { while(reader.Read()) {.... Remove the enclosing if, all it does is see if there is a row and retrieve it but then you do not read it, instead you do it again in the if so the first result is always discarded.
public List<ActiveUsers> getDatabases()
{
//passing query
string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
//creating connection
string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
using(con = new System.Data.SqlClient.SqlConnection(sqlconn))
using(var cmd = new SqlCommand(SqlQuery, con))
{
con.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
List<ActiveUsers> results = new List<ActiveUsers>();
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = reader.GetString(0);
company.ClientName = reader.GetString(1);
results.Add(company);
}
}
}
return results;
}
Side notes:
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]) would be better written as company.DatabaseName = reader.GetString(0). The same goes for the next line. No need to use string.Format and you are specifying the columns and order in the query so use the ordinal index so get the native value.
I would recommend you wrap the SqlConnection and SqlDataReader in using blocks to ensure they are closed/disposed after use even in the event of an exception.

Reading Multiple data

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Ontrip _ontrip = new Ontrip(_FNAME);
string _query2 = "select CContactno from CustomerTbl where CUsername = #USERNAME";
string _query3 = "select Price from TransactionTypeTble T join PendingTransTbl P ON P.TransType = T.TransType ";
string _query4 = "select VehicleDescription from DriverTbl D join VehicleSpecTbl V ON D.VehicleType = V.VehicleType";
SqlConnection _sqlcnn = new SqlConnection("Data Source=MELIODAS;Initial Catalog=WeGo;Integrated Security=True");
_sqlcnn.Open();
try
{
SqlDataReader _reader = null;
SqlCommand _cmd = new SqlCommand("Select CFName+' '+CLName from CustomerTbl where CUsername=#USERNAME", _sqlcnn);
SqlParameter _param = new SqlParameter();
_param.ParameterName = "#USERNAME";
_param.Value = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
_cmd.Parameters.Add(_param);
_reader = _cmd.ExecuteReader(); //for displaying users name in the label
while (_reader.Read())
{
_ontrip._txtboxUsername.Text = _reader.GetString(0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
using (SqlCommand _sqlcmd = new SqlCommand(_query2, _sqlcnn))
{
try
{
SqlDataReader _reader = null;
SqlParameter _param = new SqlParameter();
_param.ParameterName = "#USERNAME";
_param.Value = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
_sqlcmd.Parameters.Add(_param);
_reader = _sqlcmd.ExecuteReader(); //for displaying users name in the label
while (_reader.Read())
{
_ontrip._txtboxContact.Text = _reader.GetString(0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Is their a way for me to read the query and display the output, when i run this code their is an error saying that their is already an open data reader associated with the command. I should be displaying multiple data in a textbox
try Call Close when done reading.
_reader.Close();
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Ontrip _ontrip = new Ontrip(_FNAME);
string _query2 = "select CContactno from CustomerTbl where CUsername = #USERNAME";
string _query3 = "select Price from TransactionTypeTble T join PendingTransTbl P ON P.TransType = T.TransType ";
string _query4 = "select VehicleDescription from DriverTbl D join VehicleSpecTbl V ON D.VehicleType = V.VehicleType";
SqlConnection _sqlcnn = new SqlConnection("Data Source=MELIODAS;Initial Catalog=WeGo;Integrated Security=True;MultipleActiveResultSets=True ");
_sqlcnn.Open();
I added MultipleActiveResultSet or MARS

Send JSON through ActiveMQ

I'm trying to send a JSON format through ActiveMQ (C# Console Application), but right now I'm stock in the following:
If I send the direct JSON serialization (as string) the system adds backward slashes "\" to the text, which makes my listener unable to process the information.
I can remove the backward slashes by doing a JToken Parse, but I cannot send the var on ActiveMQ (ITextMessage requests a String, I'm sending a JToken) and of course if I do cast of the JToken to string I found again the backward slashes "\"
Any clue on how I can achieve my goal???
String IP = "172.29.75.43:61616";
String QueuesNameESF = "queue://MES2WMSTVOFFLINE";
try
{
Uri _uri = new Uri(String.Concat("activemq:tcp://" + IP));
IConnectionFactory factory = new ConnectionFactory(_uri);
using (IConnection conn = factory.CreateConnection())
{
using (ISession session = conn.CreateSession())
{
IDestination destination = SessionUtil.GetDestination(session, QueuesNameESF);
using (IMessageProducer producer = session.CreateProducer(destination))
{
SqlConnection dbConnection = new SqlConnection("Integrated Security=false;Data Source=smxsql08svr01;initial catalog=BSS;user id=sa;password=newshamu;Max Pool Size=75000");
SqlConnection internalConnection = new SqlConnection("Integrated Security=false;Data Source=smxsql08svr01;initial catalog=BSS;user id=sa;password=newshamu;Max Pool Size=75000");
String SearchPallet;
SqlCommand cmd = new SqlCommand();
dbConnection.Open();
SearchPallet = "";
SearchPallet = "Select Replace(Replace(Replace((Convert(varchar,GETDATE(),120) + Palletnum),'-',''),' ',''),':','') as 'ID', ";
SearchPallet += "'Y' as 'beFull','ZJ' as 'ext1','' as 'ext2','Y'as 'isCM',Part_Number as 'itemCode',linea as 'line',";
SearchPallet += "Case When len(Part_Number) = 12 then RIGHT(Part_Number,7) else RIGHT(Part_Number,8) end as 'lot',";
SearchPallet += "Palletnum as 'mainPallet',GETDATE() as 'sendTime','BSS' as'sender','8170' as'werks' From Finishgoods ";
//Remove if not test
SearchPallet += "Where PalletNum = #Palletnum GROUP by PalletNum,Part_Number,linea";
cmd.CommandText = SearchPallet;
cmd.Connection = dbConnection;
cmd.Parameters.Add("#Palletnum", SqlDbType.VarChar).Value = "PT01929734";//Pallet;//"PT01929734";
SqlDataReader rdr = cmd.ExecuteReader();
FirstLevel product = new FirstLevel();
if (rdr.Read())
{
//FirstLevel product = new FirstLevel();
product.guid = rdr.GetValue(0).ToString();
product.beFull = rdr.GetValue(1).ToString();
SecondLevel msg = new SecondLevel();
msg.carton = rdr.GetValue(8).ToString();
List<ThirdLevel> serials = new List<ThirdLevel>();
ThirdLevel sn = new ThirdLevel();
String SearchSN = "Select barcodenum as 'serNo',''as 'ext1',''as 'ext2' From Finishgoods where palletnum = #palletnum";
SqlCommand cmd_sn = new SqlCommand();
internalConnection.Open();
cmd_sn.Connection = internalConnection;
cmd_sn.CommandText = SearchSN;
cmd_sn.Parameters.Add("#Palletnum", SqlDbType.VarChar).Value = "PT01929734";
SqlDataReader rdr_sn = cmd_sn.ExecuteReader();
while (rdr_sn.Read())
{
sn.serNo = rdr_sn.GetValue(0).ToString();
sn.ext1 = rdr_sn.GetValue(1).ToString();
sn.ext2 = rdr_sn.GetValue(2).ToString();
serials.Add(sn);
}
rdr_sn.Close();
cmd_sn.Parameters.Clear();
cmd_sn.Dispose();
internalConnection.Close();
msg.serNoMsg = serials;
product.crtonMsg = msg;
product.ext1 = rdr.GetValue(2).ToString();
product.ext2 = rdr.GetValue(3).ToString();
product.isCM = rdr.GetValue(4).ToString();
product.itemCode = rdr.GetValue(5).ToString();
product.line = rdr.GetValue(6).ToString();
product.lot = rdr.GetValue(7).ToString();
product.mainPallet = rdr.GetValue(8).ToString();
product.sendTime = rdr.GetValue(9).ToString();
product.sender = rdr.GetValue(10).ToString();
product.werks = rdr.GetValue(11).ToString();
}
rdr.Close();
string json_ = JsonConvert.SerializeObject(product);
var json = JToken.Parse(json_);
conn.Start();
ITextMessage request = session.CreateTextMessage(json); //Here I need to send the JSON
producer.Send(request);
}
Console.WriteLine("send succeed");
Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Receive Failed");
Console.ReadLine();
}

how to keep appending the list of values of a column until we get a new value in another column?

I am trying to keep appending a list of values to lookaheadRunInfo.gerrits until I get a new lookaheadRunInfo.ECJobLink in the while loop,I tried to create a variable “ECJoblink_previous” to capture the previous ECJoblink and create a new list only when they are different and keep appending until ECJoblink_previous changes,I tried as below but its not working,what am I missing?
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = #"some query";
var ECJoblink_previous ="";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//Console.WriteLine(rdr[0] + " -- " + rdr[1]);
//Console.ReadLine();
lookaheadRunInfo.ECJobLink = rdr.GetString(0);
if (ECJoblink_previous == lookaheadRunInfo.ECJobLink)
{
//Keep appending the list of gerrits until we get a new lookaheadRunInfo.ECJobLink
var gerritList = new List<String>();
lookaheadRunInfo.gerrits = gerritList.Add(rdr.GetString(2));
}
ECJoblink_previous = lookaheadRunInfo.ECJobLink;
lookaheadRunInfo.UserSubmitted = rdr.GetString(2);
lookaheadRunInfo.SubmittedTime = rdr.GetString(3).ToString();
lookaheadRunInfo.RunStatus = "null";
lookaheadRunInfo.ElapsedTime = (DateTime.UtcNow - rdr.GetDateTime(3)).ToString();
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
rdr.Close();
}
var lookaheadRunsInfo = new List<LookaheadRunInfo>();
LookAheadRunInfo lookaheadRunInfo;
var i = 0;
var ecJoblink_previous = string.Empty;
while (rdr.Read())
{
if (rdr.GetString(0) != ecJoblink_previous)
{
ecJoblink_previous = rdr.GetString(0);
if (i > 0)
{
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
// Create a new lookaheadRunInfo
lookaheadRunInfo = new lookaheadRunInfo
{
ECJobLink = rdr.GetString(0),
UserSubmitted = rdr.GetString(2),
SubmittedTime = rdr.GetString(3).ToString(),
RunStatus = "null",
ElapsedTime = (DateTime.UtcNow - rdr.GetDateTime(3)).ToString(),
gerrits = new List<string>
{
rdr.GetString(2)
}
};
}
else
{
//Keep appending the list of gerrits until we get a new lookaheadRunInfo.ECJobLink
lookaheadRunInfo.gerrits.Add(rdr.GetString(2));
}
}

Categories