Add content of SELECT to LIST - sqlite

I've just started learning Xamarin and i would like to add content of SELECT query to List<SearchModel>. How can i do it? I've created Object model, according to Sqlite.
List<SearchModel> searchModelsList = new List<SearchModel>();
try
{
using (sQLiteConnection = new SQLiteConnection(path))
{
try
{
sQLiteConnection.Execute("SELECT * FROM CONTENT_TABLE);
}
catch (Exception ex) {
}
}
}
catch (Android.Database.Sqlite.SQLiteException ex)
{
Log.Info("exex", ex.Message);
}
class SearchModel
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string PERSON { get; set; }
public string NAME { get; set; }
}
}

I've just started learning Xamarin and i would like to add content of SELECT query to List. How can i do it? I've created Object model, according to Sqlite.
If you want to query data from sqlite database, you can take a look the following code:
<StackLayout>
<Button
x:Name="createdb"
Clicked="createdb_Clicked"
Text="create table in sqlite" />
<Button
x:Name="btnadd"
Clicked="btnadd_Clicked"
Text="add data to sqlite" />
<Button
x:Name="btnfetdata"
Clicked="btnfetdata_Clicked"
Text="get data from sqlite" />
</StackLayout>
public partial class Page2 : ContentPage
{
public SQLiteConnection conn;
public Page2()
{
InitializeComponent();
conn= GetSQLiteConnection();
}
public SQLiteConnection GetSQLiteConnection()
{
var fileName = "SearchModel.db";
var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentPath, fileName);
var connection = new SQLiteConnection(path);
return connection;
}
private void btnadd_Clicked(object sender, EventArgs e)
{
//var data = conn.Table<SearchModel>();
for(int i=0;i<20;i++)
{
SearchModel model = new SearchModel();
model.PERSON = "person "+ i;
model.NAME = "cherry "+ i;
conn.Insert(model);
}
}
private List<SearchModel> searchModelsList;
private void btnfetdata_Clicked(object sender, EventArgs e)
{
searchModelsList = conn.Table<SearchModel>().ToList();
var searchlist = conn.Query<SearchModel>("SELECT * FROM SearchModel WHERE PERSON = ?", "person 1");
}
private void createdb_Clicked(object sender, EventArgs e)
{
conn.CreateTable<SearchModel>();
}
}
public class SearchModel
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string PERSON { get; set; }
public string NAME { get; set; }
}
About querying data, you can use
var searchlist = conn.Query<SearchModel>("SELECT * FROM SearchModel WHERE PERSON = ?", "person 1");
But you can also get the entire SearchModel table, then query data from List
searchModelsList = conn.Table<SearchModel>().ToList();
var list = searchModelsList.Where(p => p.PERSON == "person 1");

Related

i am unable to ENABLE/DISABLE functions in function app programmatically. It does change my function.json file

