Update the database record in SqlLite Database - sqlite

Here my insert code of SQLLite Database in Windows 8 and I want to update the records which are added in database
private async void insert(object sender, RoutedEventArgs e) {
if (txt1.Text != "" && txt2.Text != "" && txt3.Text != "") {
var dbpath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.db3");
using (var db = new SQLite.SQLiteConnection(dbpath)) {
// Create the tables if they don't exist
db.Insert(new person() {
id= Guid.NewGuid(),
name = txt1.Text.ToString(),
address = txt2.Text.ToString(),
phone = Convert.ToDouble(txt3.Text.ToString()),
});
db.Commit();
db.Dispose();
db.Close();
}
} else {
throw new NullReferenceException("Enter The Data In Textboxes");
}
}

In SQLite there's Get<T> method which accept primary key as argument and it will return the row as object. Update method accept the object as parameter and it will update the existing record. Here I am giving you method to update person record.
private void UpdateRecord(int primaryKey)
{
var dbpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "data.db3");
using (var db = new SQLite.SQLiteConnection(dbpath))
{
var objPerson = db.Get<person>(primaryKey);
objPerson.name = "New name";
objPerson.address = "New address ";
objPerson.phone = Convert.ToDouble("New phone number");
db.Update(objPerson);
//You don't need to use db.Commit(), db.Dispose() & db.Close() because you are using "using" keyword.
}
}

Related

How to refresh ListView in previous activity by updating DB in current activity?

I am using Xamarin Android. In the current activity i am having an editing form and on button click event i have an update query in the current activity.
private void OnclickSaveDATAButton(object sender, EventArgs e)
{
var CNICCARDNUMBER = Intent.Extras.GetString("NIC");
var conn = Connection();
conn.BeginTransaction();
var hf = conn.Table<mof>();
var search = hf.Where(x => x.CNICNO == CNICCARDNUMBER).ToList().FirstOrDefault(); //Linq Query
var Hofid = Convert.ToString(search.HOFID);
var data = conn.Query<hof>("UPDATE hof SET HOFNAME = ? WHERE HOFID = ?", Name.Text, Hofid);
conn.Commit();
if (data!= null)
{
Toast.MakeText(this,"Updated Successfully", ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "Update failed", ToastLength.Short).Show();
}
}
When I go back to previous activity on back button event
public override void OnBackPressed()
{
Intent intent = new Intent(this, typeof(SearchingActivity));
intent.SetFlags(ActivityFlags.ClearTop);
StartActivity(intent);
}
In the previous activity i am having select query on tab selection event. when i select the tab, I want to refresh the ListView and display the updated data instead of old one.
else if (CurrentTab.Position == 1)
{
Gridd = (ListView)FindViewById(Resource.Id.gridview);
Gridd.Visibility = ViewStates.Visible;
var CNICCARDNUMBER = Intent.Extras.GetString("cnic");
var conn = Connection();
var Hofid = 2;
data1 = new List<string>();
var data = conn.Query<combine>("SELECT hof WHERE hof.HOFID=?", Hofid);
foreach (var values in data)
{
data1.Add("CNIC:" + Convert.ToString(values.CNICNO));
data1.Add("Health card Number:" + Convert.ToString(values.CARDNO));
}
Gridd = (Listview)FindViewById(Resource.Id.gridview);
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, data1);
if (data1.Count() > 0)
{
Gridd.SetAdapter(adapter);
// Gridd.Adapter = adapter;
Gridd.ItemClick += Gridd_ItemClick;
}
else
{
Toast.MakeText(this, "No Data returned.", ToastLength.Short).Show();
}
}
Q: How to achieve this?
You can get the new data from DB and then call the listviewAdapter.OnNotifyPropertyChanged() in your onResume() method of your previous activity.
That would refresh your list.

Inserting dynamics 365 records into SQL Server database using asp.net

