Need help in 3 tier entity class object code - asp.net

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

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.

Add content of SELECT to LIST

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

How to run though loop with foreach and IF-statement to check input value is found in dictionary

I have created a simple login page, without using a database, I typed the successful logins in a dictionary and want to run through the dictionary with a foreach loop, and check if input values are found in the dictionary. if so then succesfuld login, else and error. I just can't figure out how to run through the dictionary and check if the input value match dictionary values (Name and password)
public class EmployeeCollection
{
private string _name;
private int _password;
private EmployeeCollection()
{
Dictionary<int, Employee> Employees = new Dictionary<int, Employee>();
Employees.Add(1, new Employee("qwe", 12345));
Employees.Add(2, new Employee("asd", 12345));
Employees.Add(3, new Employee("zxc", 12345));
}
public Dictionary<int, Employee> Employees = new Dictionary<int, Employee>();
public bool RequestLogin(string Username, int Password)
{
foreach (var item in Employees) // Dictionary
{
if (Employees.ContainsKey(1))
{
return true;
}
else if (Employees.ContainsKey(2))
{
return true;
}
else if (Employees.ContainsKey(3))
{
return true;
}
else
{
return false;
}
}
return false;
public class LoginPageViewModel : ViewModelBase
{
private EmployeeCollection _employee;
private EmployeeCollection _employeeCollection;
private string _username;
private int _password;
public LoginPageViewModel()
{
LoginCommand = new RelayCommand(toLoginCommand);
}
public string Username
{
get { return _username; }
set { _username = value; }
}
public int Password
{
get { return _password; }
set { _password = value; }
}
public RelayCommand LoginCommand { get; set; }
public void toLoginCommand()
{
_employee.RequestLogin(Username, Password);
}

The property name '#iot.id' is invalid; property names must not contain any of the reserved characters ':', '.', '#'

I have a Asp.net Web Api project that referenced Microsoft.AspNet.Odata. I want to return data model that properties has DataMember attribute for serialization. All things well but when I call method , throw exception as "The property name '#iot.id' is invalid; property names must not contain any of the reserved characters ':', '.', '#'."
returned model like below
[DataContract]
public class Sensor:AbstractEntity
{
private string _name;
private string _description;
//private object _metadata;
private string _metadata;
private string _encodingType;
private string _datastreamsNavigationLink;
private List<Datastream> _datastreams;
public Sensor()
{
_datastreams = new List<Datastream>();
Datastreams = new List<Datastream>();
}
[JsonProperty("name")]
[DataMember(Name ="name")]
public string Name
{
get {return _name; }
set { SetProperty(ref _name, value); }
}
[JsonProperty("description")]
public string Description
{
get { return _description; }
set { SetProperty(ref _description, value); }
}
[JsonProperty("metadata")]
public string Metadata
{
get { return _metadata; }
set { SetProperty(ref _metadata, value); }
}
[JsonProperty("encodingType")]
public string EncodingType
{
get { return _encodingType; }
set { SetProperty(ref _encodingType, value);
}
}
[JsonProperty("Datastreams#iot.navigationLink")]
public string DatastreamsNavigationLink
{
get { return _datastreamsNavigationLink; }
set { SetProperty(ref _datastreamsNavigationLink, value);
}
}
[JsonProperty("Datastreams")]
[Expand(ExpandType =SelectExpandType.Allowed,MaxDepth =1)]
public List<Datastream> Datastreams { get; set; }
}
}
[DataContract]
public class AbstractEntity : INotifyPropertyChanged
{
private decimal _id;
private string _selfLink;
public event PropertyChangedEventHandler PropertyChanged;
[JsonProperty("#iot.id")]
[DataMember(Name = "#iot.id")]
[Key]
public decimal Id
{
get { return _id; }
set { SetProperty(ref _id, value); }
}
[JsonProperty("#iot.selfLink")]
[DataMember(Name = "#iot.selfLink")]
public string SelfLink
{
get { return _selfLink; }
set { SetProperty(ref _selfLink, value); }
}
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Equals(storage, value))
{
return false;
}
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void CreateSelfLink(string apiUrl,string entityLink,decimal? id)
{
if (id != null && id > 0)
entityLink = string.Format("{0}({1})", entityLink, id);
_selfLink = string.Format("{0}/api/{1}", apiUrl, entityLink);
}
public string CreateEntityLink(string apiUrl, string entityType1,string entitType2, decimal? id)
{
if (id != null && id > 0)
entityType1 = string.Format("{0}({1})", entityType1, id);
return string.Format("{0}/api/{1}/{2}", apiUrl, entityType1,entitType2);
}
}
}
and method I called
[EnableQuery]
public async Task<IHttpActionResult> GetSensors(ODataQueryOptions<Sensor> queryOptions)
{
// validate the query.
try
{
queryOptions.Validate(_validationSettings);
}
catch (ODataException ex)
{
return BadRequest(ex.Message);
}
return Ok(_sensorService.Get(queryOptions));
}
and here is global.asax configuration
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.Clear();
var formater = new JsonMediaTypeFormatter()
{
SerializerSettings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver()
},
UseDataContractJsonSerializer = true,
};
//Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSetSerializer.
//formater.SerializerSettings.
config.Formatters.Add(formater);
and here's the content I want to return
{
"#odata.context": "http://localhost:16862/api/$metadata#Sensors",
"value": [{
"#iot.id": 4,
"#iot.selfLink": "https://toronto-bike-snapshot.sensorup.com/v1.0/Sensors(4)",
"description": "A sensor for tracking how many docks are available in a bike station",
"name": "available_docks",
"encodingType": "text/plan",
"metadata": "https://member.bikesharetoronto.com/stations",
"Datastreams#iot.navigationLink": "https://toronto-bike-snapshot.sensorup.com/v1.0/Sensors(4)/Datastreams"
}]
}

