how to return the json data - asp.net

I want to convert string to json
here i want to convert string data object to json
when i inserted the data using web service page see below
and inserted data look like below:
watch window
Code:
public class WebService1 : System.Web.Services.WebService
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string InsertData(string fname, string mname, string lname, string emailid, string password, string contactno, string hobby, string address, string countrycodenum)
{
cn.Open();
string data = fname + mname + lname + emailid + password + contactno + hobby + address + countrycodenum;
string insertquery = "insert into tblstudent(fname, mname, lname, emailid, password, contactno,hobby,address,countrycodenum)values(#fname,#mname,#lname,#emailid,#password,#contactno,#hobby,#address,#countrycodenum)";
SqlCommand cmd = new SqlCommand(insertquery, cn);
//cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#mname", mname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#emailid", emailid);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#contactno", contactno);
cmd.Parameters.AddWithValue("#hobby", hobby);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#countrycodenum", countrycodenum);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Console.WriteLine("Insert Successfully");
}
else
{
Console.WriteLine("Not Insert Successfully");
}
cn.Close();
return data;
}
}
}
I install the Newtonsoft package
I want to convert string data object to json??

Instead of this line
string data = fname + mname + lname + emailid + password + contactno + hobby + address + countrycodenum;
Do these two steps.
First create an anonymous object using this line of code:
var dataObject = new { fname, mname, lname, emailid, password, contactno, hobby, address, countrycodenum };
In your example the object would look like this:
{ fname = raju, mname = makvana, lname = dinesh, emailid = raju#gmail.com, password = 12345, contactno = 1234567890, hobby = cricket, address = surat, countrycodenum = uzbekistan }
Second, serialize dataObject to JSON string:
string data = JsonConvert.SerializeObject(dataObject);
Don't forget to use Newtonsoft.Json package.
In your example the JSON string would look like this:
{"fname":"raju","mname":"makvana","lname":"dinesh","emailid":"raju#gmail.com","password":"12345","contactno":"1234567890","hobby":"cricket","address":"surat","countrycodenum":"uzbekistan"}
The entire code is below:
public class WebService1 : System.Web.Services.WebService
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string InsertData(string fname, string mname, string lname, string emailid, string password, string contactno, string hobby, string address, string countrycodenum)
{
cn.Open();
// *** this is old code ***
// string data = fname + mname + lname + emailid + password + contactno + hobby + address + countrycodenum;
// *** this is new code ***
var dataObject = new { fname, mname, lname, emailid, password, contactno, hobby, address, countrycodenum };
string data = JsonConvert.SerializeObject(dataObject);
string insertquery = "insert into tblstudent(fname, mname, lname, emailid, password, contactno,hobby,address,countrycodenum)values(#fname,#mname,#lname,#emailid,#password,#contactno,#hobby,#address,#countrycodenum)";
SqlCommand cmd = new SqlCommand(insertquery, cn);
//cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#mname", mname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#emailid", emailid);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#contactno", contactno);
cmd.Parameters.AddWithValue("#hobby", hobby);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#countrycodenum", countrycodenum);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Console.WriteLine("Insert Successfully");
}
else
{
Console.WriteLine("Not Insert Successfully");
}
cn.Close();
return data;
}
}

so you can use from newtonsoft.json library and just define your class and it convert to your class
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(serviceResult);
foreach (var item in obj1.data)
{
//convert obj1 to your class
}

Related

Sqlite code not displaying any Debug log?

Very new to sqlLite and trying to make a very simple bit of code which will display the values of username and password in the table just using the debug log for ease. When running the code nothing is display in the debug log. Could someone suggest a fix?
IDbConnection dbconn;
dbconn = (IDbConnection)new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT username, password " + "FROM user";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string username = reader.GetString(0);
string password = reader.GetString(1);
Debug.Log("Username: " + username + " Password:" + password);
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbconn.Close();
dbconn = null;
}
}
You can try to get the parameter out of the reader like that:
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string username = reader["username"];
string password = reader["password"]
Debug.Log("Username: " + username + " Password:" + password);
}

Getting error "Database is locked" when I trye to save data i SQLITE DB

