public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string Name { get; set; }
public string HasPrivateKey { get; set; }
public string Location { get; set; }
public string Issuer { get; set; }
private void button1_Click(object sender, EventArgs e)
{
var stores = new Dictionary<StoreName, string>()
{
{ StoreName.My,"Personal"},
{ StoreName.Root,"Trusted roots"},
{ StoreName.TrustedPublisher,"Trusted Publishers"}
}.Select(s => new { store = new X509Store(s.Key, StoreLocation.LocalMachine), Location = s.Value }).ToArray();
foreach (var store in stores)
store.store.Open(OpenFlags.ReadOnly);
var list = stores.SelectMany(s => s.store.Certificates.Cast<X509Certificate2>().Select(mCert => new Form1
{
HasPrivateKey = mCert.HasPrivateKey ? "Yes" : "No",
Name = mCert.FriendlyName,
Location = s.Location,
Issuer = mCert.Issuer
})).ToList();
}
}
I have used windows form application in c#.
If I click the button it has to display the available certificates present in local machine onto listbox. But I don't know how to display the available certificates.. Pls give suggestions.
You create a new Form1 instance for each certificate.
You do not refer to any existing listbox
try this:
public partial class Form1 : Form
{
//declare new listbox
ListBox lbCerts;
public Form1()
{
InitializeComponent();
//add a listbox to the form
lbCerts = new ListBox();
lbCerts.DisplayMember = "Name";
this.Controls.Add(lbCerts);
}
//class represent certificate
class myCer
{
public string Name { get; set; }
public string HasPrivateKey { get; set; }
public string Location { get; set; }
public string Issuer { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
var stores = new Dictionary<StoreName, string>()
{
{ StoreName.My,"Personal"},
{ StoreName.Root,"Trusted roots"},
{ StoreName.TrustedPublisher,"Trusted Publishers"}
}.Select(s => new { store = new X509Store(s.Key, StoreLocation.LocalMachine), Location = s.Value }).ToArray();
foreach (var store in stores)
store.store.Open(OpenFlags.ReadOnly);
//create list of myCer
var list = stores.SelectMany(s => s.store.Certificates.Cast<X509Certificate2>().Select(mCert => new myCer
{
HasPrivateKey = mCert.HasPrivateKey ? "Yes" : "No",
Name = mCert.FriendlyName,
Location = s.Location,
Issuer = mCert.Issuer
})).ToList();
//populate listbox
lbCerts.DataSource = list;
}
}
Related
I have two related classes:
public class Dealer {
public int Id { get; set; }
public string BaseUrl { get; set; }
public virtual ICollection<DealerAddress> DealerAddress { get; set; }
}
public class DealerAddress {
public int Id { get; set; }
public int DealerId { get; set; }
public string Email { get; set; }
public virtual Dealer Dealer { get; set; }
}
And in my form I want to display data from DealerAddress class:
public SortableBindingList<DealerAddress> Addresses = new SortableBindingList<DealerAddress>();
private void CreateDataGridView() {
dataGridViewPlaceHolderPanel.Visible = false;
dataGridView = new DataGridView();
dataGridView.Name = "dataGridView";
List<string> regularColumns = new List<string>()
{
nameof(DealerAddress.Id),
nameof(DealerAddress.DealerId),
nameof(DealerAddress.Dealer.BaseUrl),
nameof(DealerAddress.Email),
};
var columns = new List<DataGridViewTextBoxColumn>();
foreach (var regularColumnName in regularColumns)
{
var col = new DataGridViewTextBoxColumn
{
HeaderText = regularColumnName,
DataPropertyName = regularColumnName,
Name = "column" + regularColumnName
};
columns.Add(col);
}
}
public void SetAddresses(SortableBindingList<DealerAddress> addresses, int totalCount)
{
try
{
dataGridView.RowStateChanged -= DataGridView_RowStateChanged;
Addresses = addresses;
RefreshDataGridView();
}
finally
{
dataGridView.RowStateChanged += DataGridView_RowStateChanged;
}
}
private void RefreshDataGridView(){
if (Addresses == null || Addresses.Count == 0)
return;
dataGridView.DataSource = Addresses;
}
And the data displayed in my table is:
When I hit "SetAddresses", the data is populated from DealerAddress model, but it doesn't display column values from "DealerAddress.Dealer".
TL;DR
Quick fix it with the following. In your DealerAddres, add
public string BaseUrl
{
get => Dealer.BaseUrl;
set => Dealer.BaseUrl = value;
}
Explaining
You have two class DealerAddress and Dealer. You set a list of DealerAddress to the DataSource.
So when the DataGridView starts to render, it will search the properties in the first class.
When you do nameof(DealerAddress.Dealer.BaseUrl) you are actually telling, to the DataGridView, that the class DealerAddress contains that property --- which it does not.
See this for more information.
I'm sure I remember this being a threading issue, but I can't find an answer. It seems like it should be simple. I have the following code:
private void Dingle_Clicked(object sender, RoutedEventArgs e)
{
dynamic doc = ScraperBrowser.Document;
string htmlText = doc.documentElement.InnerHtml;
htmlText = htmlText.Replace("\r\n", " ");
Regex targetStart = new Regex(this works just fine);
MatchCollection target = targetStart.Matches(htmlText);
string priceData = target[0].Value;
foreach (StorePriceData spData in Lists.Singleton.MedicineList[medIndex].Prices)
{
Regex rx = new Regex(spData.StoreName + #".+?(\$\d+\.\d+)");
MatchCollection matches = rx.Matches(priceData);
if (matches.Count > 0)
{
if (matches[0].Groups.Count > 0)
{
spData.MedicinePrice = matches[0].Groups[1].Value;
}
}
}
string cookie = Application.GetCookie(new Uri("https://www.goodrx.com"));
++medIndex;
ScraperBrowser.Navigate(Lists.Singleton.MedicineList[medIndex].GoodRxUrlString);
}
The problem I'm having is that the spData.MedicinePrice takes the value, but the value in the singleton "MedicineList" is not being updated. How can I make that value update?
The singleton code:
public class Lists
{
private static Lists _singleton;
public static Lists Singleton
{
get
{
if (_singleton == null) _singleton = new Lists(); return _singleton;
}
}
public List<MedicineInfo> MedicineList {
get
{
return new List<MedicineInfo>()
{
new MedicineInfo() { Name = "ZOLPIDEM TAB 10MG", Doses = "30 tablets" },
new MedicineInfo() { Name = "PANTOPRAZOLE TAB 40MG", Doses = "30 tablets" }
};
}
}
}
MedicineInfo class code:
public class MedicineInfo
{
public MedicineInfo()
{
Prices = new List<StorePriceData>()
{
new StorePriceData() { StoreName = "xxxx" },
new StorePriceData() { StoreName = "yyyy" },
new StorePriceData() { StoreName = "zzzz" },
};
}
public string Name { get; set; }
public string Doses { get; set; }
public List<StorePriceData> Prices { get; set; }
}
Thanks!
Carl
You are returning a new List<MedicineInfo> each time the getter of MedicineList is called.
Also, Lists is not really a singleton. A better implementation would look something like this:
public sealed class Lists
{
private static readonly Lists _singleton = new Lists();
private readonly List<MedicineInfo> _medicineList = new List<MedicineInfo>
{
new MedicineInfo() { Name = "ZOLPIDEM TAB 10MG", Doses = "30 tablets" },
new MedicineInfo() { Name = "PANTOPRAZOLE TAB 40MG", Doses = "30 tablets" }
};
private Lists() { }
public static Lists Singleton => _singleton;
public List<MedicineInfo> MedicineList => _medicineList;
}
I have a form with several text boxes. I want to use the input in the text boxes to append to a list in c# which I then want to show in a datagrid as the enteries are entered. But I have an issue. I add the data to the textboxes hit the display to datagrid button I have created and it seems ever time instead of appending items to the list the list is recreated. What am I doing wrong?
'''
{
public LotScan()
{
InitializeComponent();
}
public class LotData
{
public string Lot;
public string Description { get; set; }
public int PO { get; set; }
public string MfgPart { get; set; }
}
// code to add from control data to list
private List<LotData> LoadCollectionData()
{
List<LotData> lot = new List<LotData>();
lot.Add(new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
});
return lot;
}
//button to add list data to datagrid on form
private void Button_Click(object sender, RoutedEventArgs e)
{
gridLotData.ItemsSource = LoadCollectionData();
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
'''
Move this variable to be a private Member variable (just put it a line above the classes constructor method):
List<LotData> lot = new List<LotData>();
public LotScan()
{
InitializeComponent();
gridLotData.ItemsSource = LotDataList;
}
private LotData LoadCollectionData()
{
return new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
};
}
public class LotData
{
public string Lot;
public string Description { get; set; }
public int PO { get; set; }
public string MfgPart { get; set; }
}
public ObservableCollection<LotData> LotDataList = new ObservableCollection<LotData>();
private void Button_Click(object sender, RoutedEventArgs e)
{
LotDataList.Add(LoadCollectionData());
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
I have a class and have added objects to a list, then binded the list to a checkboxlist. When the user checks the list, the answer goes into a new list and put in a session, then redirected to a new page. On the new page I want the result in an asp:Literal. But Im not sure how to do that.
The class:
public class Frukter
{
public string Navn { get; set; }
public string Farge { get; set; }
public string BildeSrc { get; set; }
public Frukter(string navn, string farge, string bildeSrc)
{
Navn = navn;
Farge = farge;
BildeSrc = bildeSrc;
}
}
First page:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Frukter> frukt = new List<Frukter>();
frukt.Add(new Frukter("Appelsin", "Oransj", "~/Appelsin.jpg"));
frukt.Add(new Frukter("Banan", "Gul", "~/Banan.jpg" ));
frukt.Add(new Frukter("Eple", "Rød", "~/Eple.jpg" ));
if (!this.IsPostBack)
{
chklst.DataSource = frukt;
chklst.DataTextField = "Navn";
chklst.DataBind();
}
protected void Resultat_Click(object sender, EventArgs e)
{
List<object> ChkListe = new List<object>();
foreach (ListItem item in chklst.Items)
{
if(item.Selected)
// If the item is selected, add the value to the list.
ChkListe.Add(item);
}
Session["selectedChkList"] = ChkListe;
Response.Redirect("Default2.aspx", false);
}
}
Second page where I take the list out of session, but not sure how to get it into the asp:literal.
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<object> ResultatList = new List<object>();
if (Session["selectedChkList"] != null)
{
ResultatList = (List<object>)Session["selectedStrList"];
ResultatLliteral.Text = String.Format("<p>{0} {1}</p> <img src ={3} />", Frukter.Navn, Frukter.farge, Frukter.BildeSrc);
}
}
}
}
Some critique on your code and some different approaches, not sure what your assignment is but I'll provide feedback that may be beneficial for your course.
public class Fruit
{
public Fruit(string name, string color, string image)
{
Name = name;
Color = color;
Image = image;
}
public string Name { get; }
public string Color { get; }
public string Image { get; }
}
You defined a Constructor that will always set a value upon creation, so unless you intend to modify the object after the fact you can set your properties to read only.
Personally I would use a database or another way to persist my data, but for your example you should be able to do the following:
var fruits = new List<Fruit>()
{
new Fruit("Apple", "Red", "..."),
new Fruit("Grapefuit", "Yellow", "...")
};
// Grab the selected checkbox in the checkbox list item (You'll have to see if a collection is returned or not)
var selectedFruit = chkLFruit.Items.Cast<ListItem>().Where(item => item.Selected);
// Take selected item and pass full object into session.
var filter = fruits.Where(fruit => selectedFruit.Select(t => t.Text).FirstOrDefault(x => String.Compare(x, fruit.Name, true) == 0);
// Create Session
HttpContext.Session["FruitSelection"] = filter;
On your other page before you attempt to use simply do the following:
var selectedFruits = (List<Fruit>)HttpContext.Session["FruitSelection"];
Want to assign CustomEditor to PropertyGridControl. If I try using default way it does not work, however I am trying alternative which is not suitable for my case.
Class and Custom editor which is needs to be assigned to PropertyGridControl:
public class Foo
{
public Foo()
{
}
public Language LanguageOfFoo { get; set; }
}
public class Language
{
public Language()
{
}
public int ID { get; set; }
public string Name { get; set; }
}
public class RepositoryItemForLanguage : RepositoryItemLookUpEdit
{
public RepositoryItemForLanguage()
{
this.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Name", "Name")}
);
this.DisplayMember = "Name";
List<Language> tmpList = new List<Language>();
tmpList.Add(new Language { ID = 1, Name = "AZE" });
tmpList.Add(new Language { ID = 2, Name = "ENG" });
tmpList.Add(new Language { ID = 1, Name = "RUS" });
this.DataSource = tmpList;
}
}
Default way:
private void button1_Click(object sender, EventArgs e)
{
propertyGridControl1.Rows.Clear();
propertyGridControl1.DefaultEditors.Clear();
propertyGridControl1.RepositoryItems.Clear();
propertyGridControl1.SelectedObject = null;
Foo f1 = new Foo();
f1.LanguageOfFoo = new Language();
RepositoryItemForLanguage repItem = new RepositoryItemForLanguage();
propertyGridControl1.RepositoryItems.Add(repItem);
propertyGridControl1.DefaultEditors.Add(typeof(Language), repItem);
propertyGridControl1.DefaultEditors.AddRange(new DevExpress.XtraVerticalGrid.Rows.DefaultEditor[] {
new DevExpress.XtraVerticalGrid.Rows.DefaultEditor(typeof(Language), repItem)});
propertyGridControl1.RepositoryItems.AddRange(new RepositoryItem[] { repItem});
propertyGridControl1.SelectedObject = f1;
}
Alternative method:
private void button1_Click(object sender, EventArgs e)
{
propertyGridControl1.Rows.Clear();
propertyGridControl1.DefaultEditors.Clear();
propertyGridControl1.RepositoryItems.Clear();
propertyGridControl1.SelectedObject = null;
Foo f1 = new Foo();
f1.LanguageOfFoo = new Language();
RepositoryItemForLanguage repItem = new RepositoryItemForLanguage();
propertyGridControl1.RepositoryItems.Add(repItem);
propertyGridControl1.SelectedObject = f1;
propertyGridControl1.GetRowByFieldName("LanguageOfFoo").Properties.RowEdit = repItem;
}
As you see it is possible only with "GetRowByFieldName" methods and specifying exact property name.
Appreciate for your help.