how to explicitly set the Order property of class members using XmlElement asp.net

I am trying to serialize my code.
When I set the Order property of class members using XmlElement ASP.Net, I got exception on this line;
XmlSerializer serializer = new XmlSerializer(typeof(HotelListResponse));
Exception is;
Inconsistent sequencing: if used on one of the class's members,the 'Order' property is required on all particle-like members,please explicitly set 'Order' using XmlElement, XmlAnyElement or XmlArray custom attribute on class member '_hotelId'.
Code is:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
xmldoc = (XmlDocument)JsonConvert.DeserializeXmlNode(responsedata);
xmldoc.Save(#"C:\New folder\myfile.xml");
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("hotelId");
dt.Columns.Add("name");
dt.Columns.Add("address1");
dt.Columns.Add("address2");
dt.Columns.Add("city");
dt.Columns.Add("postalCode");
dt.Columns.Add("countryCode");
dr = dt.NewRow();
XmlSerializer serializer = new XmlSerializer(typeof(HotelListResponse));
Stream reader = new FileStream(#"C:\New folder\myfile.xml", FileMode.Open);
HotelListResponse htype = (HotelListResponse)serializer.Deserialize(reader);
dt.ReadXml(#"C:\New folder\myfile.xml");
foreach(hoteltype ht in htype.hotel){
GridView1.DataSource = dt;
GridView1.DataBind();
}
//responsereader.Close();
//request.GetResponse().Close();
}
}
catch (WebException ex)
{
if (ex.Response == null)
throw new NullReferenceException("WebException response");
throw ex;
}
}
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRoot("HotelListResponse")]
public class HotelListResponse
{
[System.Xml.Serialization.XmlElementAttribute("hotel")]
public hoteltype[] hotel;
[System.Xml.Serialization.XmlElement(Order = 0)]
public hoteltype[] Items {
get {
return this.hotel;
}
set {
this.hotel = value;
}
}
}
[Serializable]
[XmlType("hoteltype")]
public class hoteltype
{
hoteltype(){}
public int _hotelId;
public string _name;
public string _address1;
public string _address2;
public string _city;
public int _postalCode;
public string _countryCode;
[XmlElement]
public hoteltype[] htype;
[System.Xml.Serialization.XmlElement(Order=1)]
public int hotelId
{
get {
return _hotelId;
}
set{
_hotelId = value;
}
}
[System.Xml.Serialization.XmlElement(Order=2)]
public string name
{
get
{
return _name;
}
set
{
_name = value;
}
}
[System.Xml.Serialization.XmlElement(Order=3)]
public string address1
{
get
{
return _address1;
}
set
{
_address1 = value;
}
}
[System.Xml.Serialization.XmlElement(Order=4)]
public string address2
{
get
{
return _address2;
}
set
{
_address2 = value;
}
}
[System.Xml.Serialization.XmlElement(Order=5)]
public string city
{
get
{
return _city;
}
set
{
_city = value;
}
}
[System.Xml.Serialization.XmlElement(Order=6)]
public int postalCode
{
get
{
return _postalCode;
}
set
{
_postalCode = value;
}
}
[System.Xml.Serialization.XmlElement(Order=7)]
public string countryCode
{
get
{
return _countryCode;
}
set
{
_countryCode = value;
}
}
}
As described in the exception, as soon as you use Order=xx, all of the serializable properties and fields on the class must be ordered. However, it seems that _hotelId may have been intended to be a private backing field. Since XmlSerializer serializes public fields as well, this may be unintentional. If _hotelId really must be public but you don't want it serialized, then you can use XmlIgnore.
I'm guessing your class might look something like:
[System.SerializableAttribute()]
public partial class HotelListResponse
{
[System.Xml.Serialization.XmlElement(Order = 0)]
public string SomeOrderedField
{
get;
set;
}
// ** Problem may be here
// Because the field is public, XmlSerializer will try to serialize this
public int _hotelId;
[System.Xml.Serialization.XmlElement(Order = 1)]
public int HotelId
{
get
{
return _hotelId;
}
set
{
_hotelId = value;
}
}
Edit Yes, that's exactly the problem
Make your backing fields private - that's why you've got the public Property accessors for.
public int _hotelId; => private int _hotelId;
public string _name; => private string _name;
etc.
Edit
[XmlElement(Order=0)]
public hoteltype[] htype;
I would also change it to a property at the same time. Use the automatic backing fields if you are using .NET 3.5 or higher.
[XmlElement(Order=0)]
public hoteltype[] htype
{
get;
set;
}
Edit
If you applied the above systematically, your serializable classes should look like:
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRoot("HotelListResponse")]
public class HotelListResponse
{
// This is bad practice - never make a backing field public
//[System.Xml.Serialization.XmlElementAttribute("hotel")]
//public hoteltype[] hotel;
// Use the >= .Net 3.5 automatic properties - this way you don't need
// the backing field at all, which will prevent confusion over
// 'what gets serialized'
[System.Xml.Serialization.XmlElement(Order = 0)]
public hoteltype[] Items
{
get;
set;
}
}
[Serializable]
[XmlType("hoteltype")]
public class hoteltype
{
public hoteltype() { }
[System.Xml.Serialization.XmlElement(Order = 0)]
public hoteltype[] htype
{
get;
set;
}
[System.Xml.Serialization.XmlElement(Order = 1)]
public int hotelId
{
get;
set;
}
[System.Xml.Serialization.XmlElement(Order = 2)]
public string name
{
get;
set;
}
[System.Xml.Serialization.XmlElement(Order = 3)]
public string address1
{
get;
set;
}
[System.Xml.Serialization.XmlElement(Order = 4)]
public string address2
{
get;
set;
}
[System.Xml.Serialization.XmlElement(Order = 5)]
public string city
{
get;
set;
}
[System.Xml.Serialization.XmlElement(Order = 6)]
public int postalCode
{
get;
set;
}
[System.Xml.Serialization.XmlElement(Order = 7)]
public string countryCode
{
get;
set;
}
}
And testing the above via a serialize / deserialize cycle like so:
XmlSerializer serializer = new XmlSerializer(typeof(HotelListResponse));
HotelListResponse X = new HotelListResponse();
X.Items = new hoteltype[2];
X.Items[0] = new hoteltype();
X.Items[0].address1 = "address1";
X.Items[1] = new hoteltype();
X.Items[1].address1 = "address2";
using (Stream writer = new FileStream(#"C:\temp\myfile.xml", FileMode.Create))
{
serializer.Serialize(writer, X);
writer.Flush();
}
Stream reader = new FileStream(#"C:\temp\myfile.xml", FileMode.Open);
HotelListResponse htype = (HotelListResponse)serializer.Deserialize(reader);
The following file Deserializes:
<?xml version="1.0"?>
<HotelListResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<hotelId>0</hotelId>
<address1>address1</address1>
<postalCode>0</postalCode>
</Items>
<Items>
<hotelId>0</hotelId>
<address1>address2</address1>
<postalCode>0</postalCode>
</Items>
</HotelListResponse>

Resources