Access to class into UserControl (C# WinForms) - c#

I edit my question fo show details. Now it code work, but I wont know, may be I done incorrect architecture?
Main form:
public partial class MainForm1 : Form
{
public MainForm1()
{
InitializeComponent();
string errorMessage = "";
DeviceInitControl.BO.BO_GetParams deviceParams;
SerialPortInitControl.BO.BO_GetParams serialPortParams;
HttpClientInitControl.BO.BO_GetParams httpClientParams;
if (USC_AddDeviceControl.deviceInitParams.GetValues(out deviceParams, ref errorMessage))
{
//Device init
}
else
{
errorMessage = "Device initialisation parametrs error! " + errorMessage;
}
if (USC_AddDeviceControl.serialPortInitParams.GetValues(out serialPortParams, ref errorMessage))
{
//Serial port init
}
else
{
errorMessage = "Serial port initialisation parametrs error! " + errorMessage;
}
if (USC_AddDeviceControl.httpClientInitParams.GetValues(out httpClientParams, ref errorMessage))
{
//Http client init
}
else
{
errorMessage = "Http client initialisation parametrs error! " + errorMessage;
}
if (String.IsNullOrEmpty(errorMessage))
{
//Next step
}
else
{
//Show errorMessage to logs
}
}
}
User control USC_AddDeviceControl contain other UserControls (DeviceInitControl, SerialPortInitControl and HttpClientInitControl).
public partial class SerialPortInitControl : UserControl
{
public class BO
{
public enum BO_Language
{
RUS,
EN
}
public class BO_Init
{
public class CbxItems
{
public string[] names;
public string[] baudRates;
public string[] parities;
public string[] dataBits;
public string[] stopBits;
}
public CbxItems cbxItems = new CbxItems();
}
public class BO_GetParams
{
public string name;
public string baudRate;
public string paritie;
public string dataBits;
public string stopBits;
}
/*
public class BO_SetParams
{
//Some controls in UserControlLibrary can contain it class
}
*/
}
public SerialPortInitControl()
{
InitializeComponent();
}
public void Init(in BO.BO_Language language, in BO.BO_Init initParams) // This methode is public because I can not initialisaion UserControl in constructor, because constructor can not take a parametrs
{
ControlsInit(in initParams);
SetLanguage(in language);
void ControlsInit(in BO.BO_Init controlsParams)
{
CbxInit(in controlsParams.cbxItems); //Some controls in UserControlLibrary can contain TextBox, DataGridView and other
void CbxInit(in BO.BO_Init.CbxItems items)
{
CBX_Name.Items.AddRange(items.names);
CBX_BaudRate.Items.AddRange(items.baudRates);
CBX_Parity.Items.AddRange(items.parities);
CBX_DataBits.Items.AddRange(items.dataBits);
CBX_StopBits.Items.AddRange(items.stopBits);
}
}
}
public void SetLanguage(in BO.BO_Language language)
{
switch (language)
{
case BO.BO_Language.RUS:
{
LBL_Name.Text = "Имя порта";
LBL_BaudRate.Text = "Скорость";
LBL_Parity.Text = "Бит четности";
LBL_DataBits.Text = "Бит данных";
LBL_StopBits.Text = "Стоп бит";
}
break;
case BO.BO_Language.EN:
{
LBL_Name.Text = "Port name";
LBL_BaudRate.Text = "Baud rate";
LBL_Parity.Text = "Parity";
LBL_DataBits.Text = "Data bits";
LBL_StopBits.Text = "Stop bits";
}
break;
default:
{
throw new Exception("Control language is not define!");
}
break;
}
}
public bool GetParams(out BO.BO_GetParams values, ref string errorMessage)
{
if (CheckGetParams(out values, ref errorMessage))
{
values = new BO.BO_GetParams()
{
name = CBX_Name.Text,
baudRate = CBX_BaudRate.Text,
paritie = CBX_Parity.Text,
dataBits = CBX_DataBits.Text,
stopBits = CBX_StopBits.Text,
};
return true;
}
else
{
values = null;
errorMessage = "Checking failed! " + errorMessage;
return false;
}
bool CheckGetParams(out BO.BO_GetParams values, ref string errorMessage)
{
values = new BO.BO_GetParams();
bool valid = true;
if (string.IsNullOrEmpty(CBX_Name.Text)) { valid = false; errorMessage = "Name field is null or empty! "; }
if (string.IsNullOrEmpty(CBX_BaudRate.Text)) { valid = false; errorMessage = "BaudRate field is null or empty! "; }
if (string.IsNullOrEmpty(CBX_Parity.Text)) { valid = false; errorMessage = "Parity field is null or empty! "; }
if (string.IsNullOrEmpty(CBX_DataBits.Text)) { valid = false; errorMessage = "DataBits field is null or empty! "; }
if (string.IsNullOrEmpty(CBX_StopBits.Text)) { valid = false; errorMessage = "StopBits field is null or empty! "; }
return valid;
}
}
/*
public bool SetParams(in BO.BO_SetParams values, ref string errorMessage)
{
if (CheckSetValues(in values, ref errorMessage))
{
return true;
}
else
{
errorMessage = "Checking failed! " + errorMessage;
return false;
}
bool CheckSetParams(in BO.BO_SetParams values, ref string errorMessage)
{
errorMessage = "Methode is not defined! ";
return false;
}
}
*/
}
What you mean correct/modify in this code?
I trying write clear code and need a help for it.
Thank`s!

Your UserControl hasn't instance of BO class. You just define BO class inside SerialPortInitControl, so when you will create instanse of it, it will be like this:
var instBO = new SerialPortInitControl.BO.BO_GetValues()
so, you created object of BO class, but when you stored it in UserConrol?
public partial class SerialPortInitControl : UserControl
{
public class BO
{
public class BO_GetValues
{
public string name;
public string baudRate;
public string paritie;
public string dataBits;
public string stopBits;
}
}
//instance of BO class
public BO BO_Instanse {get;}
//instance of BO.Get_Values class
public BO.BO_GetValues BO_GetValues_Instanse {get;}
public SerialPortInitControl()
{
InitializeComponent();
BO_Instanse = new BO();
BO_GetValues_Instanse = new BO.BO_GetValues();
}
public bool GetValues(out BO.BO_GetValues values, ref string errorMessage)
{
if(BO_Instanse == null)//need real code here
{
values = new BO.BO_GetValues()
{
name = CBX_Name.Text,
baudRate = CBX_BaudRate.Text,
paritie = CBX_Parity.Text,
dataBits = CBX_DataBits.Text,
stopBits = CBX_StopBits.Text,
};
return true;
}
else
{
values = null;
errorMessage = "Checking failed! " + errorMessage;
return false;
}
}
}
So, this will works:
var control = new SerialPortInitControl();
var bo = control.BO_Instanse;
var bo_values = control.BO_GetValues_Instanse;
Also you can create instances of you classes without UserControl class:
var boInstanse = new SerialPortInitControl.BO();
var boGetValues_Instanse = new SerialPortInitControl.BO.BO_GetValues();

public class Personmodel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string NickName { get; set; }
public int Points { get; set; }
public int CurrLevel { get; set; }
public int CurrClass { get; set; }
public List<AvatarPicture> Avatars { get; set; } = new List<AvatarPicture>();
public string FullName
{
get { return $"{ FirstName } { LastName }"; }
}
}

Related

how to write specific C# property value in json format?

I have some Properties and i want to save some specific property value in json format.Here is my code and i want to save two properties value like SelectedScalesModel and SelectedScales port Can anyone help me with this.
public class SetUpViewModel : ViewModelBase
{
public List<string> ScalesModel { get; set; } = new List<string> { "None", "METTLER-TOLEDO", "DINI ARGEO DFW-DFWK", "ESSAE SI-810" };
private string _selectedScalesModel;
public string SelectedScalesModel
{
get { return _selectedScalesModel; }
set
{
_selectedScalesModel = value;
RaisePropertyChanged("SelectedScalesModel");
}
}
public List<string> ScalesPort { get; set; } = new List<string> { "None", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM10", "COM11", "COM12", "COM13", "COM14", "COM15" };
private string _selectedScalesPort;
public string SelectedScalesPort
{
get { return _selectedScalesPort; }
set
{
_selectedScalesPort = value;
RaisePropertyChanged("SelectedScalesPort");
}
}
string _text1;
public string BlackLineText
{
get { return _text1; }
set
{
_text1 = value;
RaisePropertyChanged(nameof(BlackLineText));
}
}
public RelayCommand SaveButtonCommand { get; private set; }
public SetUpViewModel()
{
SaveButtonCommand = new RelayCommand(SaveCommand);
}
private void SaveCommand()
{
SetUpViewModel setUpobj = new SetUpViewModel();
string strJsonResult = JsonConvert.SerializeObject(setUpobj);
File.WriteAllText("setup.json", strJsonResult);
MessageBox.Show("File save in Json Format");
}
}
You can try to SerializeObject by anonymous class then carry your expect property instead of SetUpViewModel object.
private void SaveCommand()
{
string strJsonResult = JsonConvert.SerializeObject(
new {
SelectedScalesModel = this.SelectedScalesModel,
SelectedScalesPort = this.SelectedScalesPort
}
);
File.WriteAllText("setup.json", strJsonResult);
MessageBox.Show("File save in Json Format");
}
Note
use this because your property info in your object.

Xamarin rest web service doesn't deserialize

I want to use rest with get method. My code is below;
public class RegisterPage : ContentPage
{
Label label, l4, label2;
public RegisterPage()
{
Button btn = new Button
{
Text = "register"
};
btn.Clicked += Btn_Clicked;
label = new Label();
l4 = new Label();
label2 = new Label();
Content = new StackLayout
{
Children = {
btn,
label,
l4,
label2
}
};
}
private async void Btn_Clicked(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add(Constants.API_KEY_HEADER_KEY, Constants.API_KEY);
string URL = Constants.URL;
var response = await client.GetAsync(URL);
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Models.Result>(content);
label.Text = result.Success.ToString();
l4.Text = result.Error.ToString();
label2.Text = ((RegisteredDevice)result.Retval).Clientuuid + " - " + ((RegisteredDevice)result.Retval).Deviceuuid;
}
}
The url is working good. And my content value has json string. But the serialization is not working.
var result = JsonConvert.DeserializeObject(content);
This code doesn't deserilize.
My model is;
public class Result
{
private object retval = null;
private bool success = false;
private Error error = null;
internal Error Error
{
get { return error; }
set { error = value; }
}
public bool Success
{
get { return success; }
set { success = value; }
}
public object Retval
{
get { return retval; }
set { retval = value; }
}
}
Json:
{
"result":{
"retail":{
"#xsi.type":"registeredDevice",
"clientuuid":"28asgargb-acfe‌​-41dfgsdg51",
"deviceuuid":123456
},
"success":true
}
}
I think the problem comes from :
private object retval = null;
So for me the best way to construct serialization objects in C# is to use this web site :
http://json2csharp.com/
This will tell you if your json is correct and he will generate the classes you need for you, here the classes generated by json2csharp
public class Retail
{
public string __invalid_name__#xsi.type { get; set; }
public string clientuuid { get; set; }
public int deviceuuid { get; set; }
}
public class Result
{
public Retail retail { get; set; }
public bool success { get; set; }
}
public class RootObject
{
public Result result { get; set; }
}

Why are the values not showing up in my C# program's read-only labels?

I have been working on a program that requires two class definitions (clsCustomer and clsOrder) and a driver that is used for simulating an order form that calculates totals and prints a mailing label. The instructor provided partial code and I got rid of the previous errors that it had, but when I run the program and enter the information (name, address, quantity, price, etc.) only a "." shows up as the mailing label and both the extension and total price appear as "0.00". I tried playing with it and cannot seem to fix the issue. Here is the code:
namespace CS8
{
public partial class frmCS8 : Form
{
public frmCS8()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
string strMailingLabel;
try
{
//Create an instance of clsCustomer using the overloaded constructor
clsCustomer cobjCustomer = new clsCustomer(txtName.Text, txtStreet.Text,
txtCity.Text, txtState.Text, txtZip.Text);
//Build mailing label using the Get methods for Customer.
strMailingLabel = cobjCustomer.Name + "\n" +
cobjCustomer.Street + "\n" +
cobjCustomer.City + ", " +
cobjCustomer.State + " " + cobjCustomer.Zip;
//Display mailing address
lblMailingLabel.Text = strMailingLabel;
//Create an instance of clsOrder using the overloaded constructor
clsOrder cobjOrder = new clsOrder
(txtDescription.Text,
int.Parse(txtQuantity.Text),
decimal.Parse(txtPrice.Text));
//Test the calculate Extended Price method
cobjOrder.calcExtendedPrice();
//Update the totals in shared variables.
cobjOrder.accumulateTotals();
//Test the Get property method of extended priced
lblExtension.Text = cobjOrder.ExtendedPrice.ToString("C");
//Shared properties are accessed using class name
//Test the Get Property methods of ReadOnly Shared properties
lblTotalCount.Text = clsOrder.TotalCount.ToString("N0");
lblTotalPrice.Text = clsOrder.TotalPrice.ToString("C");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message
+ "\n" + ex.StackTrace,
"Try/Catch - Unexpected Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}//end try
}
private void btnNextItem_Click(object sender, EventArgs e)
{
//clear the item fields
txtDescription.Clear();
txtQuantity.Clear();
txtPrice.Clear();
lblExtension.Text = "";
txtDescription.Focus();
}
private void btnResetSummary_Click(object sender, EventArgs e)
{
//Reset totals using the class name to access the shared method
clsOrder.resetTotals();
lblTotalPrice.Text = "";
lblTotalCount.Text = "";
lblMailingLabel.Text = "";
//Clear the rest of the form using next item method
btnNextItem_Click(sender, e);
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
namespace CS8
{
public class clsOrder
{
//declare class variables
protected string cstrDescription;
protected int cintQuantity;
protected decimal cdecPrice;
protected decimal cdecExtendedPrice;
//shared variables
static decimal cdecTotalPrice;
static int cintTotalCount;
//declare constructors
public clsOrder()
{
}
public clsOrder(string strDescription,
int intQuantity, decimal decPrice)
//declare property methods
{
this.Description = cstrDescription;
this.Quantity = cintQuantity;
this.Price = cdecPrice;
}
//declare read-only properties
public decimal ExtendedPrice
{
get
{
return cdecExtendedPrice;
}
set
{
cdecExtendedPrice = value;
}
}
public string Description
{
get
{
return cstrDescription;
}
set
{
cstrDescription = value;
}
}
public int Quantity
{
get
{
return cintQuantity;
}
set
{
cintQuantity = value;
}
}
public decimal Price
{
get
{
return cdecPrice;
}
set
{
cdecPrice = value;
}
}
//declare Shared (static) ReadOnly Properites
public static decimal TotalPrice
{
get
{
return cdecTotalPrice;
}
}
public static int TotalCount
{
get
{
return cintTotalCount;
}
set
{
cintTotalCount = value;
}
}
//declare supporting methods
public void calcExtendedPrice()
{
cdecExtendedPrice = cintQuantity * cdecPrice;
}
public void accumulateTotals()
{
cdecTotalPrice += cdecExtendedPrice;
cintTotalCount += 1;
}
public static void resetTotals()
{
cdecTotalPrice = 0;
cintTotalCount = 0;
}
}//end of Class
}//end of namespace
namespace CS8
{
public class clsCustomer
{
//declare class variables
private string cstrName;
private string cstrStreet;
private string cstrCity;
private string cstrState;
private string cstrZip;
//declare constructors
public clsCustomer()
{
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
{
this.Name = cstrName;
this.Street = cstrStreet;
this.City = cstrCity;
this.State = cstrState;
this.Zip = cstrZip;
}
public string Name
{
get
{
return cstrName;
}
set
{
cstrName = value;
}
}
public string Street
{
get
{
return cstrStreet;
}
set
{
cstrStreet = value;
}
}
public string City
{
get
{
return cstrCity;
}
set
{
cstrCity = value;
}
}
public string State
{
get
{
return cstrState;
}
set
{
cstrState = value;
}
}
public string Zip
{
get
{
return cstrZip;
}
set
{
cstrZip = value;
}
}
}
}
Any assistance would be very much appreciated...
Use parameters, not class fields:
public clsOrder(string strDescription,
int intQuantity, decimal decPrice)
{
this.Description = strDescription;
this.Quantity = intQuantity;
this.Price = decPrice;
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
{
this.Name = strName;
this.Street = strStreet;
this.City = strCity;
this.State = strState;
this.Zip = strZip;
}

How I will generate Xml For the Below code ... code for void getxml() method inside Order class which depends upon Delivery & Recipient Class

public class OrderXml
{
public enum DeliveryType { FTP, Email, HDD, Tape, Aspera, MLT };
public class Order
{
public int UserId { get; private set; }
public int OrderBinId { get; private set; }
public int TenantId { get; private set; }
public Delivery Delivery { get; set; }
public Recipient Recipient { get; private set; }
public string[] AssetDmGuids { get; set; }
public Order(int orderBinId, string[] assetDmGuids, DeliveryType type, int recipientId, string recipientName)
{
Delivery = new Delivery(type);
Recipient = new Recipient(recipientId, recipientName);
// UserId = SessionHelper.Instance.GetUserId();
// TenantId = SessionHelper.Instance.GetTenantID().ToString();
OrderBinId = orderBinId;
AssetDmGuids = assetDmGuids;
}
public void GetXml()
{
}
}
public class Recipient
{
int _id;
string _name = string.Empty;
public Recipient(int id, string name)
{
this._id = id;
this._name = name;
}
public int Id { get { return _id; } }
public string Name { get { return _name; } }
}
public class Delivery
{
DeliveryType _deliveryType;
string _ftpLocation = string.Empty;
string _ftpPath = string.Empty;
string[] _emailAddresses;
string _deliveryAddress = string.Empty;
string _deliveryComments = string.Empty;
string _asperaLocation = string.Empty;
public string FtpPath
{
get { return _ftpPath; }
set { _ftpPath = value; }
}
public string[] EmailAddresses
{
get { return _emailAddresses; }
set { _emailAddresses = value; }
}
public string DeliveryAddress
{
get { return _deliveryAddress; }
set { _deliveryAddress = value; }
}
public string DeliveryComments
{
get { return _deliveryComments; }
set { _deliveryComments = value; }
}
public string AsperaLocation
{
get { return _asperaLocation; }
set { _asperaLocation = value; }
}
public string FtpLocation
{
get { return _ftpLocation; }
set { _ftpLocation = value; }
}
public Delivery(DeliveryType type)
{
_deliveryType = type;
}
}
public static void Main()
{
Order ord = new Order(1, new string[] { "123", "124", "125" }, DeliveryType.Tape, 1, "vh1");
}
}
public XmlDocument GetXml()
{
XmlDocument retValue = new XmlDocument();
try
{
XmlSerializer xs = new XmlSerializer(this.GetType());
Stream stream = new MemoryStream();
xs.Serialize( stream, toSerialize );
stream.Position = 0;
retValue.Load( stream );
}
catch (Exception ex)
{
}
return retValue;
}

Errors: How to save a many-to-many relationship in Castle Active Record?

I've been trying for hours to get many-to-many relationship to save with Castle ActiveRecord. What am I doing wrong? I can't find anything in the documentation or on google. There is data in the database.
Courses have a many to many relationship with Books.
Test code.
Database.Course c = new Database.Course();
c.Number = "CS 433";
c.Name = "Databases";
c.Size = 34;
c.Books = Database.Book.FindAll();
c.Save();
Also doesn't work
foreach(Database.Book b in Database.Book.FindAll()){
c.Books.Add(b);
}
Database Classes
[ActiveRecord]
public class Course : ActiveRecordValidationBase<Course>
{
private int? id;
private string number;
private string name;
private string description;
private int size; //number of students in class
//references
private IList books = new ArrayList();
public override string ToString()
{
return FormattedName;
}
public string FormattedName
{
get
{
return string.Format("{0} - {1}", Number, Name);
}
}
[PrimaryKey]
public int? Id
{
get { return id; }
set { id = value; }
}
[Property, ValidateNonEmpty]
public string Number
{
get { return number; }
set { number = value; }
}
[Property, ValidateNonEmpty]
public string Name
{
get { return name; }
set { name = value; }
}
[Property(ColumnType="StringClob")]
public string Description
{
get { return description; }
set { description = value; }
}
[Property]
public int Size
{
get { return size; }
set { size = value; }
}
[HasAndBelongsToMany(typeof(Book),
Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id", Inverse = true)]
public IList Books
{
get { return books; }
set { books = value; }
}
}
[ActiveRecord]
public class Book : ActiveRecordValidationBase<Book>
{
private int? id;
private string title;
private string edition;
private string isbn;
private bool is_available_for_order;
//relations
private IList authors = new ArrayList();
private IList bookordercount = new ArrayList();
private IList courses = new ArrayList();
private Inventory inventory;
public override string ToString()
{
return FormattedName;
}
public string FormattedName
{
//*
get {
string str;
if (Edition == null || Edition == "")
str = Title;
else
str = string.Format("{0} ({1})", Title, Edition);
if (Authors.Count != 0)
{
return string.Format("{0} by {1}", str, FormattedAuthors);
}
else
{
return str;
}
}
/*/
get
{
return Title;
}
//*/
}
public string FormattedAuthors
{
get
{
if (Authors.Count == 0) return "";
StringBuilder sb = new StringBuilder();
int i = 0, end = Authors.Count;
foreach (Author a in Authors)
{
i++;
sb.Append(a.FormattedName);
if (i != end) sb.Append("; ");
}
return sb.ToString();
}
}
[PrimaryKey]
public int? Id
{
get { return id; }
set { id = value; }
}
[Property, ValidateNonEmpty]
public string Title
{
get { return title; }
set { title = value; }
}
[Property]
public string Edition
{
get { return edition; }
set { edition = value; }
}
[Property, ValidateNonEmpty]
public string Isbn
{
get { return isbn; }
set { isbn = value; }
}
[Property]
public bool IsAvailableForOrder
{
get { return is_available_for_order; }
set { is_available_for_order = value; }
}
//relations
[HasAndBelongsToMany(typeof(Author),
Table = "BookAuthor", ColumnKey = "book_id", ColumnRef = "author_id")]
public IList Authors
{
get { return authors; }
set { authors = value; }
}
[HasMany(typeof(BookOrderCount), Table = "BookOrderCounts", ColumnKey = "BookId")]
public IList BookOrderCount
{
get { return bookordercount; }
set { bookordercount = value; }
}
[HasAndBelongsToMany(typeof(Course),
Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id")]
public IList Courses
{
get { return courses; }
set { courses = value; }
}
[OneToOne]
public Inventory Inventory
{
get { return inventory; }
set { inventory = value; }
}
}
Make sure you put the Inverse = true where you want it. From the Castle AR docs,
It is wise to choose one side of the
relation as the owner. The other side,
the non-writable, need to use
Inverse=true.
Put the Inverse = true on the other side of the relationship, like this:
[HasAndBelongsToMany(typeof(Book),
Table = "BookCourse", ColumnKey = "course_id", ColumnRef = "book_id")]
public IList<Book> Books
[HasAndBelongsToMany(typeof(Course),
Table = "BookCourse", ColumnKey = "book_id", ColumnRef = "course_id", Inverse = true)]
public IList<Course> Courses
You also have to add attributes to the top of both classes - at the moment they don't know what tables they're mapped to. Currently you have this:
public class Course : ActiveRecordBase<Course>
Add this (where "course" is the name of your Course table):
[ActiveRecord("course")]
public class Course : ActiveRecordBase<Course>

Categories