ObservableCollection sorting c# - c#

I'm new to C#. I need to sort my ObservableCollection with four kinds of sorts, but I can't understand how to do that, and my Google searches didn't help.
I thought that I could create a new observable collection like this:
var orderedByNameObservableCollection = performerList.OrderBy(p =\> p.Name);
...but I can't understand how to easily update the table with the new ObservableCollection.
My code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.SizeToContent = SizeToContent.WidthAndHeight;
}
private static string[] Load(string filename)
{
List<string> strings = null;
using (StreamReader sr = new StreamReader(filename))
{
strings = new List<string>();
while (!sr.EndOfStream)
{
strings.Add(sr.ReadLine());
}
}
return strings.ToArray();
}
internal string[] fileRKK;
internal string[] fileAppeals;
private void openFileRKKButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialogRKK = new OpenFileDialog();
if (openFileDialogRKK.ShowDialog() == true)
{
TextBlockRKK.Text = "Выбранный файл: " + Path.GetFileName(openFileDialogRKK.FileName);
fileRKK = Load(openFileDialogRKK.FileName);
}
}
private void openFileAppealsButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialogAppeals = new OpenFileDialog();
if (openFileDialogAppeals.ShowDialog() == true)
{
TextBlockAppeals.Text = "Выбранный файл: " + Path.GetFileName(openFileDialogAppeals.FileName);
fileAppeals = Load(openFileDialogAppeals.FileName);
}
}
Dictionary<string, int> staffRKK = new Dictionary<string, int>();
Dictionary<string, int> staffAppeals = new Dictionary<string, int>();
private Dictionary<string, int> staffGeneral = new Dictionary<string, int>();
ObservableCollection<Performer> performerList = new ObservableCollection<Performer>();
private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
private void WriteInTable()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//СЛОВАРЬ РКК
if (fileRKK != null)
{
var queryOfRKK = from line in fileRKK
let searchingPerson = line.Split('\t', ';')
select new
{
ResponsiblePerson = (searchingPerson[0] == "Климов Сергей Александрович"
? searchingPerson[1].Replace("(Отв.)", "").Trim()
: searchingPerson[0].Trim()),
};
foreach (var item in queryOfRKK)
{
var value = item.ResponsiblePerson.Trim().Split(' ');
string fio;
if (value.Length == 3)
{
fio = value[0] + " " + value[1].Substring(0, 1) + "." + value[2].Substring(0, 1) + ".".Trim();
}
else
{
fio = item.ResponsiblePerson;
}
if (staffRKK.ContainsKey(fio))
{
staffRKK[fio]++;
}
else
staffRKK.Add(fio, 1);
}
}
//СЛОВАРЬ ОБРАЩЕНИЙ
if (fileAppeals != null)
{
var queryOfAppeals = from line in fileAppeals
let searchingPerson = line.Split('\t', ';')
select new
{
ResponsiblePerson = (searchingPerson[0] == "Климов Сергей Александрович"
? searchingPerson[1].Replace("(Отв.)", "").Trim()
: searchingPerson[0]),
};
foreach (var item in queryOfAppeals)
{
var value = item.ResponsiblePerson.Trim().Split(' ');
string fio;
if (value.Length == 3)
{
fio = value[0] + " " + value[1].Substring(0, 1) + "." + value[2].Substring(0, 1) + ".";
}
else
{
fio = item.ResponsiblePerson;
}
if (staffAppeals.ContainsKey(fio))
{
staffAppeals[fio]++;
}
else
staffAppeals.Add(fio, 1);
}
}
//ОБЩИЙ СЛОВАРЬ
staffGeneral = (from p in staffRKK.Concat(staffAppeals)
group p by p.Key into g
select new { fio = g.Key, Count = g.Sum(kvp => kvp.Value) }).ToDictionary(item => item.fio,
item => item.Count);
foreach (var item in staffRKK)
{
performerList.Add(new Performer
{
Name = item.Key,
CountRKK = item.Value,
CountAppeals =
staffAppeals.ContainsKey(item.Key) ? staffAppeals[item.Key] : 0,
CountGeneral = item.Value + (staffAppeals.ContainsKey(item.Key) ? staffAppeals[item.Key] : 0)
}
);
staffAppeals.Remove(item.Key);
}
foreach (var item2 in staffAppeals)
{
performerList.Add(new Performer { Name = item2.Key, CountAppeals = item2.Value });
}
DataGrid.ItemsSource = performerList.Select(p => new
{
p.Name,
p.CountRKK,
p.CountAppeals,
p.CountGeneral
});
DataGrid.Columns[0].Header = "Ответственный" + Environment.NewLine + "исполнитель";
DataGrid.Columns[1].Header = "Количество" + Environment.NewLine + "неисполненных" + Environment.NewLine +
"входящих документов";
DataGrid.Columns[2].Header = "Количество" + Environment.NewLine + "неисполненных" + Environment.NewLine +
"письменных " + Environment.NewLine + "обращений граждан";
DataGrid.Columns[3].Header = "Общее количество " + Environment.NewLine + "документов и " +
Environment.NewLine + "обращений";
stopWatch.Stop();
TextBlockTime.Text = $"{stopWatch.ElapsedMilliseconds} мс"; ;
}
private void ButtonLoad_Click(object sender, RoutedEventArgs e)
{
if (fileRKK != null && fileAppeals != null)
{
TextBlockTodayDate.Text = $"Дата составления справки: {DateTime.Now.ToShortDateString()}";
Total.Text = $"Не исполнено в срок {performerList.Sum(p => p.CountGeneral)} документов, из них:";
TotalRKK.Text = $"- количество неисполненных входящих документов: {performerList.Sum(p => p.CountRKK)};";
TotalAppeals.Text = $"- количество неисполненных письменных обращений граждан: {performerList.Sum(p => p.CountAppeals)}.";
WriteInTable();
}
else MessageBox.Show("Вы выбрали не все файлы!");
}
/* private void ButtonNameSort_Click(object sender, RoutedEventArgs e)
{
//TODO
WriteInTable();
}
private void ButtonRKKSort_Click(object sender, RoutedEventArgs e)
{
//TODO
WriteInTable();
}
private void ButtonAppealsSort_Click(object sender, RoutedEventArgs e)
{
//TODO
WriteInTable();
}
private void ButtonGeneralSort_Click(object sender, RoutedEventArgs e)
{
//TODO
WriteInTable();
}*/
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
if (DataGrid == null)
{
MessageBox.Show("Нечего выводить!");
return;
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Text files (*.txt)|*.txt";
if (saveFileDialog.ShowDialog() == true)
{
using (StreamWriter writer = new StreamWriter(saveFileDialog.FileName, false))
{
writer.WriteLine("Справка о неисполненных документах и обращениях граждан\n");
writer.WriteLine(Total.Text);
writer.WriteLine(TotalRKK.Text);
writer.WriteLine(TotalAppeals.Text);
writer.WriteLine();
writer.WriteLine("{0,4} |{1,20} |{2,11} |{3,16}|{4,13} ",
"№", "Исполнитель", "Кол-во ркк", "Кол-во обращений", "Общее кол-во");
int i = 1;
foreach (var item in performerList)
{
writer.WriteLine("------------------------------------------------------------------------");
writer.WriteLine("{0,4} |{1,20} |{2,11} |{3,15} |{4,13} ",
i++, item.Name, item.CountRKK, item.CountAppeals, item.CountGeneral);
}
}
}
}
}
public class Performer
{
public string Name;
public int CountRKK;
public int CountAppeals;
public int CountGeneral;
}
Maybe you can help me? Maybe you'll tell me the correct ordering or how to write in datagrid the new observable collection?

