First of all - please excuse my poor pronunciation.
I'm programming a wpf-validator for a excelsheet and while this programm is getting Infos from google it should show the progress on a progressbar. I've read a lot of articles in the web about multithreading and backgroundworking but I think nothing can really help me.
Here is my GUI
<Window x:Class="DatenValidierung.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="570" Width="825" ResizeMode="NoResize">
<Grid Background="Black">
<Button Foreground="White" Background="Black" Name="exit" Content="Exit" HorizontalAlignment="Left" Margin="714,484,0,0" VerticalAlignment="Top" Width="94" Click="exit_Click" Height="27"/>
<Button Foreground="White" Background="Black" Name="open" Content="Excel öffnen" HorizontalAlignment="Left" Margin="10,460,0,0" VerticalAlignment="Top" Width="88" Click="open_Click" />
<DataGrid Name="dg1" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="445" Width="798" AutoGenerateColumns="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding SubCategory}" Header="Kat" Width="90" />
<DataGridTextColumn Binding="{Binding Title}" Header="Title" Width="80" />
<DataGridTextColumn Binding="{Binding InfoText}" Header="Info" Width="80" />
<DataGridTextColumn Binding="{Binding Domain}" Header="Domain" Width="60" />
<DataGridTextColumn Binding="{Binding City}" Header="City" Width="50" />
<DataGridTextColumn Binding="{Binding Zipcode}" Header="Zip" Width="50" />
<DataGridTextColumn Binding="{Binding Longitude}" Header="Long" Width="50" />
<DataGridTextColumn Binding="{Binding Latitude}" Header="Lat" Width="50" />
<DataGridTextColumn Binding="{Binding Telefon}" Header="Tel" Width="50" />
<DataGridTextColumn Binding="{Binding Mail}" Header="Mail" Width="50" />
<DataGridTextColumn Binding="{Binding Address}" Header="Adresse" Width="50" />
</DataGrid.Columns>
</DataGrid>
<Button Content="Hochladen" Background="Black" Foreground="White" Name="upload" Click="upload_Click" HorizontalAlignment="Left" Margin="10,508,0,0" VerticalAlignment="Top" Width="88"/>
<Button Content="google-Daten" Name="check" Background="Black" Foreground="White" HorizontalAlignment="Left" Margin="10,484,0,0" VerticalAlignment="Top" Width="88" Click="check_Click"/>
<ProgressBar Value="{Binding Path=ProgressValue}" HorizontalAlignment="Left" Height="24" Margin="270,460,0,0" VerticalAlignment="Top" Width="200" Name="pb1"/>
<Label Name="progressLabel" Foreground="White" TextBlock.TextAlignment="Center" Content="" HorizontalAlignment="Left" Margin="320,489,0,0" VerticalAlignment="Top" Width="100"/>
</Grid>
</Window>
And here is my CodeBehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
using System.Data;
using System.Globalization;
using System.ComponentModel;
using System.Threading;
using System.Net;
using System.Xml.Linq;
using DatenValidierung.ServiceReference1;
namespace DatenValidierung
{
public partial class MainWindow : Window
{
int progressCounter = 0;
List<Location> locationList = new List<Location>();
public MainWindow()
{
InitializeComponent();
}
double progressValue;
public double ProgressValue
{
get { return progressValue; }
set
{
if (progressValue != value)
{
progressValue = value;
OnPropertyChanged("ProgressValue");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property_name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property_name));
}
public static DataTable ReadExcelData(string filePath)
{
System.Data.DataTable dtExcel = new System.Data.DataTable();
dtExcel.TableName = "MyExcelData";
bool hasHeaders = false;
string strConn = string.Empty;
string HDR = hasHeaders ? "Yes" : "No";
if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
}
//string SourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='MyExcelFilePath';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(strConn);
con.Open();
DataTable schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
string query = "SELECT * FROM [" + sheet + "]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);
return dtExcel;
}
private void open_Click(object sender, RoutedEventArgs e)
{
var dataFromExcel = new DataTable();
string ausgabeTemp = String.Empty;
OpenFileDialog BrowserFileDialog = new OpenFileDialog();
BrowserFileDialog.Title = "";
BrowserFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
BrowserFileDialog.FilterIndex = 1;
BrowserFileDialog.RestoreDirectory = true;
if (BrowserFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
dataFromExcel = ReadExcelData(BrowserFileDialog.FileName);
}
var liste = dataFromExcel.AsEnumerable().ToList();
int k = 0;
for (int i = 0; i < liste.Count; i++)
{
Location loc = new Location();
loc.SubCategory = liste[k].ItemArray[0].ToString();
loc.City = liste[k].ItemArray[1].ToString();
loc.Zipcode = liste[k].ItemArray[2].ToString();
loc.Address = liste[k].ItemArray[3].ToString();
loc.Telefon = liste[k].ItemArray[4].ToString();
loc.Mail = liste[k].ItemArray[5].ToString();
loc.Domain = liste[k].ItemArray[6].ToString();
loc.SubCategory = liste[k].ItemArray[7].ToString();
loc.InfoText = liste[k].ItemArray[8].ToString();
locationList.Add(loc);
k++;
}
pb1.Maximum = k;
pb1.Minimum = 0;
var fred = new Thread(updateProgressBar);
fred.IsBackground = true;
fred.Start();
FormatList(locationList);
}
public void updateProgressBar()
{
ProgressValue = ((double)progressCounter * 100) / locationList.Count ;
progressLabel.Content = ProgressValue + " / 100";
}
public List<Location> FormatList(List<Location> locationList)
{
var locList = locationList;
locList = FormatLocationForDB(locList);
for (int i = 0; i < locList.Count; i++)
{
if (locList[i].Latitude == 0 || locList[0].Longitude == 0)
{
locList[i] = GetSingleFormatForDB(locList[i]);
}
}
return locList;
}
public List<Location> FormatLocationForDB(object o)
{
progressCounter = 0;
var locList = new List<Location>();
foreach (Location currentLocation in locationList)
{
Thread.Sleep(50);
// System.Threading.Thread.Sleep(200);
string address = currentLocation.Address + ", " + currentLocation.City;
var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));
var request = WebRequest.Create(requestUri);
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
try
{
var result = xdoc.Element("GeocodeResponse").Element("result");
var locationElement = result.Element("geometry").Element("location");
currentLocation.Latitude = (float)(locationElement.Element("lat"));
currentLocation.Longitude = (float)(locationElement.Element("lng"));
}
catch (Exception x)
{
}
dg1.Items.Add(currentLocation);
dg1.InvalidateVisual();
progressCounter++;
locList.Add(currentLocation);
}
return locList;
}
public Location GetSingleFormatForDB(Location location)
{
string address = location.Address + ", " + location.City;
var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));
var request = WebRequest.Create(requestUri);
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
try
{
var result = xdoc.Element("GeocodeResponse").Element("result");
var locationElement = result.Element("geometry").Element("location");
location.Latitude = (float)(locationElement.Element("lat"));
location.Longitude = (float)(locationElement.Element("lng"));
}
catch (Exception x)
{
}
return location;
}
public static void InsertLocationListToDB(Location location)
{
Service1Client wcf = new Service1Client();
try
{
wcf.ClientCredentials.UserName.UserName = "admin2";
wcf.ClientCredentials.UserName.Password = "123test123!";
wcf.AddLocationFromListAsync(
location.SubCategory,
location.Title,
location.InfoText,
location.Domain,
location.City,
location.Zipcode,
(float)location.Longitude,
(float)location.Latitude,
location.Telefon,
location.Mail,
location.Address
);
}
catch (Exception x)
{
}
}
private void upload_Click(object sender, RoutedEventArgs e)
{
if (locationList.Count > 0 || locationList != null)
{
dg1.Items.Clear();
foreach (Location l in locationList)
{
if (l.Latitude != 0 && l.Longitude != 0)
{
locationList.Remove(l);
}
dg1.Items.Add(l);
}
}
}
private void check_Click(object sender, RoutedEventArgs e)
{
locationList = FormatLocationForDB(locationList);
}
private void exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
I tried to manage the progressbarvalue in the thread but nothing happens at all. The value is still 0 when the programm is finished. Could someone help me? Is there an easy mistake? Or should i try somethink else like the backgroundworker (which looks pretty the same i think).
Thanks for help
private double _progressLabelContent;
public double ProgressLabelContent
{
get {return _progressLabelContent; }
set { _progressLabelContent=value; OnPropertyChanged("ProgressLabelContent"); }
}
public void updateProgressBar()
{
Application.Current.Dispatcher.Invoke(delegate
{
ProgressValue = ((double)progressCounter * 100) / locationList.Count;
ProgressLabelContent = ProgressValue + " / 100";
});
}
xaml
<Label Content={Binding Path=ProgressLabelContent} Foreground="White" TextBlock.TextAlignment="Center" Content="" HorizontalAlignment="Left" Margin="320,489,0,0" VerticalAlignment="Top" Width="100"/>
Related
I have a DataGrid connected to a SQL database. I can show in a single row the data associated to an id, I want to select that row by clicking on it and, through a btnSave, save the content of that row into a .txt file. Is this possible?
Below is the XAML for my DataGrid:
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" Margin="0,54,0,31" x:Name="STable" IsReadOnly="True" VerticalScrollBarVisibility="Visible" ScrollViewer.CanContentScroll="False" ColumnWidth="Auto">
<DataGrid.Columns>
<DataGridTextColumn x:Name="StatTableNItemColumn" Header="N" Binding="{Binding NItem, BindsDirectlyToSource=True}" />
<DataGridTextColumn x:Name="StatTablePSEColumn" Header="P" Binding="{Binding P, BindsDirectlyToSource=True}" />
<DataGridTextColumn x:Name="StatTableDStartColumn" Header="Start" HeaderStringFormat="dd-MM-yyyy" Binding="{Binding DStart, BindsDirectlyToSource=True, StringFormat=\{0:dd-MM-yyyy\}}"/>
<DataGridTextColumn x:Name="StatTableDEndSEColumn" Header="End" HeaderStringFormat="dd-MM-yyyy" Binding="{Binding DEnd, StringFormat=\{0:dd-MM-yyyy\}}" />
<DataGridTextColumn x:Name="StatTableRItemColumn" Header="R" Binding="{Binding RItem}" />
<DataGridTextColumn x:Name="StatTableRepColumn" Header="Rep" Binding="{Binding Rep}" />
</DataGrid.Columns>
This is the code for my btnSave.OnClick event handler:
private void BtnSaveStat_Click(object sender, RoutedEventArgs e)
{
if (StatTable.SelectedItem == null)
return;
var itemSelected = StatTable.SelectedItem;
if (!Directory.Exists(#"D:/ReportStatistics"))
{
Directory.CreateDirectory(#"D:/ReportStatistics");
}
try
{
sqliteCon.Open();
var filename = string.Concat("Filename", DateTime.Now.ToString("ddMMyyHHmmss"), ".txt");//THIS STRING ALLOW TO BUILD FILES EVERY TIME THE USER CHANGE ITEM AND WANTO TO PRINT IT
//DONE: SAVE PER ID
string query =
#"SELECT tabS.NItem
FROM tabS
WHERE tabS.NItem LIKE #prmNome";
using (SqlCommand command = new SqlCommand(query, sqliteCon))
{
command.Parameters.AddWithValue("#prmNome", this.txtSrcVR.Text);
using (var reader = command.ExecuteReader())
{
string file = Path.Combine(#"D:\Reports", filename);
using (TextWriter tw1 = new StreamWriter(file, true))
{
while (reader.Read())
{
string datoN = Convert.ToString(reader[0]);
tw1.WriteLine(datoN);
}
}
}
}
MessageBox.Show("File Created Successfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
sqliteCon.Close();
}
DataGrid gd=(Datagrid)sender; ERROR:'Impossible to execute the cast of
objects of type 'System.Windows.Controls.Button' on
typoe'System.Windows.Controls.DataGrid'
As per the comment you are trying to convert button to class to DataGrid so
private void BtnSaveStat_Click(object sender, RoutedEventArgs e)
{
if(STable.SelectedItem==null)
return;
var itemSelected= STable.SelectedItem
if (!Directory.Exists(#"D:/ReportStatistics"))
{
Directory.CreateDirectory(#"D:/ReportStatistics");
}
private void BtnSaveStat_Click(object sender, RoutedEventArgs e)
{
if (StatTable.SelectedItem == null)
return;
var filename = string.Concat("Filename", DateTime.Now.ToString("ddMMyyHHmmss"), ".txt");//THIS STRING ALLOW TO BUILD FILES EVERY TIME THE USER CHANGE ITEM AND WANTO TO PRINT IT
DataRowView var3 = (DataRowView)StatTable.SelectedItem;
string nome = var3.Row["NItem"].ToString();
string path = var3.Row["P"].ToString();
string datS = var3.Row["DStart"].ToString();
string datE = var3.Row["DEnd"].ToString();
string ResI = var3.Row["RItem"].ToString();
string Rep = var3.Row["Rep"].ToString();
if (!Directory.Exists(#"D:/ReportStatistics"))
{
Directory.CreateDirectory(#"D:/ReportStatistics");
}
string file = Path.Combine(#"D:/ReportStatistics", filename);
using (TextWriter tw1 = new StreamWriter(file, true))
{
tw1.WriteLine(nome+" "+path+" "+ datS+" "+datE+" "+ ResI+" "+ Rep);
}
MessageBox.Show("Line Saved");
}
I'm trying to save the data I have imported from excel into my datagrid to my database.
Data base details:
File - tensiondata.db
Table - data
I can't find enough information on how to perform this, I've attached the code below. I'm not even certain that saving it to a database is the right solution. Is there a way you can save the datagrid somewhere else?
<Window x:Class="WpfApp1.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="Open Excel File for Tension, Velocity or Takeup" Height="550" Width="900">
<Grid>
<Image Source="Capture.jpg" VerticalAlignment="Top" Height="68" Margin="5,10,0,0" HorizontalAlignment="Left" Width="75"/>
<GroupBox x:Name="Options" Header="Options" HorizontalAlignment="Left" Height="62" Margin="85,8,0,0" VerticalAlignment="Top" Width="562">
</GroupBox>
<Button x:Name="save_file" Content="Save and Update" HorizontalAlignment="Left" Margin="451,22,0,0" VerticalAlignment="Top" Width="176" Height="40" Click="Button_Click_1" FontSize="16" FontWeight="Bold"/>
<Button Content="Generate Graph" FontWeight="Bold" HorizontalAlignment="Left" Margin="350,463,0,0" VerticalAlignment="Top" Width="164" Height="29" Click="Button_Click"/>
<TextBox x:Name="txtFilePath" HorizontalAlignment="Left" Height="24" Margin="189,32,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="233"/>
<Button Content="Search" FontWeight="Bold" HorizontalAlignment="Left" Margin="100,32,0,0" VerticalAlignment="Top" Width="78" Height="24" x:Name="search_file" Click="Open_Click"/>
<DataGrid AutoGenerateColumns="True" IsReadOnly="False" HorizontalAlignment="Center" Name="dtGrid" VerticalAlignment="Center" Height="356" Margin="37,83,44,80" Width="811" RenderTransformOrigin="0.529,0.503" />
</Grid>
</Window>
Code:
public partial class Window3 : Window
{
string dbConnectionString = #"Data Source = tensiondata.db;Version=3;"; // String connection
private object con;
public Window3()
{
InitializeComponent();
}
private void Open_Click(object sender, RoutedEventArgs e) // Opening Excel file into data grid
{
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".xlsx";
openfile.Filter = "(.xlsx)|*.xlsx";
//openfile.ShowDialog();
var browsefile = openfile.ShowDialog();
if (browsefile == true)
{
txtFilePath.Text = openfile.FileName;
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open(txtFilePath.Text.ToString(), 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelBook.Worksheets.get_Item(1); ;
Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange;
string strCellData = "";
double douCellData;
int rowCnt = 0;
int colCnt = 0;
DataTable dt = new DataTable();
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
string strColumn = "";
strColumn = (string)(excelRange.Cells[1, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
dt.Columns.Add(strColumn, typeof(string));
}
for (rowCnt = 1; rowCnt <= excelRange.Rows.Count; rowCnt++)
{
string strData = "";
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
try
{
strCellData = (string)(excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
strData += strCellData + "|";
}
catch (Exception ex)
{
douCellData = (excelRange.Cells[rowCnt, colCnt] as Microsoft.Office.Interop.Excel.Range).Value2;
strData += douCellData.ToString() + "|";
}
}
strData = strData.Remove(strData.Length - 1, 1);
dt.Rows.Add(strData.Split('|'));
}
dtGrid.ItemsSource = dt.DefaultView;
excelBook.Close(true, null, null);
excelApp.Quit();
}
}
private void Button_Click(object sender, RoutedEventArgs e) // Next Window Button
{
Window2 sec = new Window2();
sec.ShowDialog();
}
private void Button_Click_1(object sender, RoutedEventArgs e) // Save and update button
{
//Open connection to database
SQLiteConnection SQLiteCon = new SQLiteConnection(dbConnectionString);
SQLiteCon.Open();
try
{
}
//SQLiteCon.Close();
//}
// while (dr.Read())
// {
// }
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Like other DB, SQLite need to design it's Table structure before you insert record into it.
I suggest you to read document of SQLite.It will be usefull.
And DataTable is available as a data source.
I have a listview whose data is extracted from sqlite database, as shown below:
I want to check the user click the delete button, then the data on the list is deleted and the data in the sqlite database also deleted.
XAML:
<ListView x:Name="ListTryout" Grid.Row="1" Margin="0,5,0,10" ItemsSource="{Binding Source={StaticResource itemsViewSource}}" DataContext="{Binding SelectedItem, ElementName=itemListView}" IsItemClickEnabled="True" SelectionChanged="ListTryout_SelectionChanged" Background="{x:Null}" SelectionMode="Single">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Vertical">
<TextBlock Margin="10,10,0,0" FontSize="20" Text="{Binding Judul}" Style="{StaticResource CaptionTextBlockStyle}" VerticalAlignment="Top" HorizontalAlignment="Left"/>
<TextBlock Margin="10,10,0,0" FontSize="17" Text="{Binding JumlahSoal}" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="SemiLight"/>
<TextBlock Margin="10,10,0,0" FontSize="17" Text="{Binding Durasi}" VerticalAlignment="Top" HorizontalAlignment="Left" FontWeight="SemiLight" Visibility="Collapsed"/>
<Line X1="0" X2="1" Stretch="Fill" Margin="10,10,10,0" Stroke="#FF4B4B4B"/>
</StackPanel>
<AppBarButton x:Name="deleteItemBtn" Grid.Column="1" Margin="0,0,50,0" Icon="Delete" HorizontalAlignment="Right" Click="deleteItemBtn_Click"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code:
private void ReadTryoutList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllDBName dbName = new ReadAllDBName();
DB_TryoutList = dbName.GetAllDBName();
ListTryout.ItemsSource = DB_TryoutList.OrderByDescending(i => i.ID).ToList();//Binding DB data to LISTBOX and Latest contact ID can Display first.
if(DB_TryoutList.Count == 0)
{
statuskosongStack.Visibility = Visibility.Visible;
ListTryout.Visibility = Visibility.Collapsed;
}
else
{
statuskosongStack.Visibility = Visibility.Collapsed;
ListTryout.Visibility = Visibility.Visible;
}
}
private void deleteItemBtn_Click(object sender, RoutedEventArgs e)
{
Db_Helper.DeleteQuiz(currentquiz.ID);
}
DatabaseHelper class:
public void CreateDatabase(string DB_PATH)
{
if (!CheckFileExists(DB_PATH).Result)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH))
{
conn.CreateTable<DBName>();
}
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
// Insert the new history in the DBName table.
public void Insert(DBName dBName)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
conn.RunInTransaction(() =>
{
conn.Insert(dBName);
});
}
}
public DBName ReadName(int quizid)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
var existingName = conn.Query<DBName>("select * from DBName where ID =" + quizid).FirstOrDefault();
return existingName;
}
}
public ObservableCollection<DBName> ReadAllDBName()
{
try
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
List<DBName> myCollection = conn.Table<DBName>().ToList<DBName>();
ObservableCollection<DBName> DBNameList = new ObservableCollection<DBName>(myCollection);
return DBNameList;
}
}
catch
{
return null;
}
}
public void DeleteQuiz(string ID)
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.DB_PATH))
{
var existingquiz = conn.Query<DBName>("delete from DBName where ID ='" + ID + "'").FirstOrDefault();
if (existingquiz != null)
{
conn.RunInTransaction(() =>
{
conn.Delete(existingquiz);
});
}
}
}
I tried it, but the data can not be deleted on listview and also on the sqlite database.
How to handle it?
Set or bind the ItemsSource of the ListView to an ObservableCollection<T> and remove the item from this one, e.g.:
private ObservableCollecton<DBName> _source;
private void ReadTryoutList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllDBName dbName = new ReadAllDBName();
DB_TryoutList = dbName.GetAllDBName();
_source = new ObservableCollecton<DBName>(DB_TryoutList.OrderByDescending(i => i.ID).ToList());
ListTryout.ItemsSource = _source;
if (DB_TryoutList.Count == 0)
{
statuskosongStack.Visibility = Visibility.Visible;
ListTryout.Visibility = Visibility.Collapsed;
}
else
{
statuskosongStack.Visibility = Visibility.Collapsed;
ListTryout.Visibility = Visibility.Visible;
}
}
private void deleteItemBtn_Click(object sender, RoutedEventArgs e)
{
var btn = sender as AppBarButton;
var item = btn.DataContext as DBName;
if (item != null)
{
_source.Remove(item);
Db_Helper.DeleteQuiz(currentquiz.ID);
}
}
I assume that GetAllDBName() are returning an IEnumerable<DBName> and that you are displaying DBNames in the ListView.
I'm using the solution from this project: http://dlaa.me/blog/post/9913083#comment-2930777923
I wanted to make my WPF program able to process the virtual file dropped into it, but I'm stuck with reading the relevant data from the MemoryStream, what I receive from DragEventArgs e.Data.GetData().
I've read many posts. the closest were:
https://blogs.msdn.microsoft.com/delay/2009/11/04/creating-something-from-nothing-asynchronously-developer-friendly-virtual-file-implementation-for-net-improved/#10040454
https://www.codeproject.com/Articles/23139/Transferring-Virtual-Files-to-Windows-Explorer-in
and the above mentioned, of course
and many others to drag&drop local files, that obviously don't help
But all of them handle the from-my-app-to-filesystem case only.
Without any fancy mvvm stuff...
where I don't get any further is the
private void Label_Drop(object sender, DragEventArgs e){...}
method in my code behind:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Input;
using Delay;
using System.Runtime.Serialization.Formatters.Binary;
namespace VirtualFileDataObjectDemo
{
public partial class Window1 : Window
{
private static TextWriterTraceListener traceListener;
private string logPath;
private string filePath;
// From Windows SDK header files
private const string CFSTR_INETURLA = "UniformResourceLocator";
public Window1()
{
//logPath = Path.Combine(#"d:\Temp", #"Log\TextWriterOutput.log");
logPath = Path.Combine(Directory.GetCurrentDirectory(), #"Log\TextWriterOutput.log");
filePath = Path.Combine(Directory.GetCurrentDirectory(), #"Log");
traceListener = new TextWriterTraceListener(logPath, "traceListener");
InitializeComponent();
// Attach to interesting events
Text.MouseLeftButtonDown += new MouseButtonEventHandler(Text_MouseButtonDown);
Text.MouseRightButtonDown += new MouseButtonEventHandler(Text_MouseButtonDown);
TextUrl.MouseLeftButtonDown += new MouseButtonEventHandler(TextUrl_MouseButtonDown);
TextUrl.MouseRightButtonDown += new MouseButtonEventHandler(TextUrl_MouseButtonDown);
VirtualFile.MouseLeftButtonDown += new MouseButtonEventHandler(VirtualFile_MouseButtonDown);
VirtualFile.MouseRightButtonDown += new MouseButtonEventHandler(VirtualFile_MouseButtonDown);
MoreVirtualFiles.MouseLeftButtonDown += new MouseButtonEventHandler(TextUrlVirtualFile_MouseButtonDown);
MoreVirtualFiles.MouseRightButtonDown += new MouseButtonEventHandler(TextUrlVirtualFile_MouseButtonDown);
}
private void Text_MouseButtonDown(object sender, MouseButtonEventArgs e) //TEXT
{
var virtualFileDataObject = new VirtualFileDataObject();
// Provide simple text (in the form of a NULL-terminated ANSI string)
virtualFileDataObject.SetData(
(short)(DataFormats.GetDataFormat(DataFormats.Text).Id),
Encoding.Default.GetBytes("This is some sample text\0"));
DoDragDropOrClipboardSetDataObject(e.ChangedButton, Text, virtualFileDataObject, DragDropEffects.Copy);
}
private void TextUrl_MouseButtonDown(object sender, MouseButtonEventArgs e) //WEBADDRESS
{
var virtualFileDataObject = new VirtualFileDataObject();
// Provide simple text and an URL in priority order
// (both in the form of a NULL-terminated ANSI string)
virtualFileDataObject.SetData(
(short)(DataFormats.GetDataFormat(CFSTR_INETURLA).Id),
Encoding.Default.GetBytes("http://blogs.msdn.com/delay/\0"));
virtualFileDataObject.SetData(
(short)(DataFormats.GetDataFormat(DataFormats.Text).Id),
Encoding.Default.GetBytes("http://blogs.msdn.com/delay/\0"));
DoDragDropOrClipboardSetDataObject(e.ChangedButton, TextUrl, virtualFileDataObject, DragDropEffects.Copy);
}
private void VirtualFile_MouseButtonDown(object sender, MouseButtonEventArgs e) //VIRTUALFILE
{
var virtualFileDataObject = new VirtualFileDataObject(
null,
(vfdo) =>
{
if (DragDropEffects.Move == vfdo.PerformedDropEffect)
{
// Hide the element that was moved (or cut)
// BeginInvoke ensures UI operations happen on the right thread
Dispatcher.BeginInvoke((Action)(() => VirtualFile.Visibility = Visibility.Hidden));
}
});
// Provide a virtual file (generated on demand) containing the letters 'a'-'z'
virtualFileDataObject.SetData(new VirtualFileDataObject.FileDescriptor[]
{
new VirtualFileDataObject.FileDescriptor
{
Name = "Alphabet.txt",
Length = 26,
ChangeTimeUtc = DateTime.Now.AddDays(-1),
StreamContents = stream =>
{
var contents = Enumerable.Range('a', 26).Select(i => (byte)i).ToArray();
stream.Write(contents, 0, contents.Length);
}
},
});
DoDragDropOrClipboardSetDataObject(e.ChangedButton, TextUrl, virtualFileDataObject, DragDropEffects.Move | DragDropEffects.Copy);
}
private void TextUrlVirtualFile_MouseButtonDown(object sender, MouseButtonEventArgs e) //ALL THREE TOGETHER
{
var virtualFileDataObject = new VirtualFileDataObject(
// BeginInvoke ensures UI operations happen on the right thread
(vfdo) => Dispatcher.BeginInvoke((Action)(() => BusyScreen.Visibility = Visibility.Visible)),
(vfdo) => Dispatcher.BeginInvoke((Action)(() => BusyScreen.Visibility = Visibility.Collapsed)));
virtualFileDataObject.SetData(new VirtualFileDataObject.FileDescriptor[]
{
new VirtualFileDataObject.FileDescriptor
{
Name = "Example.xml",
StreamContents = stream =>
{
using(var webClient = new WebClient())
{
var data = webClient.DownloadData("https://www.w3schools.com/xml/note.xml");
stream.Write(data, 0, data.Length);
}
}
},
new VirtualFileDataObject.FileDescriptor
{
Name = "Example2.xml",
StreamContents = stream =>
{
using(var webClient = new WebClient())
{
var data = webClient.DownloadData("https://www.w3schools.com/xml/cd_catalog.xml");
stream.Write(data, 0, data.Length);
}
}
},
new VirtualFileDataObject.FileDescriptor
{
Name = "Example3.xml",
StreamContents = stream =>
{
using(var webClient = new WebClient())
{
var data = webClient.DownloadData("https://www.w3schools.com/xml/plant_catalog.xml");
stream.Write(data, 0, data.Length);
}
}
},
});
DoDragDropOrClipboardSetDataObject(e.ChangedButton, MoreVirtualFiles, virtualFileDataObject, DragDropEffects.Move | DragDropEffects.Copy);
}
private static void DoDragDropOrClipboardSetDataObject(MouseButton button, DependencyObject dragSource, VirtualFileDataObject virtualFileDataObject, DragDropEffects allowedEffects)
{
try
{
if (button == MouseButton.Left)
{
// Left button is used to start a drag/drop operation
VirtualFileDataObject.DoDragDrop(dragSource, virtualFileDataObject, allowedEffects);
}
else if (button == MouseButton.Right)
{
// Right button is used to copy to the clipboard
// Communicate the preferred behavior to the destination
virtualFileDataObject.PreferredDropEffect = allowedEffects;
Clipboard.SetDataObject(virtualFileDataObject);
}
}
catch (COMException ce)
{
traceListener.WriteLine("COM Exception");
traceListener.WriteLine(ce);
traceListener.WriteLine(ce.Message);
traceListener.WriteLine(ce.InnerException);
// Failure; no way to recover
}
}
private void Label_Drop(object sender, DragEventArgs e)
{
try
{
dropLabel.Content = "";
string[] retrievedFormats = e.Data.GetFormats();
foreach (string retFormat in retrievedFormats)
{
object retrievedData = e.Data.GetData(retFormat);
dropLabel.Content = dropLabel.Content + Environment.NewLine + retrievedData.ToString() + " - " + retFormat;
}
}
catch (Exception ex)
{
traceListener.WriteLine("-------------");
traceListener.WriteLine(ex + Environment.NewLine);
traceListener.WriteLine(ex.Message + Environment.NewLine);
traceListener.WriteLine(ex.StackTrace + Environment.NewLine);
traceListener.WriteLine("-------------");
traceListener.Flush();
}
}
private void Label_DragEnter(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.Copy;
}
}
}
and the XAML:
<Window x:Class="VirtualFileDataObjectDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="VirtualFileDataObjectDemo"
Height="800"
Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<UniformGrid
Rows="5"
Background="#ffdddddd"
TextElement.FontSize="22"
TextElement.FontWeight="Bold">
<UniformGrid.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="Background" Value="Orange"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Margin" Value="10"/>
</Style>
</UniformGrid.Resources>
<ContentControl
Content="Drag an item or right-click to copy it:"
FontSize="18"
VerticalAlignment="Center"
Margin="20"/>
<Label
x:Name="Text"
Content="Text only"/>
<Label
x:Name="TextUrl"
Content="Text and URL"/>
<Label
x:Name="VirtualFile">
<DockPanel>
<ContentControl
Content="Virtual file"
DockPanel.Dock="Left"
VerticalAlignment="Center"/>
<ContentControl
Content="[Drag moves; paste cuts]"
FontSize="14"
HorizontalAlignment="Right"
VerticalAlignment="Center"/>
</DockPanel>
</Label>
<Label
x:Name="MoreVirtualFiles"
Content="More virtual files"/>
</UniformGrid>
<Grid
x:Name="BusyScreen"
Background="LightGray"
Visibility="Collapsed">
<StackPanel
VerticalAlignment="Center"
Margin="50">
<Viewbox>
<TextBlock Text="Busy..."/>
</Viewbox>
<ProgressBar IsIndeterminate="True" Height="20"/>
</StackPanel>
</Grid>
<Label Name="dropLabel" Grid.Row="1" Content="Drop Area" MinHeight="50" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontSize="20" AllowDrop="True" Drop="Label_Drop" DragEnter="Label_DragEnter"/>
</Grid>
</Window>
The VirtualFileDataObject can be downloaded from here:
http://dlaa.me/Samples/VirtualFileDataObjectDemo/VirtualFileDataObjectDemo.zip
Thanks to James Barrass.
His solution in this topic here:
Dropped zip file causes e.Data.GetData("FileContents") to throw an exception
solved my problem.
I am working on a project that retrieves addresses from Google's API. I am getting response from google, but I am having trouble displaying the address results(AddressList) to the radgridview. I am using a WPF application and just need to display the results to the RADGRIDVIEW. I am using 'ItemSource' to try to bind to the grid but I am getting the following error: Invalid Cross Thread Access.
CODE
public partial class AddressSearch : ContentAppEntityView
{
public AddressSearch()
{
InitializeComponent();
}
HttpWebRequest request = null;
#region **********SEARCHING**********
private void addressInput_GotFocus(object sender, RoutedEventArgs e)
{
if (addressInput.Text == "Search")
addressInput.Text = "";
else
addressInput.SelectAll();
}
private void addressInput_LostFocus(object sender, RoutedEventArgs e)
{
if (addressInput.Text == String.Empty)
{
addressInput.Text = "Search";
searchclose.Opacity = 0;
}
else if (addressInput.Text == "Search")
searchclose.Opacity = 0;
}
private void EmptySearch_Click(object sender, RoutedEventArgs e)
{
addressInput.Text = "Search";
searchclose.Opacity = 0;
}
private void addressInput_KeyDown(object sender, KeyEventArgs e)
{
searchclose.Opacity = 1;
}
private void Enter_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
var address = addressInput.Text;
var requestUri = string.Format("http://localhost/media/TextToSpeech/TextToSpeechService.svc/getDataProxy?url=https://maps.googleapis.com/maps/api/geocode/json?address={0}&key=AIzaSyCgsNpuUoH7m6U7lqeZjlLZ3MgM15PW15o", Uri.EscapeDataString(address));
//var requestUri = string.Format(ConfigurationManager.GetAppSetting("addressSearchGeoCode", Uri.EscapeDataString(address)));
HttpWebRequest request = WebRequest.Create(requestUri) as HttpWebRequest;
request.Method = "GET";
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(RequestCompleted), request);
var dodo = result;
}
}
private void RequestCompleted(IAsyncResult result)
{
var request = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(result);
Stream stream = response.GetResponseStream();
try
{
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
Regex rgx = new Regex("<.*\\>");
string newResult = rgx.Replace(text, "");
JObject json = JObject.Parse(newResult);
JArray results = (JArray)json["results"];
List<double> latList = new List<double>();
List<double> lngList = new List<double>();
List<string> AddressList = new List<string>();
if (results.Count == 0)
{
MessageBox.Show("No results found");
}
else
{
foreach (JObject obj in results)
{
if (obj == null)
{
MessageBox.Show("Address returned no results");
}
string formattedAddress = (string)obj["formatted_address"];
AddressList.Add(formattedAddress);
double lat = (double)obj["geometry"]["location"]["lat"];
latList.Add(lat);
double lng = (double)obj["geometry"]["location"]["lng"];
lngList.Add(lng);
//TODO Add exception handling
}
this.addressGrid.ItemsSource = AddressList;
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message);
}
}
}
Section of XAML
<!--Address Results-->
<telerik:RadGridView Grid.Row="2" AutoGenerateColumns="True" x:Name="addressGrid" Margin="0 0 0 18"
ItemsSource="{Binding}" CanUserFreezeColumns="False" CanUserSelect="False"
EnableColumnVirtualization="True" EnableRowVirtualization="True" ShowGroupPanel="False" ScrollViewer.VerticalScrollBarVisibility="Visible"
CanUserDeleteRows="True" RowIndicatorVisibility="Collapsed" DataLoadMode="Asynchronous" HeaderRowStyle="{StaticResource ZoneActivityHeaderRowStyle}"
GroupPanelStyle="{StaticResource GroupPanelStyle}" Background="#00000000" VerticalGridLinesBrush="#00000000" HorizontalGridLinesBrush="#00000000" AlternationCount="2"
RowHeight="32" ShowColumnHeaders="False" RowStyle="{StaticResource ActivityRowStyle}" AlternateRowStyle="{StaticResource ActivityAlternateRowStyle}">
<telerik:RadGridView.Columns>
<telerik:GridViewDataColumn Header="Targetting" Width="28" IsReadOnly="True" IsFilterable="False" ShowDistinctFilters="True" IsGroupable="False">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<ctrl:TargetButton x:Name="targetButton" VerticalAlignment="Center" HorizontalAlignment="Center" />
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
<telerik:GridViewDataColumn Header="Address" Width="*" IsReadOnly="True"
IsFilterable="False" ShowDistinctFilters="True" IsGroupable="False">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding}" Foreground="White" FontFamily="Segoe UI"
FontSize="12" VerticalAlignment="Top" Margin="5" TextWrapping="Wrap" />
<Border Background="#00000000" Height="32" Margin="-5 0" />
</Grid>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
</telerik:RadGridView.Columns>
</telerik:RadGridView>
<TextBlock Text="No addresses available" FontFamily="Segoe UI Semibold" FontSize="12" Foreground="#FFFFFF" Grid.Row="2" Margin="18" Visibility="{Binding AddressCollection.Count}" />
</Grid>
The RadGridView can only be accessed on the thread on which it was originally created. You could use the dispatcher to marshal any calls to the RadGridView back to the UI thread. Try this:
private void RequestCompleted(IAsyncResult result)
{
var request = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(result);
Stream stream = response.GetResponseStream();
try
{
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
Regex rgx = new Regex("<.*\\>");
string newResult = rgx.Replace(text, "");
JObject json = JObject.Parse(newResult);
JArray results = (JArray)json["results"];
List<double> latList = new List<double>();
List<double> lngList = new List<double>();
List<string> AddressList = new List<string>();
if (results.Count == 0)
{
Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("No results found")));
}
else
{
foreach (JObject obj in results)
{
if (obj == null)
{
Dispatcher.Invoke(new Action(() => MessageBox.Show("Address returned no results")));
}
string formattedAddress = (string)obj["formatted_address"];
AddressList.Add(formattedAddress);
double lat = (double)obj["geometry"]["location"]["lat"];
latList.Add(lat);
double lng = (double)obj["geometry"]["location"]["lng"];
lngList.Add(lng);
//TODO Add exception handling
}
Dispatcher.Invoke(new Action(() => this.addressGrid.ItemsSource = AddressList));
}
}
catch (Exception ex)
{
Dispatcher.Invoke(new Action(() => MessageBox.Show("Error" + ex.Message)));
}
}
Sounds like it is because you are trying to update an object that is bound to the UI from a non-UI thread. In order for this to work you need to ask the dispatcher to do the update for you like this.
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
//Do something
}));
Personally I use the MVVM-Light framework that has the DispatcherHelper class so I can write code like this
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
//Do something
});