I have following class that connects to database but when I trye to call the method that saves data I get error "Database is locked". Could some one please help me to find the problem?
class Data
{
private SQLiteConnection con;
private void ConnectoDB()
{
String PathDB = Directory.GetCurrentDirectory();
PathDB += "\\SQLiteDB_MEDFit.db";
string cs = #"URI=file:" + PathDB;
string stm = "SELECT SQLITE_VERSION()";
con = new SQLiteConnection(cs);
con.Open();
var cmd = new SQLiteCommand(stm, con);
string version = cmd.ExecuteScalar().ToString();
}
public Boolean SaveToDatabase(string name, string number)
{
bool result = false;
try
{
ConnectoDB();
con.Execute("insert into People(name, number) values ('" + name+ "', '" + number+ "')");
con.Close();
result = true;
MessageBox.Show("Saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
}
The code that calls the "SaveToDatabase()"
string name = textBox1.Text();
string number = textBox2.Text();
Data connect = new Data();
connect.SavetoDB(name, number);

Existing data in database SQLITE + Unity

I need to check in the database if the value is current exist. but i don't know how use data in my value public Text CreateUsername.
[SerializeField]
private Text CreateUsername;
Create user query
public void CreateUser(string username, int status)
{
using (IDbConnection dbConnection = new SqliteConnection(Connection))
{
dbConnection.Open();
using (IDbCommand dbCmd = dbConnection.CreateCommand())
{
string insertuser = String.Format("insert into user_data (UserData_name, UserData_status) values (\"{0}\",\"{1}\")", username, status);
dbCmd.CommandText = insertuser;
dbCmd.ExecuteScalar();
dbConnection.Close();
}
}
}
Insert user query... in this process i don't know what correct query will i use in where condition in String checkusername.
public void insertCreateUser()
{
using (IDbConnection dbConnection = new SqliteConnection(Connection))
{
dbConnection.Open();
using (IDbCommand dbCmd = dbConnection.CreateCommand())
{
string checkusername = "select count(UserData_name) from user_data where UserData_name ";
dbCmd.CommandText = updatestatus;
dbCmd.ExecuteScalar();
dbConnection.Close();
}
}
ChangeStatus();
int stat = 1;
CreateUser(CreateUsername.text, stat);
}

checkout.fi payment gateway implement (convert php code to asp.net with C#)

I am implementing checkout.fi payment gateway. I got the source code in php and java.I don't have any idea about php. That's why I want to convert Php source code to Asp.net code. Any Help Please
Below link given the sample code of PHP
https://checkoutfinland.github.io/#testing
and other sample java code link on github
https://github.com/AgiSol/checkout-java/
i have made code in asp.net but it is not working. For reference i have taking a Test Data. Below my code. This code run on button click event.
Code here
<pre><code>
protected void Button2_Click(object sender, EventArgs e){
string ver = "0001";
string stamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string amount = "1000";
string refer = "2432324";
string message = "hi";
string language = "FI";
string returnurl = "domain.com/return.aspx";
string cancelurl = "domain.com/cancel.aspx";
string reject = "2";
string delaye = "";
string country = "FIN";
string currency = "EUR";
string device = "10"; // 10 = XML
string content = "1";
string type = "0";
string algorithms = "3";
string delivery_date = "20171207";
string firstname = "Tarun";
string family = "Parmar";
string address = "Ääkköstie 5b3\nKulmaravintolan yläkerta";
string postcode = "33100";
string postoffice = "Tampere";
string MERCHANT="375917";
string SECRET_KEY= "SAIPPUAKAUPPIAS";
string macnew = encryptionMD5(ver, stamp, amount, refer, message, language,MERCHANT ,returnurl, cancelurl, reject,delaye, country,currency, device, content, type,algorithms, delivery_date, firstname,family, address, postcode,postoffice, SECRET_KEY).ToUpper();
string email = "support#checkout.fi";
string phone = "0800552010";
string status = "1";
string generatedMac = GetHashSha256(ver,stamp, refer, amount, status, algorithms, SECRET_KEY);
NameValueCollection collections = new NameValueCollection();
collections.Add("VERSION", ver);
collections.Add("STAMP", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
collections.Add("AMOUNT", amount);
collections.Add("REFERENCE", refer);
collections.Add("MESSAGE", message);
collections.Add("LANGUAGE", language);
collections.Add("RETURN", "domain.com/return.aspx");
collections.Add("CANCEL", "domain.com/cancel.aspx");
collections.Add("REJECT", reject);
collections.Add("DELAYED", delaye);
collections.Add("COUNTRY", country);
collections.Add("CURRENCY", currency);
collections.Add("DEVICE", device);
collections.Add("CONTENT", content);
collections.Add("TYPE", type);
collections.Add("ALGORITHM", algorithms);
collections.Add("DELIVERY_DATE", delivery_date);
collections.Add("FIRSTNAME", firstname);
collections.Add("FAMILYNAME", family);
collections.Add("ADDRESS",address);
collections.Add("POSTCODE", postcode);
collections.Add("POSTOFFIC", postoffice);
collections.Add("MAC", macnew);
collections.Add("EMAIL", email);
collections.Add("PHONE", phone);
collections.Add("MERCHANT",MERCHANT);
collections.Add("SECRET_KEY", SECRET_KEY);
string remoteUrl = "https://payment.checkout.fi";
string html = "<html><head>";
html += "</head><body onload='document.forms[0].submit()'>";
html += string.Format("<form name='PostForm' method='POST' action='{0}'>", remoteUrl);
foreach (string key in collections.Keys)
{
html += string.Format("<input name='{0}' type='text' value='{1}'>", key, collections[key]);
}
html += "</form></body></html>";
Response.Clear();
Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
Response.HeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
Response.Charset = "ISO-8859-1";
Response.Write(html);
Response.End();
}
Function For encryptionMD5
public string encryptionMD5(String VERSION, String STAMP, String AMOUNT, String REFERENCEs, String MESSAGE, String LANGUAGE, String merchantId, String RETURN, String CANCEL, String REJECT, String DELAYED, String COUNTRY, String CURRENCY, String DEVICE, String CONTENT, String TYPE, String ALGORITHM, String DELIVERY_DATE, String FIRSTNAME, String FAMILYNAME, String ADDRESS, String POSTCODE, String POSTOFFICE, String PasswordID)
{
string passwords = VERSION + STAMP + AMOUNT + REFERENCEs + MESSAGE + LANGUAGE + merchantId + RETURN + CANCEL + REJECT + DELAYED + COUNTRY + CURRENCY + DEVICE + CONTENT + TYPE + ALGORITHM + DELIVERY_DATE + FIRSTNAME + FAMILYNAME + ADDRESS + POSTCODE + POSTOFFICE + PasswordID;
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] encrypt;
UTF8Encoding encode = new UTF8Encoding();
encrypt = md5.ComputeHash(encode.GetBytes(passwords));
StringBuilder encryptdata = new StringBuilder();
for (int i= 0; i<encrypt.Length; i++) {
encryptdata.Append(encrypt[i].ToString());
}
return encryptdata.ToString();
}
Function For GetHashSha256
<pre><code>
public string GetHashSha256(string VERSION,string STAMP, string REFERENCE,string PAYMENT, string STATUS, string ALGORITHM, string password)
{
string text = VERSION + STAMP + REFERENCE + PAYMENT + STATUS + ALGORITHM + password;
byte[] bytes = Encoding.ASCII.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
This above code give below error
Creating a Payment Transaction failed (-24).
Error in field: MAC
Thanks in Advance if anybody help in solving this problem.
Well, the Finland checkout payment gateway means that your MAC is not hashed correctly. I downloaded the java version from their github and it works perfectly. You are not generating the correct MD5 hash.
Quite a few problems in your code. First of all you must append + sign with each of the strings because they do same in Java. Second, you are assigning algorithms = "3". You should use algorithms = "2" for MD5. Third your encryptionMD5 doesn't returns correct hash.
Below is the correct implementation that I have done for you:
string ver = "0001";
string stamp = "kpjkq1510841290161";
string amount = "1490";
string refer = "12345";
string message = "My custom message";
string language = "FI";
string returnurl = "http://localhost/success";
string cancelurl = "http://localhost/cancel";
string reject = "http://localhost/rejected";
string delaye = "http://localhost/delayed";
string country = "FIN";
string currency = "EUR";
string device = "10"; // 10 = XML
string content = "1";
string type = "0";
string algorithms = "2";
string delivery_date = "20171123";
string firstname = "Tero";
string family = "Testaaja";
string address = "Mystreet 1";
string postcode = "12345";
string postoffice = "Tampere";
string MERCHANT = "375917";
string SECRET_KEY = "SAIPPUAKAUPPIAS";
using (MD5 md5Hash = MD5.Create())
{
string fromValue = String.Join("+", new string[] { ver, stamp, amount, refer, message, language, MERCHANT, returnurl, cancelurl, reject, delaye, country, currency, device, content, type, algorithms, delivery_date, firstname, family, address, postcode, postoffice, SECRET_KEY });
string macnew = GetMd5Hash(md5Hash, fromValue);
}
public string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
Output is c84e068fcab5c4dad93a29dd4c567b7f
Verified from finland checkout java github project.
And one tip is that you should use StringBuilder for appending text instead of concatenating with + sign for improved performance.

return parameters from function

I have a function:
internal static void GetUserData(int userId, out string userName,
out string userEmail, out string userPassword)
{
using (SqlConnection con = Util.GetConnection())
{
con.Open();
using (SqlCommand cmd = new SqlCommand("usp_UD_SelectById", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UD_ID", SqlDbType.Int).Value = userId;
cmd.Parameters.Add("#UD_UserName", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#UD_Password", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#UD_Email", SqlDbType.NVarChar, 100).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
userName = Convert.ToString(cmd.Parameters["#UD_UserName"].Value);
userEmail = Convert.ToString(cmd.Parameters["#UD_Email"].Value);
userPassword = Convert.ToString(cmd.Parameters["#UD_Password"].Value);
}
}
}
and the call
string userEmail;
string userName;
string userPassword;
MemberHelper.GetUserData(userId, out userName, out userEmail, out userPassword);
Sometimes I need to get just one parameter from the out parameters, how can I call the function when I want to get just one:
string userPassword;
MemberHelper.GetUserData(userId,"","",out userPassword);
You have to supply them. out parameters are not optional. You could write a custom overload that only provides the out parameters that you need.

Resources