I am currently working on a project to insert a list of records from a dynamics 365 website into to a SQL Server database. However when I call the class file no insert is currently made into the database.
Can someone assist me? I have placed an ellipsis at the where the code which pulls the data from crm would be as that code works fine and so what you're reading isn't as long. Let me know if it is needed.
public class ProgramPVT
{
static void Main (string[] args)
{
try
{
...
int count = 0;
int n = count;
foreach (var item in performancevt)
{
performancevt.Add(item);
}
var totalnumber = performancevt.Count;
var t = totalnumber;
var accountmanager = new string[t];
var monthlytarget = new string[t];
var forecast_ = new string[t];
var actual_ = new string[t];
var managedservices = new string[t];
var pvtpercentage_ = new string[t];
var mspercentage_ = new string[t];
SqlConnection crmdbconnection = new SqlConnection("Data Source =*****;Initial Catalog=****;User Id = ******;Password = ******;");
crmdbconnection.Open();
foreach (var performanceitem in performancevt)
{
accountmanager[n] = performanceitem.accountmanager.ToString();
monthlytarget[n] = performanceitem.monthlytarget.ToString();
forecast_[n] = performanceitem.accountmanager.ToString();
actual_[n] = performanceitem.accountmanager.ToString();
managedservices[n] = performanceitem.monthlytarget.ToString();
pvtpercentage_[n] = performanceitem.accountmanager.ToString();
mspercentage_[n] = performanceitem.accountmanager.ToString();
var i = 0;
do
{
try
{
string cmdtext = "INSERT INTO PerformanceVTarget (Account_Manager, Month_Target, Forecast, Achieved, Total_Percentage, MS_Percentage) VALUES (#Account_Manager, #Month_Target, #Forecast, #Achieved, #Total_Percentage, #MS_Percentage)";
using (var cmd = new SqlCommand(cmdtext, crmdbconnection))
{
{
cmd.Parameters.AddWithValue("#Account_Manager", accountmanager[n]);
cmd.Parameters.AddWithValue("#Month_Target", accountmanager[n]);
cmd.Parameters.AddWithValue("#Forecast", accountmanager[n]);
cmd.Parameters.AddWithValue("#Achieved", accountmanager[n]);
cmd.Parameters.AddWithValue("#Total_Percentage", accountmanager[n]);
cmd.Parameters.AddWithValue("#Account_Manager", accountmanager[n]);
}
cmd.ExecuteNonQuery();
}
}
catch (Exception fx)
{
Console.Write(fx);
Console.WriteLine("Line with ID:", n, " not inserted");
Console.WriteLine("Error - Press enter to Continue");
Console.ReadLine();
}
i++;
} while (i < t);
}
n = n + 1;
}
catch (Exception ex)
{
Console.Write(ex);
Console.WriteLine("Press Enter to Continue");
Console.ReadLine();
}
}
}
}
Table PerformanceVTarget
[ID] pk, int ,not null
[Report_ID] int, null
[Account_Manager] varchar(50) not null
[Month_Target] varchar(50) not null
[Forecast] varchar(50) not null
[Achieved] varchar(50) not null
[Total_Percentage] varchar(50) not null
[MS_Percentage] varchar(50) not null
[Team] varchar(50) null
Your code execution will never come out of this loop.
foreach (var item in performancevt)
{
performancevt.Add(item);
}
This is a deadlock or you should get an error.
Also you are not passing any value to [MS_Percentage] & Id (primary key field), both are non-null columns.

Using Dapper to select data from MS SQL

I use Dapper to select data form Mssql, It result display "null"
(use stored procedure态 List to get data, and "myDictionary[0].Account" and myDictionary[0].Password to get detail information) ,
but MS SQL database have data.
How can I fix code ? thanks.
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
using (var conn = new SqlConnection(strConn))
{
try
{
conn.Open();
List<LoginModel> myDictionary =
conn.Query<LoginModel>(#"uspSelectLoginChk",
new { LoginAcc = strAccount, LoginPsd = strPassword }, commandType: CommandType.StoredProcedure).ToList();
string strAccountChk = myDictionary[0].Account;
string strPASChk = myDictionary[0].Password;
conn.Close();
if (strAccountChk != null && strAccountChk != null)
{
Response.Redirect("test.aspx");
}
else
{
}
}
catch (Exception ex)
{
response.write( ex.ToString());
}
}
}
Try this one,
// Modified your code
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
var _para = new DynamicParameters();
_para.Add("#LoginAcc", strAccount);
_para.Add("#LoginPsd", strPassword);
var _list = _con.Query<LoginModel>("uspSelectLoginChk", _para, commandType: CommandType.StoredProcedure); // _con is SqlConnection _con = new SqlConnection("your connection string")
if(_list != null) {
Response.Redirect("test.aspx");
}
}
you need to check:
execute sp in sql with parameter which can view in debug the code.
example:
exec uspSelectLoginChk 'LoginAccValue', 'LoginPsdValue'
if a any data in sql execute,your code is error,if no data, you can insert data before with a data debug result.
Thanks

dropdown values according to rights

