Checkbox turning multiple values true - c#

I've been stuck of this for a while and would love some insight.
When I add a new user or source and check the drawn checkbox, it causes the bool to be true when checked, as expected.
However it also checks all the other users connected to that source as true or false.
[before]
[after]
This only occurs when I load the XML file into my program that already had existing data, then add new Users or Sources via the UI.
this is a part of the LoadXML Method.
// Load the source list
sourceProps.SystemSources.Clear();
fCMUserSourceBindingSource.Clear();
fCMSourceBindingSource.Clear();
foreach (FusionSource src in fusionSystem.sourceList)
{
FCMSource fSource = new FCMSource(src);
sourceProps.SystemSources.Add(fSource);
fCMSourceBindingSource.Add(fSource);
fCMUserSourceBindingSource.Add(fSource);
}
txtSourceID.Text = sourceProps.GenerateNextSourceId();
// Load the user data from the fusionSystem object.
userProfile.SystemUserList.Clear();
//currently clears grid. might need to clear list instead
fCMUserBindingSource.Clear();
foreach (FusionUser usr in fusionSystem.userList)
{
FCMUser fUser = new FCMUser(usr);
userProfile.SystemUserList.Add(fUser);
fCMUserBindingSource.Add(fUser);
foreach (FusionSourcePermission srcPerm in usr.SourcePermissionList)
{
FCMSource fSource = new FCMSource(srcPerm);
fUser.fusionUserSources.Add(fSource);
}
}
AddColumnsUsersToSourceAllocation();
txtUserID.Text = userProfile.GenerateNextUserId();
// Load the zone group data from the fusionSystem object
zoneProps.systemZoneGroupList.Clear();
fCMZoneGroupBindingSource.Clear();
Any help would be appreciated.
Edit
The ListView is not binded and all the 'checking' is done programmatically when the user activates the click event.
private void lstSourceToUser_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if (e.ColumnIndex > 1)
{
int usrIndex = userProfile.GetUserIndexByID(e.Header.Name);
int srcIndex = userProfile.GetUsersSourceIndex(e.Header.Name, e.Item.SubItems[0].Text);
Graphics g = e.Graphics;
CheckBoxRenderer.DrawCheckBox(g,new Point((e.Bounds.X + e.Bounds.Width/2 -10 ),(e.Bounds.Y)), userProfile.SystemUserList[usrIndex].fusionUserSources[srcIndex].UserSourceChkBox.MyCheckedState ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);
}
else
// Draw the other subitems with default drawing.
e.DrawDefault = true;
}
Edit
This is the FCMSource constructor.
public FCMSource(string sourceId, string sourceName, string icnId, string lstIndx)
{
id = sourceId;
icon = icnId;
name = sourceName;
listIndex = lstIndx;
UserSourceCheckState = false;
UserSourceChkBox = new MyCheckBoxItem(false);
}
public FCMSource(FCMSource fSource, bool chk)
{
name = fSource.name;
icon = fSource.icon;
id = fSource.id;
listIndex = fSource.listIndex;
UserSourceCheckState = chk ? true : false;
UserSourceChkBox = new MyCheckBoxItem(chk);
}
And this is the FCMUser constructor which contains the different Sources.
public FCMUser(string userid, string nm, string icn, string pinNo, CheckBox pinEn, string lstIndx)
{
id = userid;
name = nm;
icon = icn;
pin = pinNo;
pinEnabled = pinEn.CheckState;
chkBoxPINEnable = new MyCheckBoxItem(false);
fusionUserSources = new List<FCMSource>();
ListIndex = lstIndx;
updateCheckbox();
}

Related

Reloading live charts chart only adds new data