public class AzureFunctionsHelper
{
private static string azureFunctionURL = string.Empty;
private static string azureFunctionUsername = string.Empty;
private static string azureFunctionPassword = string.Empty;
private static List<string> azureFunctionNames = new List<string>();
private WebClient _webClient;
public AzureFunctionsHelper()
{
if (azureFunctionURL == string.Empty || azureFunctionUsername == string.Empty || azureFunctionPassword == string.Empty)
{
setParameters();
}
_webClient = new WebClient
{
Headers = { ["ContentType"] = "application/json" },
Credentials = new NetworkCredential(azureFunctionUsername, azureFunctionPassword),
BaseAddress = azureFunctionURL
};
}
public void SetAzureFuncDisabled(bool isDisabled)
{
try
{
foreach(var functionName in azureFunctionNames)
{
string conUri = _webClient.BaseAddress + $"/{functionName}/function.json";
var functionJson = JsonConvert.DeserializeObject<FunctionSettings>(_webClient.DownloadString(conUri));
functionJson.disabled = isDisabled;
_webClient.Headers["If-Match"] = "*";
_webClient.UploadString(conUri, "STOR", JsonConvert.SerializeObject(functionJson));
}
}
catch (Exception ex)
{
throw ex;
}
}
private static string GetFunctionJsonUrl(string functionName)
{
try
{
return $"{functionName}/function.json";
}
catch (Exception ex)
{
throw ex;
}
}
public void setParameters()
{
try
{
var filePath = Path.Combine(System.AppContext.BaseDirectory, "appsettings.json");
azureFunctionURL = ReaderHelper.Read(filePath, "AzureFunctionAppURL");
azureFunctionUsername = ReaderHelper.Read(filePath, "AzureFunctionUsername");
azureFunctionPassword = ReaderHelper.Read(filePath, "AzureFunctionPassword");
var values = ReaderHelper.Read(filePath, "AzureFunctionNames");
azureFunctionNames = values.Split(", ").ToList();
//It does change function.json file "IsDisabled" attribute from true to false but it does //not effect on my function status
}
catch (Exception ex)
{
throw ex;
}
}
}
//Classes
internal class FunctionSettings
{
public string generatedBy { get; set; }
public string configurationSource { get; set; }
public List<Binding> bindings { get; set; }
public bool disabled { get; set; }
public string scriptFile { get; set; }
public string entryPoint { get; set; }
}
internal class Binding
{
public string type { get; set; }
public List<string> methods { get; set;}
public string authLevel { get; set; }
public string name { get; set; }
}
I create two function first is Timer trigger function and second is HTTP trigger function.
add a string value in local.settings.json .
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"Function_Disable": "True"
}
}
Function 1 : add Function_Disable attributes. I try to disable this function1 function.
Function 2 : no change in another function.
Output :- function 1 disable
After remove Function_Disable attributes.
Function1
local.settings.json file
Output:- Show two function run.

Windows 8 RT App - Passing info between pages

I am using SQLite to store data, I have a class:
class Customers
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(30)]
public string customerNumber { get; set; }
[MaxLength(100)]
public string customerName { get; set; }
}
How I am sending data is:
private void customer_Click(object sender, ItemClickEventArgs e)
{
Customers customer = e.ClickedItem as Customers;
if(customer != null)
{
Customers c = new Customers();
c.customerName = customer.customerName;
c.customerNumber = customer.customerNumber;
c.Id = customer.Id;
this.Frame.Navigate(typeof(customerDetail), c);
}
}
I need the data to display in text boxes on the detail page.
You need to access data on DetailsPage? Here you are:
public sealed partial class DetailPage : Page
{
public DetailPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Customers customer = (Customers)e.Parameter;
//Now you can get it from customer object
}
}
This is how I solved it:
From Page:
private void customer_Click(object sender, ItemClickEventArgs e)
{
Customers customer = e.ClickedItem as Customers;
if(customer != null)
{
Customers c = new Customers();
c.customerName = customer.customerName;
c.customerNumber = customer.customerNumber;
c.Id = customer.Id;
Frame.Navigate(typeof(customerDetail), c.Id.ToString());
}
}
To Page:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string custId = e.Parameter as string;
int custIDLookup = Convert.ToInt32(custId);
lookUp(custIDLookup);
navigationHelper.OnNavigatedTo(e);
}

How to retrieve the text from a cell in a dynamically generated gridview

I want to get the book name which is in the first column of gridview. I used Template field and added a link button in it. Book name is retrieved from database, thus dynamically wriiten. I want open the selected book in pdf in another page.
public class Book
{
public string Bookn{get;set;}
public string Auth { get; set; }
public string Category { get; set; }
public string Edi { get; set; }
public string Yopub { get; set; }
public string Avai { get; set; }
public string img { get; set; }
}
public class GetData
{
public static List<Book> Getallrecord(string author)
{
List<Book> ob1 = new List<Book>();
SqlConnection con;
SqlCommand com;
string cs = ConfigurationManager.ConnectionStrings["SDL_DBConnectionString"].ConnectionString;
using (con = new SqlConnection(cs))
{
com = new SqlCommand("searchByAuthor3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#SAuthor", author + "%");
con.Open();
SqlDataReader rd = com.ExecuteReader();
while (rd.Read())
{
Book bo = new Book();
bo.Bookn = rd["BookName"].ToString();
bo.Auth = rd["Author"].ToString();
bo.Category = rd["Category"].ToString();
bo.Yopub = rd["Yopublication"].ToString();
bo.Edi = rd["Edition"].ToString();
bo.Avai = rd["Available"].ToString();
bo.img = rd["Images"].ToString();
ob1.Add(bo);
}
}
return ob1;
}
}
protected void SAButton_Click(object sender, EventArgs e)
{
string author = TAuthor.Text;
if (Session["ClientLogin"] != null)
{
SAGridView.DataSource=GetData.Getallrecord(author);
SAGridView.DataBind();
}
else
{
Server.Transfer("Login.aspx");
}
}
You can add a hyperlink field in your gridview and redirect to your other page like
<asp:HyperLinkField DataNavigateUrlFields="Bookn"
DataNavigateUrlFormatString="View_Book.aspx?BookNo={0}" Text="View Book" />

