format export to excel using closedxml with Title - export-to-excel

I am exporting to excel using closedxml my code is working fine, but i want to format my exported excel file with a title, backgroundcolour for the title if possible adding image.
private void button4_Click(object sender, EventArgs e)
{
string svFileName = GetSaveFileName(Convert.ToInt32(comboBox1.SelectedValue));
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
//if (!Directory.Exists(folderPath))
//{
// Directory.CreateDirectory(folderPath);
//}
if (svFileName == string.Empty)
{
DateTime mydatetime = new DateTime();
SaveFileDialog objSaveFile = new SaveFileDialog();
objSaveFile.FileName = "" + comboBox1.SelectedValue.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx";
objSaveFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
objSaveFile.FilterIndex = 2;
objSaveFile.RestoreDirectory = true;
string folderpath = string.Empty;
Cursor.Current = Cursors.WaitCursor;
if (objSaveFile.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
FileInfo fi = new FileInfo(objSaveFile.FileName);
folderpath = fi.DirectoryName;
int rowcount = 0;
int sheetcount = 1;
int temprowcount = 0;
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt,comboBox1.Text.ToString() + sheetcount.ToString());
ws.Row(1).Height=50;
//ws.FirstRow().Merge();
ws.Row(1).Merge();
//ws.Row(1).Value = comboBox1.Text.ToString();
//ws.Row(1).Cell(1).im
ws.Row(1).Cell(1).Value = comboBox1.Text.ToString();
ws.Row(1).Cell(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(1).Cell(1).Style.Alignment.Vertical=XLAlignmentVerticalValues.Center;
ws.Row(1).Cell(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Row(1).Cell(1).Style.Font.FontColor = XLColor.White;
ws.Row(1).Cell(1).Style.Font.FontSize = 21;
ws.Row(1).Cell(1).Style.Font.Bold = true;
ws.Column(1).Merge();
ws.Column(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Cell(2, 2).InsertTable(dt);
wb.SaveAs(fi.ToString());
//wb.SaveAs(folderpath + "\\" + comboBox1.SelectedItem.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx");
//rowcount = 0;
//sheetcount++;
//}
}
//}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}
else
{
Cursor.Current = Cursors.WaitCursor;
string folderpath = string.Empty;
folderpath = Properties.Settings.Default.ODRSPath + "\\" + svFileName;
using (XLWorkbook wb = new XLWorkbook())
{
//DateTime mydatetime = new DateTime();
wb.Worksheets.Add(dt, comboBox1.SelectedItem.ToString());
wb.SaveAs(folderpath);
}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}

Related

Output SQL Table to existing Excel file/ new worksheet in SSIS / C# in script task

Good day,
I had a request to create a SSIS package that would output an SQL table to an Excel file. I had no problem creating this. However, the client came back asking that they wanted to be able to output the SQL table content to an existing Excel file in a new worksheet. If the worksheet does not exists in my following script, it is being created. However, it just goes back in the loop and fail because now it exists.
Here is my code:
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
string currentTab;
DataTable ExcelFileTabs;
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
string FullExcelFilePath = FolderPath + ExcelFileName + ".xlsx";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FullExcelFilePath + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
// Verify if file exists
if (File.Exists(FullExcelFilePath))
{
//Verify if the sheet exists
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
currentTab = excelTable["TABLE_NAME"].ToString();
if (currentTab == SheetName)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine("The sheet " + SheetName + " that your are trying to create in " + FullExcelFilePath + " already exists.");
sw.WriteLine("Please enter another sheet name or delete the Excel file and try again.");
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Failure;
}
else
{
// Create the worksheet in the existing Excel file
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
}
}
else
{
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
}
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
ExcelFileTabs = Excel_OLE_Con.GetSchema("Tables");
foreach (DataRow excelTable in ExcelFileTabs.Rows)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + "_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
Can somebody please help me with this ? I am pretty new to C#, and English is not my primary language. Please let me know if this is not clear enough.
Thanks in advance for you time :-)
Mylene
You know when you are trying to find the solution way to fare when it is just in front of you ?
My code, before wanting to catch the error if the user was trying to add a worksheet that already exists, already was trowing an exception in those cases...
public void Main()
{
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
//Declare Variables
string ExcelFileName = Dts.Variables["$Package::ExcelFileName"].Value.ToString();
string FolderPath = Dts.Variables["$Package::FolderPath"].Value.ToString();
string TableName = Dts.Variables["$Package::SQLTableName"].Value.ToString();
string SchemaName = Dts.Variables["$Package::SQLTableSchema"].Value.ToString();
string SheetName = Dts.Variables["$Package::SheetName"].Value.ToString();
ExcelFileName = ExcelFileName + "_" + datetime;
string lastChar = FolderPath.Substring(FolderPath.Length - 1);
//Validate format of FolderPath
if (lastChar != "\\")
{
FolderPath = FolderPath + "\\";
}
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
//Construct ConnectionString for Excel
string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
//USE ADO.NET Connection from SSIS Package to get data from table
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["ADO_DBConnection"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Load Data into DataTable from SQL ServerTable
// Assumes that connection is a valid SqlConnection object.
string queryString = "SELECT * from " + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
DataSet ds = new DataSet();
adapter.Fill(ds);
//Get Header Columns
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["$Package::FolderPath"].Value.ToString() + "\\" + Dts.Variables["$Package::ExcelFileName"].Value.ToString() + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
}
Error log :
System.Data.OleDb.OleDbException (0x80040E14): Table 'Test9' already exists.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ST_a21007570143466693913591932c30b7.ScriptMain.Main()
Problem resolved.

How can I get the proper value of proper button with this method?

Code:
for (int i = 1; i < butonsayisi; i++)
{
int buttonvalue = 1;
var buttonmenu = new Button
{
HeightRequest = 100,
WidthRequest = 100,
Margin = 5,
CornerRadius = 15,
BackgroundColor = Color.FromRgb(192,192,192),
};
buttonmenu.Clicked += butonmenu;
butonlar.Children.Add(buttonmenu);
if (baglanti.State.ToString() == "Open")
{
}
else
{
baglanti.Open();
}
SqlCommand getir = new SqlCommand("select * from butonlar where id = '" + i.ToString() + "'", baglanti);
SqlDataReader oku = getir.ExecuteReader();
while (oku.Read())
{
buttonmenu.Text = oku.GetValue(1).ToString();
baglanti.Close();
break;
}
async void butonmenu(object o, EventArgs args)
{
baglanti.Open();
SqlCommand getirici = new SqlCommand("select * from butonlar where id = '" + buttonvalue.ToString() + "'", baglanti);
SqlDataReader okuyucu = getirici.ExecuteReader();
while (okuyucu.Read())
{
butonadi = okuyucu.GetValue(2).ToString();
baglanti.Close();
break;
}
await DisplayAlert("Alert","Deneme " + butonadi,"OK");
buttonvalue++;
}
}
I have to reach the right buttonvalue.
butonsayisi counts how much row I have in database, this is how I create buttons and after that I edit the name of buttons with buttonmenu.Text = oku.GetValue(1).ToString(); in index 1 I have the the name of buttons.
So in index 2 I have another table name. When I press the button, I have to get the right table name. With this method I use, I am taking another button's index 2.
await DisplayAlert("Alert","Deneme " + butonadi,"OK"); is just for testing.
i did it guys!
simply i did;
SqlCommand getirici = new SqlCommand("select * from butonlar where butonadi = '" + buttonmenu.Text + "'", baglanti);
SqlDataReader okuyucu = getirici.ExecuteReader();
while (okuyucu.Read())
{
butonadi = okuyucu.GetValue(2).ToString();
baglanti.Close();
break;
}
i used to get the value from id now i get from name of button so it works!

How do I convert a Word Table into an embedded Excel Worksheet?

I have a document that has multiple Word Tables. I need to convert them into embedded Excel Worksheets (or COM Objects). I've been able to "import" the Word Tables into Excel using the following:
Excel.Application xlApp = new Excel.Application();
// Call the conversion tool
for (int i = 1; i <= curDoc.Tables.Count; i++ )
{
Word.Table tbl = curDoc.Tables[i];
Word.Range tblLoc = tbl.Range;
// Used for debugging.
xlApp.Visible = true;
if (xlApp == null)
{
messageAlert = "Excel could not be started. Check that your office installation and project references are correct.";
break;
}
Excel.Workbook wb = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
if (ws == null)
{
messageAlert = "Worksheet could not be created. Check that your office installation and project reference are correct.";
break;
}
Word.Range rng = tbl.ConvertToText(Separator: ";", NestedTables: false);
string sData = rng.Text;
string[] rows = sData.Split('\r');
int r = 1, c = 1;
int numRows = rows.Count();
int numCols = rows[0].Split(';').Count();
foreach (string row in rows)
{
string[] cells = row.Split(';');
foreach (string cell in cells)
{
ws.Cells[r, c].Value = cell;
c += 1;
}
r += 1;
c = 1;
}
Problem is whenever I copy the contents back into the document, a new Word Table is created instead of an Excel Worksheet. How do I either import an Excel Worksheet into Word, or directly convert the tables into Excel Worksheets?
In order to do this, you'll have to first save the excel worksheet and then import it as an OLEObject. Here's an example:
public void ConvertTables()
{
string messageAlert = "";
Word.Application curApp = Globals.ThisAddIn.Application;
Word.Document curDoc = curApp.ActiveDocument;
if (curDoc.Tables.Count > 0)
{
Excel.Application xlApp = new Excel.Application();
//Used for debugging.
//xlApp.Visible = true;
//Call the conversion tool
for (int i = 1; i <= curDoc.Tables.Count; i++ )
{
Word.Table tbl = curDoc.Tables[i];
Word.Range tblLoc = tbl.Range;
if (xlApp == null)
{
messageAlert = "Excel could not be started. Check that your office installation and project references are correct.";
break;
}
Excel.Workbook wb = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
if (ws == null)
{
messageAlert = "Worksheet could not be created. Check that your office installation and project reference are correct.";
break;
}
Word.Range rng = tbl.ConvertToText(Separator: ";", NestedTables: false);
string sData = rng.Text;
string[] rows = sData.Split('\r');
int r = 1, c = 1;
int numRows = rows.Count();
int numCols = rows[0].Split(';').Count();
foreach (string row in rows)
{
string[] cells = row.Split(';');
foreach (string cell in cells)
{
ws.Cells[r, c].Value = cell;
c += 1;
}
r += 1;
c = 1;
}
ws.SaveAs("C:\\temp\\test.xlsx");
rng.Text = "";
rng.InlineShapes.AddOLEObject(ClassType: "Excel.Sheet.12", FileName: "C:\\temp\\test.xlsx");
ws.Range["A1", ws.Cells[numRows, numCols]].Value = "";
ws.SaveAs("C:\\Temp\\test.xlsx");
}
xlApp.Quit();
messageAlert = "Tables converted";
}
else
{
// No tables found
messageAlert = "No tables found within the document";
}
MessageBox.Show(messageAlert);
}

Silverlight some wcf problems

I have created a WCF Service which is called many times,
An example of a call
This Service will do a call to a Database. Lets say in my Client I do have a List with 200 Values. Every Value will match a Database Entry. Every Database Entry does have 10 Values. Now what I do is the following. I select some of the list entrys and call in a loop the WCF Service.
I have 2 Issues
First: the UI will hang for that time the WCF Calls are made
Second: The data will come back step by step, how can I collect them and send it back when all calls are completed?
Please excuse any typos I made, my english is not the best.
Here is my source code
[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[OperationContract]
public List<string> GetData(string sWert1, string sWert2)
{
List<string> realtimanswer = new List<string>();
string applicationPath = HostingEnvironment.MapPath("~/Configuration");
cIniReader _ini = new cIniReader(applicationPath + #"\config.ini");
string connectionString = _ini.ReadString("Database", "ConnectionString", "");
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connectionString;
try
{
connection.Open();
OracleCommand cmd = connection.CreateCommand();
cmd = new OracleCommand("GETDATA", connection);
cmd.Parameters.Clear();
OracleParameter param1 = new OracleParameter("PI_Wert1", OracleDbType.Varchar2);
OracleParameter param2 = new OracleParameter("PI_Wert2", OracleDbType.Varchar2);
OracleParameter param3 = new OracleParameter("PO_Wert3", OracleDbType.Int16);
OracleParameter param4 = new OracleParameter("PO_Wert3", OracleDbType.Int16);
OracleParameter param5 = new OracleParameter("PO_Wert4", OracleDbType.Int16);
param1.Value = sWert1;
param2.Value = sWert2;
param1.Direction = System.Data.ParameterDirection.Input;
param1.Size = 4096;
param2.Direction = System.Data.ParameterDirection.Input;
param2.Size = 4096;
param3.Direction = System.Data.ParameterDirection.Output;
param3.Size = 4096;
param4.Direction = System.Data.ParameterDirection.Output;
param4.Size = 4096;
param5.Direction = System.Data.ParameterDirection.Output;
param5.Size = 4096;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
cmd.Parameters.Add(param3);
cmd.Parameters.Add(param4);
cmd.Parameters.Add(param5);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//cmd.CommandTimeout = 30;
int test = cmd.ExecuteNonQuery();
string returnCode = cmd.Parameters[17 - 1].Value.ToString();
if (returnCode == "OK")
{
string sErg1 = cmd.Parameters[3 - 1].Value.ToString();
realtimanswer.Add(sErg1);
string sErg2 = cmd.Parameters[4 - 1].Value.ToString();
realtimanswer.Add(sErg2);
string sErg3 = cmd.Parameters[5 - 1].Value.ToString();
realtimanswer.Add(sErg3);
string sErg4 = cmd.Parameters[6 - 1].Value.ToString();
realtimanswer.Add(sErg4);
string sErg5 = cmd.Parameters[7 - 1].Value.ToString();
realtimanswer.Add(sErg5);
}
}
catch (Exception exp)
{
cDebugLog.Log("Error in Function: GetData " + exp.Message + " StackTrace: " + exp.StackTrace);
connection.Close();
}
connection.Close();
return realtimanswer;
}
}
I call this with this Code
void Button1_Click(object sender, EventArgs e)
{
busyRealTimeViewPage.IsBusy = true;
try
{
string url = Application.Current.Host.Source.AbsoluteUri;
url = url.Replace("/ClientBin/ICWeb.xap", "/DBService.svc");
var proxy_GetRealTime_DBService = new DBServiceReference.DBServiceClient();
proxy_GetRealTime_DBService.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);
proxy_GetRealTime_DBService.GetDataCompleted += new EventHandler<DBServiceReference.GetDataCompletedEventArgs>(proxy_GetRealTime_DBService_GetDataCompleted);
for (int i = 0; i < lstRealtime.Items.Count; i++)
{
if ((lstRealtim.ItemsSource as ObservableCollection<ListOfData>)[i].IsSelected == true)
{
object[] w_toread = new object[5];
string sWrk = (lstMappedWorkgroups.ItemsSource as ObservableCollection<ListOfWorkgroups>)[i].Content;
w_toread[0] = sDat;
w_toread[1] = sDat + "_DE";
w_toread[2] = sDat + "_FR";
proxy_GetRealTime_DBService.GetDataAsync(w_toread[1].ToString(), "current", w_toread[1]);
proxy_GetRealTime_DBService.GetDataAsync(w_toread[2].ToString(), "current", w_toread[2]);
}
}
}
catch (Exception exp)
{
cDebugLog logger = new cDebugLog();
logger.LogMessage("Error in Function: Button1_Click " + exp.Message + " StackTrace: " + exp.StackTrace);
}
and now here is the rest of it
void proxy_GetRealTime_DBService_GetDataCompleted(object sender, DBServiceReference.GetMarqueeDataCompletedEventArgs e)
{
try
{
string help = e.UserState.ToString();
string sWrktoView = cStringFunctions.Left(e.UserState.ToString(), help.Length - 3);
// string sWrktoView = (lstMappedWorkgroups.ItemsSource as ObservableCollection<ListOfWorkgroups>)[i].Content;
string sWrktoViewDE = sWrktoView + "_DE";
string sWrktoViewFR = sWrktoView + "_FR";
if ((sWrktoViewDE == e.UserState.ToString()) || (sWrktoViewFR == e.UserState.ToString()))
{
if (!(toView.Any(wrk => wrk.Workgroup == sWrktoView)))
{
if (sWrktoViewDE == e.UserState.ToString())
{
toView.Add(new RealtTime(sWrktoView, sWrktoViewDE, e.Result[0], e.Result[1], e.Result[2], e.Result[3], e.Result[4], e.Result[5], e.Result[6], e.Result[7], e.Result[8], e.Result[9], e.Result[10], e.Result[11], e.Result[12], e.Result[13], sWrktoViewFR, "", "", "", "", "", "", "", "", "", "", "", "", "", ""));
}
if (sWrktoViewFR == e.UserState.ToString())
{
toView.Add(new RealtTime(sWrktoView, sWrktoViewDE, "", "", "", "", "", "", "", "", "", "", "", "", "", "", sWrktoViewFR, e.Result[0], e.Result[1], e.Result[2], e.Result[3], e.Result[4], e.Result[5], e.Result[6], e.Result[7], e.Result[8], e.Result[9], e.Result[10], e.Result[11], e.Result[12], e.Result[13]));
}
}
}
if (sWrktoViewFR == e.UserState.ToString())
{
var wrkFR = toView.FirstOrDefault(x => x.WorkgroupFR == sWrktoViewFR);
if (wrkFR != null)
{
wrkFR.WorkgroupFR = sWrktoViewFR;
wrkFR.erg1FR = e.Result[0];
wrkFR.erg2FR = e.Result[1];
wrkFR.erg3FR = e.Result[2];
wrkFR.erg4FR = e.Result[3];
wrkFR.erg5FR = e.Result[4];
// fill with other data
}
}
if (sWrktoViewDE == e.UserState.ToString())
{
var wrkDE = toView.FirstOrDefault(x => x.WorkgroupDE == sWrktoViewDE);
if (wrkDE != null)
{
wrkDE.WorkgroupDE = sWrktoViewDE;
wrkDE.erg1DE = e.Result[0];
wrkDE.erg2DE = e.Result[1];
wrkDE.erg3DE = e.Result[2];
wrkDE.erg4DE = e.Result[3];
wrkDE.erg5DE = e.Result[4];
// fill with other Data
}
}
dgridRealTimeView.ItemsSource = null;
dgridRealTimeView.ItemsSource = toView;
busyRealTimeViewPage.IsBusy = false;
}
catch (Exception exp)
{
cDebugLog logger = new cDebugLog();
logger.LogMessage("Methode: proxy_GetRealTime_DBService_GetDataCompleted: " + exp.Message + " StackTrace: " + exp.StackTrace);
}
}
I hope someone can help me out.
Regards
Martin
This call
for (int i = 0; i < lstRealtime.Items.Count; i++)
can take a long time if the there are a lot of items in the list.
You should consider creating a new method on the WCF Service to do all the operations and then returning the result.
public List<string> GetData(string[] sWert1, string[] sWert2)
{
}

Microsoft Interop Outlook c# - invalidcastexception?

Suddenly getting a System.invalidcastexception: unable to cast COM object of type 'system._object' to interface type 'Microsoft.office.interop.outlook.mailitem' ... to a program I wrote that was working fine and now BAM! Exception.
Not sure why... please note I'm a novice programmer.
Here's a snippet of coding where I'm using the Outlook things :
using Microsoft.Office.Interop.Outlook;
static Microsoft.Office.Interop.Outlook.Application app = null;
static _NameSpace ns = null;
static MailItem item = null;
static MAPIFolder inboxFolder = null;
static MAPIFolder dest = null;
static void SendMail(string mailSubject, string htmlMailBody, string mailTo)
{
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
NameSpace outlookNS = outlookApp.GetNamespace("MAPI");
outlookNS.Logon(Missing.Value, Missing.Value, true, true);
MailItem oMsg = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
oMsg.To = mailTo;
oMsg.Recipients.ResolveAll();
StreamReader sr = new StreamReader(#"C:\Users\" + WindowsIdentity.GetCurrent().Name.Split('\\')[1] + #"\AppData\Roaming\Microsoft\Signatures\Default.htm");
string signature = sr.ReadToEnd();
oMsg.Subject = mailSubject;
oMsg.HTMLBody = htmlMailBody + "<br><br>" + signature + "</font>";
oMsg.Save();
((Microsoft.Office.Interop.Outlook._MailItem)oMsg).Send();
oMsg = null;
outlookNS = null;
outlookApp = null;
}
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
#region match - convert - extract
foreach (string tifFile in Directory.GetFiles(workFolder, "*.tif", SearchOption.TopDirectoryOnly))
{
string currentFile = Path.GetFileNameWithoutExtension(tifFile);
for (int i = 1; i <= inboxFolder.Items.Count; i++)
{
//##############CODE CRASHES HERE##############
item = (MailItem)inboxFolder.Items[i];
// item = inboxFolder.Items[i];
if (item.Body != "")
{
if ((item.Body.Contains("Box Number =")) && (item.Body.Contains("Contract ID = ")) && (item.Body.Contains("Branch = ")) && (item.Body.Contains(currentFile.Replace('_', '/'))))
{
// matchFound = true;
MailStack current = new MailStack();
Console.WriteLine("________________________");
Console.WriteLine("File matched \t\t:\t" + currentFile + ".tif");
I've looked around but can't make much sense of the answers available.
any help appreciated.
Try this...
item = inboxFolder.Items[i] as MailItem;
if (item != null)
{
// ...
}

Resources