Web User Control Collection data is not storing - c#

I wanted to create a web control which has collection featured in the ASPX. I have code below which has a problem.
I seem to turn off and objects collection editor(collection stable).But I object design information Design Time at runtime what you can not get
when I turn off the project.So in a way the information will be saved during design is disappear.
When I open the project files in aspx file nor what. Designer.cs do not coincide in any record in the file.
I want to show in the picture below, this situation partially.
Based on the above, or as seen in the example in asp.net collection listing on sample collection can fix or waiting for your advice.
Here is code
//******************************************************Rol.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SANNET.ToolBox.TemelRoller
{/*
[ControlBuilder(typeof(ListItemControlBuilder))]
[ParseChildren(true, "Text")]*/
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Rol
{
private string rolAdi;
private AksiyonTuru aksiyonIcinKullan;
private EfektTuru iseYapilacak;
private string hataMesaji;
private IOzelEfekt ozelEfekt;
public String RolAdi { get { return rolAdi; } set { rolAdi = value; } }
public AksiyonTuru AksiyonIcinKullan { get { return aksiyonIcinKullan; } set { aksiyonIcinKullan = value; } }
public EfektTuru IseYapilacak { get { return iseYapilacak; } set { iseYapilacak = value; } }
public String HataMesaji { get { return hataMesaji; } set { hataMesaji = value; } }
public IOzelEfekt OzelEfekt { get { return ozelEfekt; } set { ozelEfekt = value; } }
public Rol()
{
RolAdi = "Hicbiri";
}
/*
public string GetAttribute(string key)
{
return (String)ViewState[key];
}
public void SetAttribute(string key, string value)
{
ViewState[key] = value;
}*/
}
}
//******************************************************RolListesi.cs
using SANNET.ToolBox.Yardimcilar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI;
namespace SANNET.ToolBox.TemelRoller
{
//[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class RolListesi : CollectionBase//ICollection<Rol>
{
private Collection<Rol> roller;
private Control parent;
public RolListesi(Control parent)
{
this.parent = parent;
parent.PreRender += parent_PreRender;
parent.Load += parent_PreRender;
roller = new Collection<Rol>();
}
void parent_PreRender(object sender, EventArgs e)
{
RolIslemleri.PreRenderIsle((Control)sender, this);
}
public Control Parent { get { return this.parent; } }
public Rol rolGetir(String rolAdi)
{
foreach (Rol r in roller) {
if (r.RolAdi.Equals(rolAdi))
return r;
}
return null;
}
public bool Contains(String rolAdi)
{
return rolGetir(rolAdi) != null;
}
public Rol this[int index]
{
get { return (Rol)roller[index]; }
}
public void Add(Rol emp)
{
roller.Add(emp);
}
public void Remove(Rol emp)
{
roller.Remove(emp);
}
}
}
//******************************************************RolCollectionEditor.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SANNET.ToolBox.TemelRoller
{
public class RolCollectionEditor : CollectionEditor
{
public RolCollectionEditor(Type type)
: base(type)
{
}
protected override string GetDisplayText(object value)
{
Rol item = new Rol();
item = (Rol)value;
return base.GetDisplayText(string.Format("{0}, {1}", item.RolAdi,
item.AksiyonIcinKullan));
}
}
}
//******************************************************SANButton.cs
using DevExpress.Web.ASPxEditors;
using SANNET.ToolBox.TemelRoller;
using System.ComponentModel;
using System.Web.UI;
namespace SANNET.ToolBox.Bilesenler
{
public class SANButton : ASPxButton, IRolSahibi
{
private RolListesi roller;
/* [Editor(typeof(System.ComponentModel.Design.CollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]*/
[Editor(typeof(RolCollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public RolListesi Roller { get {
if (roller == null)
{
roller = new RolListesi(this);
}
return roller; } }
}
}

The answer is
[PersistenceMode(PersistenceMode.InnerProperty)]
Here is sample usage
private Roller roller;
[Editor(typeof(RolCollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[PersistenceMode(PersistenceMode.InnerProperty)]
public Roller Roller
{
get
{
if (roller == null)
{
roller = new Roller();
} return roller;
}
}

Related

What is the required parameter for casting C#

Minimal reproducible example
Base abstract class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace YangHandlerTool
{
public abstract class YangNode
{
public string Name { get; set; }
/// <summary>
/// This is here to force YangNode constructor with Name parameter.
/// </summary>
private YangNode() { }
public YangNode(string name) { Name = name; }
}
}
Child that adds "Type" property
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace YangHandlerTool
{
public class Leaf : YangNode
{
public string Type { get; set; }
public Leaf(string leafname) : base(leafname){ }
}
}
Other Child that adds "Type" property
using System;
namespace YangHandlerTool
{
public class LeafList : YangNode
{
public string Type { get; set; }
public LeafList(string leafname) : base(leafname) { }
}
}
Main
using System;
using System.Collections.Generic;
namespace YangHandlerTool
{
class Program
{
static void Main(string[] args)
{
List<YangNode> yangnodes = new List<YangNode>();
yangnodes.Add(new Leaf("leafname"));
for (int i = 0; i < yangnodes.Count; i++)
{
if (IsLeaf(i))
{
///I want to call SetTypeOfNode with the intention to cast to Leaf
SetTypeOfNode(yangnodes[i]);
}
if (IsLeafList(i))
{
///I want to call SetTypeOfNode with the intention to cast to LeafList
SetTypeOfNode(yangnodes[i]);
}
}
}
private static void SetTypeOfNode(YangNode inputnode)
{
///Desired
//Replace GIVENANYCLASSNAME with any given classname as parameter
//((GIVENANYCLASSNAME)inputnode).Type = "value";
((Leaf)inputnode).Type = "value";
}
/// <summary>
/// It is 100% guaranteed that the item is a Leaf.
/// </summary>
private static bool IsLeaf(int index)
{
return index == 0;
}
private static bool IsLeafList(int index)
{
return index == 1;
}
}
}
In the function "private static void SetTypeOfNode(YangNode inputnode)" I want to be able to give a Class as parameter what to cast to. In order to spare 100+ line in my actual program of casting like:
((Leaf)inputnode).Type = "value";
((LeafList)inputnode).Type = "value";
((AnothertypeInheritedfromYangnode)inputnode).Type = "value";
((AnothertypeInheritedfromYangnode2)inputnode).Type = "value";
...
How can you pass a Classname as parameter that can be given into the casting parameter?

Missing bracket in C# because of Windows IoT background task?

I have created a test app for my first Windows IoT project with raspberry pi and an ultrasonic sensor.
I have placed some sample code in it. Visual Studio tells me that I am missing a curly bracket in "public void run…", but that doesn't seem to be the problem.
Is it because of the public class within the BackgroundTaskInstance?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Windows.ApplicationModel.Background;
using Windows.Devices.Gpio;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
// The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409
namespace IoTtest
{
public sealed class StartupTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
public class HCSR04
{
private GpioPin triggerPin { get; set; }
private GpioPin echoPin { get; set; }
private Stopwatch timeWatcher;
public HCSR04(int triggerPin, int echoPin)
{
GpioController controller = GpioController.GetDefault();
timeWatcher = new Stopwatch();
//initialize trigger pin.
this.triggerPin = controller.OpenPin(triggerPin);
this.triggerPin.SetDriveMode(GpioPinDriveMode.Output);
this.triggerPin.Write(GpioPinValue.Low);
//initialize echo pin.
this.echoPin = controller.OpenPin(echoPin);
this.echoPin.SetDriveMode(GpioPinDriveMode.Input);
}
public double GetDistance()
{
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(500);
timeWatcher.Reset();
//Send pulse
this.triggerPin.Write(GpioPinValue.High);
mre.WaitOne(TimeSpan.FromMilliseconds(0.01));
this.triggerPin.Write(GpioPinValue.Low);
return this.PulseIn(echoPin, GpioPinValue.High);
}
private double PulseIn(GpioPin echoPin, GpioPinValue value)
{
var t = Task.Run(() =>
{
//Recieve pusle
while (this.echoPin.Read() != value)
{
}
timeWatcher.Start();
while (this.echoPin.Read() == value)
{
}
timeWatcher.Stop();
//Calculating distance
double distance = timeWatcher.Elapsed.TotalSeconds * 17000;
return distance;
});
bool didComplete = t.Wait(TimeSpan.FromMilliseconds(100));
if (didComplete)
{
return t.Result;
}
else
{
return 0.0;
}
}
}
}
}
I took the code and reformatted it for you. Please change the namespace to the value you would like
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace MyIotNamespace
{
public sealed class StartupTask :IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
}
}
public class HCSR04
{
private GpioPin triggerPin { get; set; }
private GpioPin echoPin { get; set; }
private Stopwatch timeWatcher;
public HCSR04(int triggerPin, int echoPin)
{
GpioController controller = GpioController.GetDefault();
timeWatcher = new Stopwatch();
//initialize trigger pin.
this.triggerPin = controller.OpenPin(triggerPin);
this.triggerPin.SetDriveMode(GpioPinDriveMode.Output);
this.triggerPin.Write(GpioPinValue.Low);
//initialize echo pin.
this.echoPin = controller.OpenPin(echoPin);
this.echoPin.SetDriveMode(GpioPinDriveMode.Input);
}
public double GetDistance()
{
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(500);
timeWatcher.Reset();
//Send pulse
this.triggerPin.Write(GpioPinValue.High);
mre.WaitOne(TimeSpan.FromMilliseconds(0.01));
this.triggerPin.Write(GpioPinValue.Low);
return this.PulseIn(echoPin, GpioPinValue.High);
}
private double PulseIn(GpioPin echoPin, GpioPinValue value)
{
var t = Task.Run(() =>
{
//Recieve pusle
while(this.echoPin.Read() != value)
{
}
timeWatcher.Start();
while(this.echoPin.Read() == value)
{
}
timeWatcher.Stop();
//Calculating distance
double distance = timeWatcher.Elapsed.TotalSeconds * 17000;
return distance;
});
bool didComplete = t.Wait(TimeSpan.FromMilliseconds(100));
if(didComplete)
{
return t.Result;
}
else
{
return 0.0;
}
}
}
}
Nested class can't exist inside functions. Place HCSR04 inside StartupTask instead.
See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/nested-types

Xamarin SQLite Database Check

I am new to Xamarin. I want to confirm if the database is created and if the data is being inserted to the SQLite database. Thank you for the help
Questions:
1. How to check if database exist/created or not?
2. How to check if the user are inserted successfully or it failed?
3. Where do these file go in my phone?
Below is my code:
App.xaml.cs
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using TBSMobileApplication.Views;
using TBSMobileApplication.Data;
[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
namespace TBSMobileApplication
{
public partial class App : Application
{
static TokenDatabaseController tokenDatabase;
static UserDatabaseController userDatabase;
public App ()
{
InitializeComponent();
MainPage = new LoginPage();
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
public static UserDatabaseController UserDatabase
{
get
{
if(userDatabase == null)
{
userDatabase = new UserDatabaseController();
}
return userDatabase;
}
}
public static TokenDatabaseController TokenDatabase
{
get
{
if (tokenDatabase == null)
{
tokenDatabase = new TokenDatabaseController();
}
return tokenDatabase;
}
}
}
}
LoginPage.xaml.cs (Basically this is my Code behind in my login page)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBSMobileApplication.Models;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TBSMobileApplication.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage ()
{
InitializeComponent ();
}
void LoginProcedure(object sender, EventArgs e)
{
User user = new User(entUser.Text, entPassword.Text);
if (user.CheckInformation())
{
//DisplayAlert("Login Message", "Login Success", "Ok");
try
{
App.UserDatabase.SaveUser(user);
DisplayAlert("Database Message", "User Saved", "Ok");
}
catch(Exception ex)
{
DisplayAlert("Message", ex.Message, "Ok");
}
}
else
{
DisplayAlert("Login Message", "Login Failed", "Ok");
}
}
}
}
ISQLite.cs (This is where you get the connection to the database)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace TBSMobileApplication.Data
{
public interface ISQLite
{
SQLiteConnection GetConnection();
}
}
User.cs (This is where the parameters of the User table)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace TBSMobileApplication.Models
{
public class User
{
[PrimaryKey, AutoIncrement]
public int ContactID { get; set; }
[Unique]
public string UserID { get; set; }
public string UserPassword { get; set; }
public User() { }
public User(string Username, string Password)
{
this.UserID = Username;
this.UserPassword = Password;
}
public bool CheckInformation()
{
if(!this.UserID.Equals("") || !this.UserPassword.Equals(""))
{
return true;
}
else
{
return false;
}
}
}
}
SQLite_Android.cs (This is where I created the database)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using TBSMobileApplication.Data;
using TBSMobileApplication.Droid.Data;
using Xamarin.Forms;
[assembly: Dependency(typeof(SQLite_Android))]
namespace TBSMobileApplication.Droid.Data
{
public class SQLite_Android : ISQLite
{
public SQLite_Android() { }
public SQLite.SQLiteConnection GetConnection()
{
var DBFileName = "backend.db3";
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(DocumentPath, DBFileName);
var conn = new SQLite.SQLiteConnection(path);
return conn;
}
}
}
UserDatabaseController.cs (This is where I control User table like adding, deleting or getting data from User table)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using TBSMobileApplication.Models;
using Xamarin.Forms;
namespace TBSMobileApplication.Data
{
public class UserDatabaseController
{
static object locker = new object();
SQLiteConnection database;
public UserDatabaseController()
{
database = DependencyService.Get<ISQLite>().GetConnection();
database.CreateTable<User>();
}
public User GetUser()
{
lock (locker)
{
if(database.Table<User>().Count() == 0)
{
return null;
}
else
{
return database.Table<User>().First();
}
}
}
public int SaveUser(User user)
{
lock (locker)
{
if (user.ContactID != 0)
{
database.Update(user);
return user.ContactID;
}
else
{
return database.Insert(user);
}
}
}
public int DeleteUser(int contactid)
{
lock (locker)
{
return database.Delete<User>(contactid);
}
}
}
}
Starting with part 3 of your question - where is the database file? - it's here:
var DBFileName = "backend.db3";
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
That equates to:
/data/data/[your.package.name]/files/backend.db3
For the first part of your question, to check whether the database has been created, just check whether the file exists:
public static bool DBExists()
{
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(DocumentPath, "backend.db3");
return File.Exists(path);
}
Accessing the file there is somewhere between difficult and impossible without a rooted device. You're not supposed to be able to access files there - only your app can access them. It's a safety measure.
Your application doesn't have any trouble accessing the database file, though, so you can implement a method in your application to copy it somewhere more accessible (e.g. the Downloads directory).
Put this in your Android project:
public static void CopyDBToDownloadsDirectory()
{
var path = System.IO.Path.Combine(
Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath,
"backend.db3");
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var safePath = Path.Combine(DocumentPath, "backend.db3");
File.Copy(safePath, path, true);
}
Call it to create a copy of the database you can readily access on the phone's built-in file browser.
So, for part 2 of the question, whether a transaction succeeded or failed, you can either run queries against your database in code to check, or open a copy of the database file in a GUI and browse the data.

Property or indexer must have at least one accessor

I'm learning C#, trying to get to grips with accessors at the moment.
I'm going nuts looking at this, I have no idea what I've done wrong:
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
The Form looks like this:
public partial class BankForm : Form
{
private BankAccount _myAccount;
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
But I get this error:
Property or indexer must have at least one accessor
I'm not getting any errors. Move location of private BankAccount _myAccount;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BankForm
{
public partial class BankForm : Form
{
public BankForm()
{
InitializeComponent();
_myAccount = new BankAccount();
}
private BankAccount _myAccount;
private void initialDepositButton_Click(object sender, EventArgs e)
{
_myAccount.SavingsAccount = Convert.ToInt32(initialDepositTextBox.Text);
bankAccountListBox.Text = "Account opened with initial Deposit " + initialDepositTextBox.Text;
}
}
class BankAccount
{
// *PROPERTIES*
private int _initialDeposit = 0;
// **ACCESSORS**
public int SavingsAccount
{
set
{
_initialDeposit = value;
}
get
{
return _initialDeposit;
}
}
}
}
​

C# The type or namespace name could not be found

I have a problem that has been driving me nuts.
I have 2 ASPX pages in which the parent use Server.Transfer() function. The parent is called Submit.aspx whereas child is called Review.aspx
In Submit.aspx.cs, I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Contacts_Submit : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Review_Click(object sender, EventArgs e)
{
Server.Transfer("Review.aspx", true);
}
/*
* Sequence of functions that will server as a Get functionality that will
* return the text inside each textbox.
* These information will be used by "Review.aspx" to validate the
* information given by the user before final submission takes place.
*/
public string GetFirstName { get { return FirstName.Text; } }
public string GetLastName { get { return LastName.Text; } }
public string GetAddress { get { return Address.Text; } }
public string GetCountry { get { return Country.SelectedValue; } }
public string GetProvince { get { return Province.SelectedValue; } }
public string GetCity { get { return City.Text; } }
public string GetZipCode { get { return ZipCode.Text; } }
public string GetWorkPhone { get { return WorkPhone.Text; } }
public string GetMobilePhone { get { return MobilePhone.Text; } }
public string GetFax { get { return Fax.Text; } }
public string GetEmail { get { return Email.Text; } }
public string GetCompany { get { return Company.Text; } }
public string GetWebsite { get { return Website.Text; } }
public string GetRelationship { get { return Relationship.SelectedValue; } }
}
Whereas on the Review.aspx.cs, I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Contacts_Review : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if(PreviousPage != null)
{
Contacts_Submit prevpage = PreviousPage as Contacts_Submit;
//FirstName.Text = PreviousPage.GetFirstName;
}
}
}
The problem is when I declare "Contacts_Submit prevpage = PreviousPage as Contacts_Submit". The system is giving me an error that says "The type or namespace name 'Contacts_Submit' could not be found (are you missing a using directive or an assembly reference?)".
I am a beginner in both ASP.NET and C#, can anyone help me with this? Thank you SOOO MUCH.
I think you just want
Contacts_Submit prevpage = PreviousPage as Contacts_Submit;
instead of
Contacts_Submit prevpage = PreviousPage as System.Data.DataSet Contacts_Submit;
Contacts_Submit is type of Page and not in any way related to Dataset, so your cast is invalid.
remove that and it should be fine

Categories

Resources