DataTable Loop Within a Loop C#

I have a nice dataset loop working, but I need to run another loop based on an ID in the parent loop.
I set up a generic list in a separate class, but I'm totally stumped on how to actually call it. I've Googled it but can't find an example I understand.
EDIT:
List Code...
public class BinList
{
public static List<Bin> GetById(int binOrderSiteID)
{
List<Bin> bins = new List<Bin>();
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
using (conn = new SqlConnection(myConnectionHere))
{
comm = new SqlCommand("dbo.sl_BinsBySite", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("#binOrderSiteID", SqlDbType.Int));
comm.Parameters["#binOrderSiteID"].Value = binOrderSiteID;
try
{
conn.Open();
reader = comm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Bin b = new Bin();
b.BinQty = reader["binQty"].ToString();
b.BinType = reader["binType"].ToString();
b.BinWasteGroupName = reader["binWasteGroupName"].ToString();
b.BinCollectionFrequencyType = reader["binCollectionFrequencyType"].ToString();
b.BinDeliveryStartDate = reader["binDeliveryStartDate"].ToString();
b.BinEmptyCharge = reader["binEmptyCharge"].ToString();
b.BinRentalCharge = reader["binRentalCharge"].ToString();
b.BinDutyOfCareCharge = reader["binDutyOfCareCharge"].ToString();
b.BinDeliveryCharge = reader["binDeliveryCharge"].ToString();
bins.Add(b);
}
}
}
finally
{
conn.Close();
}
}
return bins;
}
}
This is a repository for each field
public class Bin
{
public string BinQty { get; set; }
public string BinType { get; set; }
public string BinWasteGroupName { get; set; }
public string BinCollectionFrequencyType { get; set; }
public string BinDeliveryStartDate { get; set; }
public string BinEmptyCharge { get; set; }
public string BinRentalCharge { get; set; }
public string BinDutyOfCareCharge { get; set; }
public string BinDeliveryCharge { get; set; }
}
Code to that calls the loops
public class PDFCreator
{
public static int BinOrderID { get; set; }
private int binOrderID = 0;
public PDFCreator(int intBinOrderID)
{
//Lots of code here
//Data conenection/datatable code here
foreach (DataRow row in dt.Rows)
{
//lots of code here
//dont know how to connect up or call the List
something?? = BinList.GetById(Convert.ToInt32(row["binOrderSiteID"].ToString()));
foreach (//somnething here)
}
}
}
Sorry I didn't add my code initially. I didn't want to show it cos I thought it was pants.
Any ideas?
Cheers,
Numb
To call BinList GetById
var binList = BinList.GetById((int)row["binOrderSiteID"]);
foreach (var bin in binList)
{
// do what you need to do with bin variable
}

Need help in 3 tier entity class object code

I am trying to access entity class but getting the error message "No overload method for CreateDoctor takse 3 argument" Here is my code please modify somebody..
DoctorProperty class:
public class DoctorProperty //class for doctor table
{
int _Id;
string _Name;
string _Address;
int _Phone;
public int Id
{
get
{
return _Id;
}
set
{
_Id = value;
}
}
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
public string Address
{
get
{
return _Address;
}
set
{
_Address = value;
}
}
public int Phone
{
get
{
return _Phone;
}
set
{
_Phone = value;
}
}
}
Doctor DataLayer:
public class DoctorDataLayer
{
public string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
public int AddDoctor(DoctorProperty obj)
{
SqlConnection con = new SqlConnection(str);
SqlCommand com =new SqlCommand("insert into Doctor values('"+obj.Name+"','"+obj.Address+"','"+obj.Phone+"')",con);
com.ExecuteNonQuery();
return 0;
}
}
Doctor BusinessLayer:
public class DoctorBusinessLayer
{
public void CreateDoctor(DoctorProperty obj)
{
DoctorDataLayer dl = new DoctorDataLayer();
dl.AddDoctor(obj);
}
}
AdDoctor.aspx.cs
protected void Btnsubmit_Click(object sender, EventArgs e)
{
DoctorBusinessLayer DB = new DoctorBusinessLayer();
DoctorProperty dp = new DoctorProperty();
DB.CreateDoctor(TxtName.Text, TxtAddress.Text, TxtPhone.Text);
}
Above highlighted line getting error:
Your CreateDoctor method only take 1 argument.
public void CreateDoctor(DoctorProperty)
But you're calling it with 3 arguments...
DB.CreateDoctor(string, string, string)
You could solve the problem in 1 way...
Edit:
Taking a closer look at your code it seems it would benefit of a rewrite, so here goes:
public class Doctor
{
// JohannesH: Changed to use auto properties instead.
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
public static class DoctorDataLayer
{
public static void AddDoctor(Doctor doctor) // JohannesH: Changed return type from int to void.
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; // JohannesH: Changed from .ToString() to .ConnectionString
// JohannesH: Changed to use "using" to make sure everything gets disposed correctly during failure.
using(var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("insert into doctor values(#name,#address,#phone)", connection))
{
// JohannesH: Now using SqlParameters to get rid of sql injection attacks.
command.Parameters.AddWithValue("#name", doctor.Name);
command.Parameters.AddWithValue("#address", doctor.Address);
command.Parameters.AddWithValue("#phone", doctor.Phone);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
}
public static class DoctorBusinessLayer
{
public static void CreateDoctor(string name, string address, string phone)
{
DoctorDataLayer.AddDoctor(new Doctor {Name = name, Address = address, Phone = phone});
}
}
Change this line :
DB.CreateDoctor(TxtName.Text, TxtAddress.Text, TxtPhone.Text);
With these :
dp.Name = TxtName.Text;
dp.Address = TxtAddress.Text;
dp.Phone = TxtPhone.Text;
DB.CreateDoctor(db);
Here is the reformatted code :
DoctorProperty class: public class DoctorProperty //class for doctor table
{
int _Id;
string _Name;
string _Address;
int _Phone;
public int Id { get { return _Id; } set { _Id = value; } }
public string Name { get { return _Name; } set { _Name = value; } }
public string Address { get { return _Address; } set { _Address = value; } }
public int Phone { get { return _Phone; } set { _Phone = value; } }
}
//Doctor DataLayer:
public class DoctorDataLayer
{
public string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
public int AddDoctor(DoctorProperty obj)
{
SqlConnection con = new SqlConnection(str);
SqlCommand com =new SqlCommand("insert into Doctor values('"+obj.Name+"','"+obj.Address+"','"+obj.Phone+"')",con);
com.ExecuteNonQuery();
return 0;
}
}
//Doctor BusinessLayer:
public class DoctorBusinessLayer {
public void CreateDoctor(DoctorProperty obj)
{
DoctorDataLayer dl = new DoctorDataLayer();
dl.AddDoctor(obj);
}
}
//AdDoctor.aspx.cs
protected void Btnsubmit_Click(object sender, EventArgs e) {
DoctorBusinessLayer DB = new DoctorBusinessLayer();
DoctorProperty dp = new DoctorProperty();
dp.Name = TxtName.Text;
dp.Address = TxtAddress.Text;
dp.Phone = TxtPhone.Text;
DB.CreateDoctor(db);
}

Resources