When you use the OrderBy() function from LINQ, the output is an IEnumerable, which is not an observable collection. So, you need to create an observable collection from the OrderBy() result
var orderedByName = performerList.OrderBy(p => p.Name);
DataGrid.ItemsSource = new ObservableCollection<Performer>(orderedByName);

Related

The code is giving error at MultiSheetsPdf

This is my code which create PDF of a dwg file but it gives me error near MultiSheetPdf. Please give me the solution for same.
I thought that linking is the problem but I am not able to identify please suggest me the solution.
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdfPlot(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Here you go: (Try to note and understand the difference between your version and this version)
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdf(){}
public MultiSheetsPdf(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Heads up. The method, PostProcessDSD, tests are too generic. Client contacted me complaining that one of his files was not plotting. It was named "SOUTH". The test for "OUT" in the string caused the issue. No errors were thrown. Just a good ol' fashion mystery.
Change all tests to include the "=". ie else if (str.Contains("OUT=")) { ...

WPF, C# TPL AggregateException never fired

I am trying to develop a small application with WPF, C#. I encountered a problem when trying to use the library TPL, especially exception handling. The problem is that AggregateException is never captured, and the program displays an exception in the method I passed as a task. here's my code. I removed unnecessary code :
private void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (e == null || processIt == true)
{
TaskInProgress = true;
SBMessage = "Query In progress...";
var uischeduler = TaskScheduler.FromCurrentSynchronizationContext();
var refreshold = Task.Factory.StartNew(() =>
RefreshOldDossierFinancement(DossierFinancementEnteredKey));
refreshold.ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler);
try
{
refreshold.Wait();
}
catch (AggregateException aex) //This Exception is never fired
{
Messenger.Default.Send(new ExceptionMessageRefresh(aex), "DossierFinancement");
}
}
}
private void RefreshOldDossierFinancement(long dfId)
{
TotalContrats = 0.000M;
TotalMefs = 0.000M;
TotalCommandes = 0.000M;
decimal phb = 0.000M;
decimal pctr = 0.000M;
decimal pmef = 0.000M;
PercentageHorsBilan = "(0%)";
PercentageContrats = "(0%)";
PercentageMef = "(0%)";
DossierNumber = "";
using (UnitOfWork cx = new UnitOfWork(_currentLog))
{
// try
{
IDossierFinancementRepository sr = new DossierFinancementRepository(cx, _currentLog);
IDossierFinancementManagementService dfms = new DossierFinancementManagementService(_currentLog, sr);
IDataTraceRepository dtr = new DataTraceRepository(cx, _currentLog);
IDataTraceManagementService dtms = new DataTraceManagementService(_currentLog, dtr);
CurrentDossierFinancement = dfms.FindById(dfId);
//I put this code in comment to force a nullReferenceException exception
/*if (CurrentDossierFinancement == null) //Not Found
Messenger.Default.Send<NotificationMessage>(new NotificationMessage("Dossier Financement n° " + dfId.ToString() + " introuvable."),"DossierFinancementError");
else*/
{
//The debugger stops here with NullRefrenceException Exception
// I want this exception to be captured in AggregateException
DossierFinancementEnteredKey = CurrentDossierFinancement.DossierId;
DossierNumber = "N° " + DossierFinancementEnteredKey.ToString();
RequestNature = (CurrentDossierFinancement.InvestmentGoal == 0) ? "Création" : (CurrentDossierFinancement.InvestmentGoal == 1) ? "Renouvellement" : "Extension";
EtatDossier = (CurrentDossierFinancement.Status == 1) ? "En cours" : (CurrentDossierFinancement.Status == 2) ? "Approuvé" : "Rejeté";
if (CurrentDossierFinancement.ClientId != null)
{
CustomerCode = (long)CurrentDossierFinancement.ClientId;
CustomerName = CurrentDossierFinancement.Client.NomCli;
}
else
{
CustomerCode = 0;
if (CurrentDossierFinancement.ClientType == 1)
CustomerName = CurrentDossierFinancement.Name + " " + CurrentDossierFinancement.FirstName;
else
CustomerName = CurrentDossierFinancement.CompanyName;
}
if (CurrentDossierFinancement.Contrat != null)
{
TotalContrats = CurrentDossierFinancement.Contrat.Montant;
TotalHorsBilan = CurrentDossierFinancement.Contrat.Montant;
pctr = Math.Round((TotalContrats / CurrentDossierFinancement.Montant) * 100, 0);
PercentageContrats = "(" + pctr.ToString() + "%)";
if (CurrentDossierFinancement.Contrat.Mefs != null)
{
TotalMefs = CurrentDossierFinancement.Contrat.Mefs.Sum(x => x.Montant);
pmef = Math.Round((TotalMefs / CurrentDossierFinancement.Montant) * 100, 0);
PercentageMef = "(" + pmef.ToString() + "%)";
}
TotalHorsBilan = TotalContrats - TotalMefs;
phb = Math.Round((TotalHorsBilan / CurrentDossierFinancement.Montant) * 100, 0);
PercentageHorsBilan = "(" + phb.ToString() + "%)";
}
//Extraire la trace
List<DataTrace> traceList = dtms.GetTrace(DossierFinancementEnteredKey, "DossierFinancement").ToList();
DataTrace newRecord = traceList.Where(xx => string.Equals(xx.ActionLib, "New", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (newRecord != null)
{
CreatedBy = newRecord.Coduser;
CreatedAt = newRecord.ActionDate.ToString();
}
}
}
/*
catch (Exception ex)
{
throw ex;
}*/
}
}
I tested the following code and it still doesn't work :
Task.Run(() =>
{
RefreshOldDossierFinancement(DossierFinancementEnteredKey);
}
catch (AggregateException aex)
{
Messenger.Default.Send(new ExceptionMessageRefresh(aex), "DossierFinancement");
}}).ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler
);
A simpler approach to using continuations is to use async-await. When we execute a delegate using Task.Run, and want to asynchronously wait for it's completion, we can await it:
private async void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (!processIt)
return;
TaskInProgress = true;
SBMessage = "Query In progress...";
try
{
await Task.Run(() => RefreshOldDossierFinancement(DossierFinancementEnteredKey));
}
catch (Exception e)
{
// Do stuff
}
finally
{
TaskInProgress = false;
}
}
This way, you don't need to explicitly capture the SynchronizationContext, and you don't block the UI thread while the operation is on-going.
Finally i found a solution, I dont know if it is the best.
I modified my code as follows :
private void RefreshOldDossierFinancementCommandExecute(KeyEventArgs e)
{
bool processIt = false;
if (e != null && e.Key == Key.Enter)
processIt = true;
if (e == null || processIt == true)
{
TaskInProgress = true;
SBMessage = "Query in progress...";
var uischeduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Run(() =>
{
RefreshOldDossierFinancement(DossierFinancementEnteredKey);
}).ContinueWith(task => { TaskInProgress = false; },
CancellationToken.None,
TaskContinuationOptions.NotOnFaulted, uischeduler);
}
}
and i capture the exception in RefreshOldDossierFinancement Method. The trick lies to add a Dispatch.BeginInvoke in code behind of the window.
Here The code of RefreshOldDossierFinancement Method :
private void RefreshOldDossierFinancement(long dfId)
{
TotalContrats = 0.000M;
TotalMefs = 0.000M;
TotalCommandes = 0.000M;
decimal phb = 0.000M;
decimal pctr = 0.000M;
decimal pmef = 0.000M;
PercentageHorsBilan = "(0%)";
PercentageContrats = "(0%)";
PercentageMef = "(0%)";
DossierNumber = "";
using (UnitOfWork cx = new UnitOfWork(_currentLog))
{
try
{
IDossierFinancementRepository sr = new DossierFinancementRepository(cx, _currentLog);
IDossierFinancementManagementService dfms = new DossierFinancementManagementService(_currentLog, sr);
IDataTraceRepository dtr = new DataTraceRepository(cx, _currentLog);
IDataTraceManagementService dtms = new DataTraceManagementService(_currentLog, dtr);
CurrentDossierFinancement = dfms.FindById(dfId);
/*if (CurrentDossierFinancement == null) //Not Found
Messenger.Default.Send<NotificationMessage>(new NotificationMessage("Dossier Financement n° " + dfId.ToString() + " introuvable."),"DossierFinancementError");
else*/
{
DossierFinancementEnteredKey = CurrentDossierFinancement.DossierId;
DossierNumber = "N° " + DossierFinancementEnteredKey.ToString();
RequestNature = (CurrentDossierFinancement.InvestmentGoal == 0) ? "Création" : (CurrentDossierFinancement.InvestmentGoal == 1) ? "Renouvellement" : "Extension";
EtatDossier = (CurrentDossierFinancement.Status == 1) ? "En cours" : (CurrentDossierFinancement.Status == 2) ? "Approuvé" : "Rejeté";
if (CurrentDossierFinancement.ClientId != null)
{
CustomerCode = (long)CurrentDossierFinancement.ClientId;
CustomerName = CurrentDossierFinancement.Client.NomCli;
}
else
{
CustomerCode = 0;
if (CurrentDossierFinancement.ClientType == 1)
CustomerName = CurrentDossierFinancement.Name + " " + CurrentDossierFinancement.FirstName;
else
CustomerName = CurrentDossierFinancement.CompanyName;
}
if (CurrentDossierFinancement.Contrat != null)
{
TotalContrats = CurrentDossierFinancement.Contrat.Montant;
TotalHorsBilan = CurrentDossierFinancement.Contrat.Montant;
pctr = Math.Round((TotalContrats / CurrentDossierFinancement.Montant) * 100, 0);
PercentageContrats = "(" + pctr.ToString() + "%)";
if (CurrentDossierFinancement.Contrat.Mefs != null)
{
TotalMefs = CurrentDossierFinancement.Contrat.Mefs.Sum(x => x.Montant);
pmef = Math.Round((TotalMefs / CurrentDossierFinancement.Montant) * 100, 0);
PercentageMef = "(" + pmef.ToString() + "%)";
}
TotalHorsBilan = TotalContrats - TotalMefs;
phb = Math.Round((TotalHorsBilan / CurrentDossierFinancement.Montant) * 100, 0);
PercentageHorsBilan = "(" + phb.ToString() + "%)";
}
//Extraire la trace
List<DataTrace> traceList = dtms.GetTrace(DossierFinancementEnteredKey, "DossierFinancement").ToList();
DataTrace newRecord = traceList.Where(xx => string.Equals(xx.ActionLib, "New", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (newRecord != null)
{
CreatedBy = newRecord.Coduser;
CreatedAt = newRecord.ActionDate.ToString();
}
}
}
catch (Exception ex)
{
//Here i send a message to Window to display The Exception Message in a custom Dialog
Messenger.Default.Send(new ExceptionMessageRefresh(ex), "DossierFinancement");
}
}
}
And finally here The code Behind of The window :
public partial class Dossier : Window
{
public Dossier()
{
InitializeComponent();
Messenger.Default.Register<ExitMessage>(this, "DossierFinancement", (action) => CloseWindow(action));
Messenger.Default.Register<ExceptionMessageRefresh>(this, "DossierFinancement", (action) => ShowExceptionMessage(action));
Messenger.Default.Register<NotificationMessage>(this, "DossierFinancementInfo", (action) => ProcessNotification(action));
Messenger.Default.Register<NotificationMessage>(this, "DossierFinancementError", (action) => ProcessErrorDialogNotification(action));
}
private void ProcessNotification(NotificationMessage action)
{
MessageBox.Show(action.Notification.ToString(), "Information", MessageBoxButton.OK,MessageBoxImage.Information);
}
private void ProcessErrorDialogNotification(NotificationMessage action)
{
MessageBox.Show(action.Notification.ToString(), "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
}
private void CloseWindow(ExitMessage action)
{
this.Close();
Messenger.Default.Unregister<ExitMessage>(this, "DossierFinancement");
}
private void ShowExceptionMessage(ExceptionMessageRefresh obj)
{
//Without the following Call of Dispatcher, An exception "Thread must be STA... will be fired
Dispatcher.BeginInvoke(new Action(() =>
{
UICommon.ShowErrorMessage(obj.ExceptionToRefresh);
}));
}
}
and that's all.
Thanks.

Not all code paths return error in c#

I want to pass real time signals from emotive to octave.
I tried to write a c# wrapper for octave. Here is the code.
namespace LibSharpTave {
public class Octave {
Process OctaveProcess { get; set; }
private string OctaveEchoString { get; set; }
public Octave(string PathToOctaveBinaries) {
StartOctave(PathToOctaveBinaries, false);
}
public Octave(string PathToOctaveBinaries, bool CreateWindow) {
StartOctave(PathToOctaveBinaries, CreateWindow);
}
string ptob;
bool cw;
private void StartOctave(string PathToOctaveBinaries, bool CreateWindow) {
ptob = PathToOctaveBinaries;
cw = CreateWindow;
this.OctaveEchoString = Guid.NewGuid().ToString();
OctaveProcess = new Process();
ProcessStartInfo pi = new ProcessStartInfo();
if (PathToOctaveBinaries[PathToOctaveBinaries.Length - 1] != '\\')
PathToOctaveBinaries = PathToOctaveBinaries + "\\";
pi.FileName = PathToOctaveBinaries + "octave.exe";
pi.RedirectStandardInput = true;
pi.RedirectStandardOutput = true;
pi.RedirectStandardError = true;
pi.UseShellExecute = false;
pi.CreateNoWindow = !CreateWindow;
pi.Verb = "open";
//
pi.WorkingDirectory = ".";
OctaveProcess.StartInfo = pi;
OctaveProcess.Start();
OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(OctaveProcess_OutputDataReceived);
OctaveProcess.BeginOutputReadLine();
OctaveEntryText = ExecuteCommand(null);
//OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(Oc
}
public double GetScalar(string scalar) {
string rasp = ExecuteCommand(scalar, 30000);
string val = rasp.Substring(rasp.LastIndexOf("\\") + 1).Trim();
return double.Parse(val);
}
public double[] GetVector(string vector) {
string rasp = ExecuteCommand(vector, 30000);
string[] lines = rasp.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
int i = 0;
//catam urmatorul entry
List<double> data = new List<double>();
while (i != lines.Length) {
string line = lines[i];
if (line.Contains("through") || line.Contains("and")) {
i++;
line = lines[i];
string[] dataS = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
for (int k = 0; k < dataS.Length; k++) {
data.Add(double.Parse(dataS[k]));
}
}
i++;
}
//caz special in care a pus toate rezultatele pe o singura linie
if (data.Count == 0) {
string[] dataS = lines[lines.Length - 1].Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (dataS.Length != 0)
for (int k = 0; k < dataS.Length; k++) {
data.Add(double.Parse(dataS[k]));
}
}
return data.ToArray();
}
public double[][] GetMatrix(string matrix) {
//string rasp = ExecuteCommand(matrix);
//aflam numarul de randuri
string rasp = ExecuteCommand(matrix + "(:,1)", 30000);
string[] lines = rasp.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
double[][] mat = new double[lines.Length - 1][];
for (int i = 0; i < mat.Length; i++) {
mat[i] = GetVector(matrix + "(" + (i + 1) + ",:)");
}
return mat;
}
StringBuilder SharedBuilder = new StringBuilder();
ManualResetEvent OctaveDoneEvent = new ManualResetEvent(false);
public string OctaveEntryText { get; internal set; }
public void WorkThread(object o) {
string command = (string)o;
SharedBuilder.Clear();
OctaveDoneEvent.Reset();
if (command != null) {
OctaveProcess.StandardInput.WriteLine(command);
}
//ca sa avem referinta pentru output
OctaveProcess.StandardInput.WriteLine("\"" + OctaveEchoString + "\"");
OctaveDoneEvent.WaitOne();
}
public string ExecuteCommand(string command, int timeout) {
if (OctaveProcess.HasExited) {
StartOctave(ptob, cw);
if (OctaveRestarted != null) OctaveRestarted(this, EventArgs.Empty);
}
exitError = false;
Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
tmp.Start(command);
if (!tmp.Join(timeout)) {
tmp.Abort();
throw new Exception("Octave timeout");
}
if (exitError) {
throw new Exception(errorMessage);
}
return SharedBuilder.ToString();
}
public string ExecuteCommand(string command) {
// Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
// tmp.Start(command);
// tmp.Join();
// return SharedBuilder.ToString();
if (OctaveProcess.HasExited)
{
OctaveProcess.Start();
}
SharedBuilder.Clear();
if (command != null)
{
OctaveProcess.StandardInput.WriteLine(command);
OctaveDoneEvent.Reset();
OctaveDoneEvent.WaitOne();
return SharedBuilder.ToString();
}
Octave octave = new Octave(#"c:\software\Octave-3.6.4",false);
octave.ExecuteCommand("a=[1,2;3,4];");
octave.ExecuteCommand("result=a;");
double[][] m = octave.GetMatrix("result");
}
bool exitError = false;
string errorMessage = null;
void OctaveProcess_OutputDataReceived(object sender, DataReceivedEventArgs e) {
if (e.Data == null) {
SharedBuilder.Clear();
//errorMessage = OctaveProcess.StandardError.ReadToEnd();
SharedBuilder.Append("Octave has exited with the following error message: \r\n" + errorMessage);
//exitError = true;
OctaveDoneEvent.Set();
return;
}
if (e.Data.Trim() == "ans = " + OctaveEchoString)
OctaveDoneEvent.Set();
else
SharedBuilder.Append(e.Data + "\r\n");
}
public event OctaveRestartedEventHandler OctaveRestarted;
public delegate void OctaveRestartedEventHandler(object sender, EventArgs e);
}
//custom class
// void OctaveProcess_OutputDataReceived (object sender, DataReceivedeEventArgs e)
/*{
if (e.data == null)
{
SharedBuilder.Clear();
SharedBuilder.Append("Octave has exited with the following error message: \r\n" + OctaveProcess.StandardError.ReadToEnd());
OctaveDoneEvent.Set();
return;
}
if (e.data.Trim == "ans =" + OctaveEchoString())
OctaveDoneEvent.set();
else
SharedBuilder.Append(e.Data + "\r\n");
}*/
}
And it is returning the error: "Not all code paths return a value".
How can I fix this error?
Your ExecuteCommand function should return a string, but doesn't. This is the ExecuteCommand overload that accepts one argument.
This function has string as return type but does not return anything when if (command != null) statement is false -
public string ExecuteCommand(string command) {
// Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
// tmp.Start(command);
// tmp.Join();
// return SharedBuilder.ToString();
if (OctaveProcess.HasExited)
{
OctaveProcess.Start();
}
SharedBuilder.Clear();
if (command != null)
{
OctaveProcess.StandardInput.WriteLine(command);
OctaveDoneEvent.Reset();
OctaveDoneEvent.WaitOne();
return SharedBuilder.ToString();
}
Octave octave = new Octave(#"c:\software\Octave-3.6.4",false);
octave.ExecuteCommand("a=[1,2;3,4];");
octave.ExecuteCommand("result=a;");
double[][] m = octave.GetMatrix("result");
//**** The Error is here *****
//return a string here
}
Return a string at the mention section. I highlighted in the comment as - //**** The Error is here *****
Your
public string ExecuteCommand(string command) {
has no return statement even though you specified return type string.
Either return some string or make its return type void as in :
public void ExecuteCommand(string command) {

How to deal with multiple EventHandlers to AsyncQuery

I am working on Windows Phone 8 project. In my project there are 10 Events with 10 EventHandlers ReverseGeocodeQuery_QueryCompleted (1 to 10). When first EventHandler is completed it turn on second event.
What should I implement to manage those Events without so much code.
code
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(0);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_1;
myReverseGeocodeQuery.QueryAsync();
private void ReverseGeocodeQuery_QueryCompleted_1(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Pierwszy");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
}
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(1);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_2;
myReverseGeocodeQuery.QueryAsync();
}
}
private void ReverseGeocodeQuery_QueryCompleted_2(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Drugi");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(2);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_3;
myReverseGeocodeQuery.QueryAsync();
}
}
}
Example Solution 1
public class DataContainer
{
public string Description { get; set; }
public GeoCoordinate Coordinate { get; set; }
//public List<GeoCoordinate> mySimulationCoordinates { get; set; }
public String EnterSimulation() {
StringBuilder strRet = new StringBuilder();
List<GeoCoordinate> mySimulationCoordinates = new List<GeoCoordinate>();
mySimulationCoordinates.Add(new GeoCoordinate(51.760752, 19.458216));
mySimulationCoordinates.Add(new GeoCoordinate(51.760757, 19.458356));
mySimulationCoordinates.Add(new GeoCoordinate(51.760738, 19.458442));
mySimulationCoordinates.Add(new GeoCoordinate(51.7607, 19.458501));
mySimulationCoordinates.Add(new GeoCoordinate(51.760662, 19.458533));
var descriptions = new[] { "Pierwszy", "Drugi", "Trzeci", "Czwarty", "Piąty" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
int k = zipped.Count();
foreach (var item in zipped)
{
var currentItem = item;
using (var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = item.Coordinate;
geocodeQuery.QueryCompleted += (sender, args) =>
{
if (args.Error == null)
{
if (args.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
//label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("House Number" + address.HouseNumber);
str.AppendLine("Street " + address.Street);
strRet.AppendLine("->");
strRet.Append(str);
waitHandle.Set();
}
}
};
geocodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
return strRet.ToString();
}
It stuck on 1st item. Is inside and wait ... wait ... can't pass to next element.
Umm... Let's see, shouldn't that be easier?
Warning: untested
public class DataContainer
{
public string Description {get;set;}
public GeoCoordinate Coordinate {get;set;}
}
var descriptions = new[] {"Pierwszy" , "Drugi" , "Trzeci" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
foreach(var item in zipped)
{
var currentItem = item;
using(var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = currentItem.Coordinates;
geocodeQuery.QueryCompleted += (sender, args) => {
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
waitHandle.Set();
}
}
};
geoCodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
That should guarantee you that one event is handled after another in order.

fb.Get() doesn't exist?

I have the code below that I got from off of Prabir's Blog (codeplex documentation) and the fb.get() method does not exist...I was able to test all the way up to authentication where it takes me to the fb login page and now I am trying to do the fb.Get("/me"); I am new to this and am just following the guide...
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
string appId = "xxx";
string[] extendedPermissions = new[] { "publish_stream", "offline_access" };
var oauth = new FacebookOAuthClient { AppId = appId};
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "popup" }
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
webBrowser.Navigating += webBrowser_Navigated;
webBrowser.Navigate(loginUrl);
}
private void webBrowser_Navigated(object sender, NavigatingEventArgs e)
{
FacebookOAuthResult result=null;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
var fb = new FacebookClient(accesstoken);
var results = (IDictionary<string, object>)fb.Get("/me");
var name = (string)results["name"];
MessageBox.Show("Hi " + name);
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
}
use fb.GetAsync instead. Window Phone 7 doesn't support synchronous methods.
i highly recommend you to download the source code and checkout the "Samples\CS-WP7.sln" example.
var fb = new FacebookClient(_accessToken);
fb.GetCompleted += (o, args) =>
{
if (args.Error == null)
{
var me = (IDictionary<string, object>)args.GetResultData();
Dispatcher.BeginInvoke(
() =>
{
FirstName.Text = "First Name: " + me["first_name"];
LastName.Text = "Last Name: " + me["last_name"];
});
}
else
{
Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message));
}
};
fb.GetAsync("me");

Categories

Resources