I'm using Live Charts in my application for a pareto chart. I have made a SeriesCollection. I'm loading it from a Stored Procedure in the following way:
public void LoadChart()
{
List<DataTops> dataTops = GetTops();
ChartValues<int> Pareto = new ChartValues<int>();
List<string> timevalues = new List<string>();
int selected = ComboSelect();
IDLables = new List<string>();
foreach (var item in dataTops)
{
values.Add(item.Total);
Pareto.Add(item.Running);
IDLables.Add((item.W) + "." + (item.B));
}
TopAlarms = new SeriesCollection
{
new ColumnSeries
{
Title = "Total",
Values =values,
DataLabels = false,
ScalesYAt = 0,
},
new LineSeries
{
Title = "%",
Values = Pareto,
ScalesYAt = 1,
PointGeometrySize = 0
}
};
public List<DataTops> GetTops()
{
int selected = ComboSelect();
DataSet Ds = new DataSet();
DataSetTableAdapters.TimePerID_TopTableAdapter TimerTopta = new DataSetTableAdapters.TimePerID_TopTableAdapter();
TimerTopta.Fill(Ds.TimePerID_Top, selected);
List<DataTops> Tops = new List<DataTops>();
foreach (DataRow row in Ds.Tables["TimePerID_Top"].Rows)
{
Tops.Add(new DataTops() { Total = (int)row["Total"], W = (int)row["W"], B = (int)row["B"], Amount = (int)row["Amount"], Running = (int)row["Running"] });
}
return Tops;
}
I have a combobox to select an amount to show (selected in the dataset) and a button that I use to update the chart. The Chart works fine, but whenever I press the update button it only adds new data behind the already existing data.
Live charts doesn't automatically clear the chart collection data upon loading so I did this:
private void UpdateChart_Click(object sender, RoutedEventArgs e)
{
if (TopAlarms != null)
{
TopAlarms.Clear();
}
LoadChart();
}
But it still won't clear and reload the chart. How can i reload the chart when the button is pressed so the new selected data amount will show?
after some testing and reasearch I have the following solution for clearing the chart:
try
{
if (TopAlarms != null)
{
TopAlarms.Clear();
}
}
catch { }
This is probably not the best solution but it works for me.

Bing API Query Callback to Observable Collection

Created a Windows Store App using some info found on this post: How do I use the Bing Search API in Windows Phone?
Goal
Textbox - Type any term
Search Button - Searches that term and populates a GridView of pictures retrieved with the Bing API
Problem
I get the pictures, and they are received via my "OnQueryComplete" callback, but I can't figure out what the correct way to populate the collection would be. Since I can't figure out how to await this call, I (just to see if I could get it working, which it does) added a while loop (which you can probably see the issues with). What would be the correct way to do this? How do you handle callbacks for populating the GridView and having it wait until it's finished?
Current ViewModel Code
public bool itemsFinished = false;
private ObservableCollection<SearchResult> _ImageResults;
public ObservableCollection<SearchResult> ImageResults {
get {
if (_ImageResults == null) {
while (!itemsFinished) {
int i = 0;
i++;
}
}
return _ImageResults;
}
set {
_ImageResults = value;
}
}
public SearchResultViewModel() {
GetPictures("dogs");
}
public void GetPictures(string searchTerm) {
// This is the query - or you could get it from args.
string query = searchTerm;
// Create a Bing container.
string rootUri = "https://api.datamarket.azure.com/Bing/Search";
var bingContainer = new Bing.BingSearchContainer(new Uri(rootUri));
// Replace this value with your account key.
var accountKey = "myaccountkey";
// Configure bingContainer to use your credentials.
bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);
// Build the query.
var imageQuery = bingContainer.Image(query, null, null, null, null, null, null);
imageQuery.BeginExecute(OnQueryComplete, imageQuery);
// var imageResults = imageQuery.Execute();
}
private void OnQueryComplete(IAsyncResult result) {
// ImageResults.Clear();
_ImageResults = new ObservableCollection<SearchResult>();
var query = (DataServiceQuery<ImageResult>)result.AsyncState;
var enumerableResults = query.EndExecute(result);
int i = 0;
foreach (var item in enumerableResults) {
SearchResult myResult = new SearchResult();
myResult.Title = item.Title;
myResult.ImageUri = new Uri(item.MediaUrl);
ImageResults.Add(myResult);
i++;
if (i >= 14) {
break;
}
}
itemsFinished = true;
}
Please excuse any syntax errors, I'm without a Visual Studio instance right now.
The problem I see is that you reset your ObservableCollection when you receive content.
Try it as follows:
private ObservableCollection<SearchResult> _ImageResults;
public ObservableCollection<SearchResult> ImageResults {
get
{
return _ImageResults;
}
set {
_ImageResults = value;
}
}
public SearchResultViewModel() {
_ImageResults = new ObservableCollection<SearchResult>(); // Just create it once.
GetPictures("dogs");
}
private void OnQueryComplete(IAsyncResult result) {
_ImageResults.Clear(); // Clear isn't bad, that way you keep your reference to your original collection!
//_ImageResults = new ObservableCollection<SearchResult>(); // We already have one. ObservableCollection works best if you keep on working with the collection you have.
var query = (DataServiceQuery<ImageResult>)result.AsyncState;
var enumerableResults = query.EndExecute(result);
int i = 0;
foreach (var item in enumerableResults) {
SearchResult myResult = new SearchResult();
myResult.Title = item.Title;
myResult.ImageUri = new Uri(item.MediaUrl);
ImageResults.Add(myResult);
i++;
if (i >= 14) {
break;
}
}
}
As far as I see (can't test sadly) this should work, provided you have bound your ObservableCollection the right way in your xaml.

Using word interop create multiple documents from a template for print preview

I have an app where the user selects from a list all the students they want to print an award document for.
I have a template .doc file that contains 3 text boxes that I populate from code. I can populate the file and show it in the print preview for a single student, but based on how many students are selected I want to create a large document with many pages I can see in print preview before printing and print all at once.
The following is my attempt to turn my working code for a single word document being created from the template to show in print preview. Any ideas?
public void AddStudentToDocument(IEnumerable<StudentToPrint> studentsToPrint )
{
_Application oWordApp = new Application();
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string specificFolder = Path.Combine(folder, "FoothillsAcademy");
string fileLocation = Path.Combine(specificFolder, "CertTemplate.doc");
if (File.Exists(fileLocation))
{
var oWordDoc = oWordApp.Documents.Open(fileLocation);
oWordDoc.Activate();
oWordApp.Selection.TypeParagraph();
foreach (var studentToPrint in studentsToPrint)
{
_Document oDoc = oWordApp.Documents.Add();
Selection oSelection = oWordApp.Selection;
string docText = oWordDoc.Content.Text;
if (docText != null)
{
int boxNumber = 1;
foreach (Shape shape in oWordApp.ActiveDocument.Shapes)
{
if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
{
if (boxNumber == 1)
{
shape.TextFrame.TextRange.Text = studentToPrint.StudentName;
}
if (boxNumber == 2)
{
shape.TextFrame.TextRange.Text = studentToPrint.Rank;
}
if (boxNumber == 3)
{
shape.TextFrame.TextRange.Text = studentToPrint.DateAcheved;
}
boxNumber++;
}
}
_Document oCurrentDocument = oWordApp.Documents.Add(oWordDoc);
copyPageSetup(oCurrentDocument.PageSetup, oDoc.Sections.Last.PageSetup);
oCurrentDocument.Range().Copy();
oSelection.PasteAndFormat(WdRecoveryType.wdFormatOriginalFormatting);
//if (!Object.ReferenceEquals(oWordDoc.Content, oWordDoc.Last()))
oSelection.InsertBreak(WdBreakType.wdSectionBreakNextPage);
}
oWordApp.Visible = true;
oWordApp.ShowStartupDialog = true;
oWordApp.ActiveDocument.PrintPreview();
}
}
}
private void copyPageSetup(PageSetup source, PageSetup target)
{
target.PaperSize = source.PaperSize;
if (!source.Orientation.Equals(target.Orientation))
target.TogglePortrait();
target.TopMargin = source.TopMargin;
target.BottomMargin = source.BottomMargin;
target.RightMargin = source.RightMargin;
target.LeftMargin = source.LeftMargin;
target.FooterDistance = source.FooterDistance;
target.HeaderDistance = source.HeaderDistance;
target.LayoutMode = source.LayoutMode;
}
public class StudentToPrint
{
public string StudentName { get; set; }
public string Rank { get; set; }
public string DateAcheved { get; set; }
}
Currently I am testing this with a collection of StudentsToPrint added below. Based on the data below I would expect to see 3 certificates personalized for each of the 3 students. Each certificate would be on its own page.
List<StudentToPrint> listOfStudents = new List<StudentToPrint>
{
new StudentToPrint
{
DateAcheved = DateTime.Now.ToShortDateString(),
Rank = "5th Degree",
StudentName = "Scott LaFoy"
},
new StudentToPrint
{
DateAcheved = DateTime.Now.ToShortDateString(),
Rank = "3rd Degree",
StudentName = "John Doe"
},
new StudentToPrint
{
DateAcheved = DateTime.Now.ToShortDateString(),
Rank = "2nd Degree",
StudentName = "Jane Doe"
}
};
The template is a word doc that has 3 text boxes. Using the text box lets me set font and position different for each of them as well as making the background transparent so the template background shows through. I am sure there is another way to do this as well but there is not much on this topic around.

when add emoticon to RichTextBox Error (**An item with the same key has already been added**)

I try to add emoticon in RichTextBox in WPF that use function below, when I type text :) from Textbox, it shows the good result but when I type the other text again it show error
(An item with the same key has already been added).this is code that i call from function Emoticons below :
private void btnSend_Click(object sender, RoutedEventArgs e)
{
Paragraph p = new Paragraph();
p.LineHeight = 1;
Run dd = new Run();
dd.Text= DateTime.Now.ToString("(HH:mm:ss)") + "Chat" + rtbMessage.Text;
rtbBody.Document.Blocks.Add(p);
Emoticons(dd.Text);
}
I type to fix it but still not solve. I hope all programmer will help me.
Thanks
///Function Emoticon////
private Dictionary<string, string> _mappings = new Dictionary<string, string>();
private string GetEmoticonText(string text)
{
string match = string.Empty;
int lowestPosition = text.Length;
foreach (KeyValuePair<string, string> pair in _mappings)
{
if (text.Contains(pair.Key))
{
int newPosition = text.IndexOf(pair.Key);
if (newPosition < lowestPosition)
{
match = pair.Key;
lowestPosition = newPosition;
}
}
}
return match;
}
// And also function which add smiles in richtextbox, here is it:
private void Emoticons(string msg)
{
//try
//{
_mappings.Add(#":)", "/Images/smiles/silly.png");
_mappings.Add(#">:o", "/Images/smiles/angry.png");
_mappings.Add(#":'(", "/Images/smiles/cry.png");
_mappings.Add(#"B-)", "/Images/smiles/cool.png");
_mappings.Add(#":^0", "/Images/smiles/laught.png");
_mappings.Add(#":-[", "/Images/smiles/blush.png");
_mappings.Add(#":-)", "/Images/smiles/happy.png");
_mappings.Add(#"?:|", "/Images/smiles/confuse.png");
_mappings.Add(#":x", "/Images/smiles/love.png");
var para = new Paragraph { LineHeight=1};
//Paragraph para = new Paragraph();
var r = new Run(msg);
para.Inlines.Add(r);
string emoticonText = GetEmoticonText(r.Text);
//if paragraph does not contains smile only add plain text to richtextbox rtb2
if (string.IsNullOrEmpty(emoticonText))
{
rtbBody.Document.Blocks.Add(para);
}
else
{
while (!string.IsNullOrEmpty(emoticonText))
{
TextPointer tp = r.ContentStart;
// keep moving the cursor until we find the emoticon text
while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith(emoticonText))
tp = tp.GetNextInsertionPosition(LogicalDirection.Forward);
// select all of the emoticon text
var tr = new TextRange(tp, tp.GetPositionAtOffset(emoticonText.Length)) { Text = string.Empty };
//relative path to image smile file
string path = _mappings[emoticonText];
var image = new Image
{
Source =
new BitmapImage(new Uri(Environment.CurrentDirectory + path,
UriKind.RelativeOrAbsolute)),
Width=Height=25,
};
//insert smile
new InlineUIContainer(image, tp);
if (para != null)
{
var endRun = para.Inlines.LastInline as Run;
if (endRun == null)
{
break;
}
else
{
emoticonText = GetEmoticonText(endRun.Text);
}
}
}
rtbBody.Document.Blocks.Add(para);
}
The reason you are getting this error is because you are adding an object in the dictionary with the same key, infact you are adding all the items in the _mappings dictionary on each call of your function Emoticons. You can't add duplicate entries in the dictionary. I have no idea why you are doing that, but you may fill up the dictionary once in your application startup or window load event and then use it later.
Move the following lines to any method/event where it would be executed only once.
_mappings.Add(#":)", "/Images/smiles/silly.png");
_mappings.Add(#">:o", "/Images/smiles/angry.png");
_mappings.Add(#":'(", "/Images/smiles/cry.png");
_mappings.Add(#"B-)", "/Images/smiles/cool.png");
_mappings.Add(#":^0", "/Images/smiles/laught.png");
_mappings.Add(#":-[", "/Images/smiles/blush.png");
_mappings.Add(#":-)", "/Images/smiles/happy.png");
_mappings.Add(#"?:|", "/Images/smiles/confuse.png");
_mappings.Add(#":x", "/Images/smiles/love.png");

C# Creating a datasource that gets all branches for a specific bank

I am trying to create a binding source to my binding navigator that will be able to show all branches within a specific bank.
The statement that gets the datasource is as follows
branchMasterBindingSource.DataSource = Program.Kernel.Get<IBranchMasterService>().GetAllBranchMasters();
However, this pulls all branches regardless of the banks they belong to.
I need to know how to change this so that it gets AllBranchMasters where a field in the database ("U_bank_code") is equals to a combobox named "cb_bank_code"
Extra code is below:
private void cb_bank_code_SelectedIndexChanged(object sender, EventArgs e)
{
branchMasterBindingSource.DataSource = null;
branchMasterBindingSource.DataSource = Program.Kernel.Get<IBranchMasterService>().GetAllBranchMasters();
//clear textfields after input
lbl_show_bank_name.Text = string.Empty;
txt_branch_code.Text = string.Empty;
txt_branch_name.Text = string.Empty;
txt_swift_sort_code.Text = string.Empty;
txt_address_1.Text = string.Empty;
txt_address_2.Text = string.Empty;
txt_comments.Text = string.Empty;
var bankMasterService = Program.Kernel.Get<IBankMasterService>();
var bankMasters = from bm in bankMasterService.GetAllBankMasters()
where bm.U_Bank_code.Trim().Equals(cb_bank_code.Text.Trim(), StringComparison.CurrentCultureIgnoreCase)
select bm;
if (bankMasters.Any(x => x != null))
{
var bankMaster = bankMasters.First();
lbl_show_bank_name.Text = bankMaster.U_Bank_name;
CbBankCode = bankMaster.U_Bank_code;
}
else
{
//clear textfields after input
lbl_show_bank_name.Text = string.Empty;
}
Im new to C# and dot net and do not know how the syntax to change the statement. Any help appreciated
If I understand you correctly, and make a couple assumptions on the types, the following should work:
branchMasterBindingSource.DataSource = Program.Kernel.Get<IBranchMasterService>().GetAllBranchMasters.Where(x => x.U_Bank_code.Trim().Equals(cb_bank_code.Text.Trim(), StringComparison.CurrentCultureIgnoreCase))
I'm guessing the
Program.Kernel.Get<IBranchMasterService>().GetAllBranchMasters
returns an IEnumerable or perhaps List. There won't be much you can do about that function returning all banks/branches unless you either:
Change GetAllBranchMasters to return an IQueryable - you can then apply the filter as above and add .ToList() to the end to perform the query.
(Recommended) Create a second method that accepts a Bank Code, and returns the branches in accordance with the underlying DAL.
Although you should look at refactoring your data access methods to do the filtering something like this should do the trick for you
private void cb_bank_code_SelectedIndexChanged(object sender, EventArgs e)
{
ClearTextfieldsAfterInput();
branchMasterBindingSource.DataSource = GetSelectedBranchMasters();
var bankMasters = GetSelectedBankMaster();
if (bankMasters.Any(x => x != null))
{
var bankMaster = bankMasters.First();
lbl_show_bank_name.Text = bankMaster.U_Bank_name;
CbBankCode = bankMaster.U_Bank_code;
}
else
{
//clear textfields after input
lbl_show_bank_name.Text = string.Empty;
}
}
private IEnumerable<BankMaster> GetSelectedBankMaster()
{
var selectedBank = cb_bank_code.Text.Trim();
return Program.Kernel.Get<IBankMasterService>()
.GetAllBankMasters()
.Where(bm => bm.U_Bank_code.Trim().Equals(selectedBank, StringComparison.CurrentCultureIgnoreCase))
.ToList();
}
private IEnumerable<BranchMaster> GetSelectedBranchMasters()
{
var selectedBank = cb_bank_code.Text.Trim();
return Program.Kernel.Get<IBranchMasterService>()
.GetAllBranchMasters()
.Where(branch => string.Equals(branch.U_bank_code, selectedBank, StringComparison.CurrentCultureIgnoreCase))
.ToList();
}
private void ClearTextfieldsAfterInput()
{
lbl_show_bank_name.Text = "";
txt_branch_code.Text = "";
txt_branch_name.Text = "";
txt_swift_sort_code.Text = "";
txt_address_1.Text = "";
txt_address_2.Text = "";
txt_comments.Text = "";
}

Categories