There is multiple values in that dropdown ..
e.g.
Car
Truck
Bike
Drink
Factory
There is another login page Login.aspx .
Login code
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//Label1.BackColor = "F8D8D7";
loginmethod(txt_us.Text, txt_pwd.Text);
Response.Redirect("WebForm1.aspx");
}
catch( Exception )
{
Label1.Text = ("Incorrect UserName/Password");
Label1.Visible = true;
}
txt_us.Text = "";
txt_pwd.Text = "";
}
public bool loginmethod(string UserName,string Password)
{
TrackDataEntities1 td = new TrackDataEntities1();
splogin1_Result sp = td.splogin1(UserName, Password).FirstOrDefault();
if(sp.Password==txt_pwd.Text)
{
return true;
}
else
{
return false;
}
}
Now there is two users .. admin and user . Now i want when admin login then with their id and password then he see some values from this list and when user login then he will see some values from this list for example when admin login then he may able to see only Factory value and when user login then he able to see all values except factory
UPDATE
in login.aspx i save username is session
Session["UserName"] = txt_us.Text;
in form.aspx
Here first i create sp
ALTER procedure [dbo].[spadminlist]
as
select Region from tblReg
where Region in ('Factory')
then i add this sp in form.aspx
//this linq query for selecting all values
var list = tea.tblReg.AsEnumerable()
.Where(x => !x.Region.Any(char.IsDigit) && (x.Region != ""))
.GroupBy(x => x.Region)
.Select(x => new { Region = x.Key, Value = x.Key })
.ToList();
//this is for admin
if (Session["UserName"] = "admin")
{
List<spadminlist_Result> admin = tea.spadminlist().ToList();
}
and filling dropdown
if (!Page.IsPostBack)
{
regiondrop.DataSource = list;
regiondrop.DataTextField = "Region";
regiondrop.DataValueField = "Region";
regiondrop.DataBind();
Label4.Visible = false;
}
but this show error and also how i fill dropdown with admin sp because there is queries
Error 3 Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?)
how i do this ?
For Dynamic list:
Get from the backend whether user is admin or normal user.
List<string> menuItems = new List<string>();
if(logged_user == "ADMIN")
{
menuItems.add("item1");
menuItems.add("item2");
}
else
{
menuItems.add("item1");
menuItems.add("item2");
}
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataSource = menuItems;
DropDownList1.DataBind();
For Static list:
if(logged_user == "ADMIN")
{
DropDownList1.Items.FindByText("Item1").Enabled = false;
OR
DropDownList1.Items[i].Enabled = false;
}
else
{
Same process as above.
}
DropDownList1.DataTextField = "user_name";
DropDownList1.DataValueField = "user_id";
DropDownList1.DataBind();

if..else statement not working in foreach loop

Else statement not working properly in foreach loop? Here's my code. If something's wrong with my code explanations would be nice.
protected void getdata_Click(object sender, EventArgs e)
{
using (var db2 = new cftzClassDataContext())
{
var username = (from p in db2.cftzAccounts
where p.username.Equals(getdata2.Text)
select p);
foreach (var p in username)
{
if (getdata2.Text == p.username)
{
displayMSG.Text = "Is this correct ";
displayData.Text = p.username;
displayQuestionMark.Text = "?";
}
else
{
displayMSG.Text = "No User Found.";
}
}
}
}
The if statement is entirely redundant, as you have already filtered your list to only include accounts where the username equals getData2.Text. Therefore, your if test will always evaluate to true.
You can rewrite it as this, with the same effect
using (var db2 = new cftzClassDataContext())
{
var username = (from p in db2.cftzAccounts.Take(100)
where p.username.Equals(getdata2.Text)
select p);
foreach (var p in username)
{
displayMSG.Text = "Is this correct ";
displayData.Text = p.username;
displayQuestionMark.Text = "?";
}
}
However, as Hans points out, your loop is unnecessary as well, as all the usernames will be the same. Your code could be as simple as:
using (var db2 = new cftzClassDataContext())
{
var user = db2.cftzAccounts.
FirstOrDefault(account => account.username.Equals(getdata2.Text));
if (user != null)
{
displayMSG.Text = "Is this correct ";
displayData.Text = user.username;
displayQuestionMark.Text = "?";
}
else
{
displayMSG.Text = "No User Found.";
}
}
not sure what you try to achieve, but it looks like you are try to find if user is in database and if so, configure displayMSG object.
cant you do something like
var user=db2.Single(u=> u.username==getdata2.Text);
if no user is found, Singe will throw an exception. If you dont wont that, you can use SingleOrDefault() method
protected void getdata_Click(object sender, EventArgs e)
{
using (var db2 = new cftzClassDataContext())
{
try
{
var user=db2.Single(u=> u.username==getdata2.Text);
displayMSG.Text = "Is this correct ";
displayData.Text = user.username;
displayQuestionMark.Text = "?";
}
catch
{
displayMSG.Text = "No User Found.";
}
}
}

Resources