Send JSON through ActiveMQ - c#

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();
}

Related

Showing list of bank in db on click of a button

I have 3 input (username,password and datasource) and a button (connect) by clicking on button list of bank in db will be demonstrate
\[HttpGet\]
public JsonResult search()
{
//try connect to make connection on sql engine
// if it could to connect get list of db and return
// that
var username = Request.QueryString["username"].ToString();
var password = Request.QueryString["password"].ToString();
var datasource = Request.QueryString["databaseConString"].ToString();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Server"] = datasource;
builder["Connect Timeout"] = 1000;
builder["Trusted_Connection"] = true;
builder["Integrated Security"] = false;
builder.Password = password;
builder.UserID = username;
List<string> list = new List<string>();
Console.WriteLine(builder.ConnectionString);
using (SqlConnection con = new SqlConnection(builder.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(" **problem **SELECT name FROM sys.databases**"**,con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
// # I have problem in this loop **
while (dr.Read())
{
//list.Add(dr.GetString());
Console.WriteLine("{0}",dr[0]);
}
//foreach(var item in list)
//{
// Console.WriteLine(list);
//}
}
return Json( JsonRequestBehavior.AllowGet);
}
}
}
I do not know How use sqlDataReader and add object to my list
**problem SELECT name FROM sys.databases
Here you should also need to know in which table under the database, you are going to search bank name you haven't specified that. For instance, you should write like beloww:
SELECT BankName FROM BankTable [dbo].[BankDatabase]
I do not know How use sqlDataReader and add object to my list
Well, you could fetch your database-entity from your table inside the while loop. Finally bind your property into your list. Your code should be as following:
[HttpGet]
public JsonResult search()
{
var username = Request.QueryString["username"].ToString();
var password = Request.QueryString["password"].ToString();
var datasource = Request.QueryString["databaseConString"].ToString();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Server"] = datasource;
builder["Connect Timeout"] = 1000;
builder["Trusted_Connection"] = true;
builder["Integrated Security"] = false;
builder.Password = password;
builder.UserID = username;
List<string> listData = new List<string>();
using (SqlConnection con = new SqlConnection(builder.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT [BankName] FROM [DataBaseName].[dbo].[TableName]", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string bankName = reader.GetString(0);
listData.Add(bankNamee);
}
}
return Json(listData);
}
}
}
Note: Make sure reader.GetString(0) the order has followed accordingly. Means if the [BankName] is in first order theb it should be as reader.GetString(0). In addition, remember the data-type as well. For your information, here, I am getting each bankNamee and binding to the list I defined above listData.Add(bankNamee);
Output:

Update table row in database c# console app

trying to update a column of null values with instagramIds, this is my current approach but the console app just keeps running and doesn't update any values in the database.
public static async Task<InstagramUser> ScrapeInstagram(string url)
{
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
// create html document
var htmlBody = await response.Content.ReadAsStringAsync();
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(htmlBody);
// select script tags
var scripts = htmlDocument.DocumentNode.SelectNodes("/html/body/script");
// preprocess result
var uselessString = "window._sharedData = ";
var scriptInnerText = scripts[0].InnerText
.Substring(uselessString.Length)
.Replace(";", "");
// serialize objects and fetch the user data
dynamic jsonStuff = JObject.Parse(scriptInnerText);
dynamic userProfile = jsonStuff["entry_data"]["ProfilePage"][0]["graphql"]["user"];
List<String> columnData = new List<String>();
//Update database query
string connectionString = #"Server=myProject-dev-db.cothtpanmcn7.ap-southeast-2.rds.amazonaws.com;Database=Projectdb;User Id=testadmin;Password=U8gs7vb7C7yvakXf;MultipleActiveResultSets=true;Trusted_Connection=False;";
using (SqlConnection con = new SqlConnection(connectionString))
{
//get null values from database
string query = "Select * from ApplicationUser where InstagramId is null";
using (SqlCommand command = new SqlCommand(query, con))
{
command.Connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
columnData.Add(reader.GetString(0));
}
}
}
for (int index = 0; index < columnData.Count(); index++)
{
//get username and scrape info
var instagramInfo = new InstagramUser
{
Id = userProfile.id,
};
columnData.Add(instagramInfo.ToString());
}
SqlCommand cmd = new SqlCommand("Update ApplicationUser Set InstagramId = '" + columnData + "'" + "where InstagramUsername = '" + userprofile.username + "'", con);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
// create an InstagramUser
var instagramUser = new InstagramUser
{
FullName = userProfile.full_name,
FollowerCount = userProfile.edge_followed_by.count,
FollowingCount = userProfile.edge_follow.count,
Id = userProfile.id,
url = url
};
return instagramUser;
}
else
{
throw new Exception($"Something wrong happened {response.StatusCode} - {response.ReasonPhrase} - {response.RequestMessage}");
}
}
}
The current output:
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
{"FullName":null,"FollowerCount":0,"FollowingCount":0,"Id":"6978701146","url":null}
My current approach is to create a list, add all instagramIDs which are null to that list. From there I add all instagramIds to that list after scraping Instagram for their usernames e.g. https://www.instagram.com/therock/?__a=1
then I update the column InstagramUsername with their instagram Ids

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

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));
}
}

Json Deserialization

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.

Categories