Excel file generated from WinForm app via template is sometimes "InVisible" - c#

We have a WinForm application that uses VSTO to generate an Excel file from a Template.
Occasionally (frequently) the file opens (because you can use the cursor keys and the formula and cell changes) but it is invisible. Even if you save the file and open it back up, it is still invisible.
The users use Excel 2007 and pretty much all (6 - 8) of our users experience this problem.
The (temporary) fix I have given them is to choose "Arrange All". When this is done, the worksheet pops into view.
I have seen several causes and fixes for this on the web. Everything from using a graphic in the template that was in Excel 2003, but isn't in Excel 2007.
The template is pretty "simple". It has formulas, fonts and colors and that is about it.
The template (and WinForm application) is deployed to the users via Click Once.
Here is the code from the "ThisWorkbook.cs" file:
public string TemplateTableName;
public string TemplateSelectStatement;
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
Properties.Settings.Default.myConnectionString = Registry.GetValue("myConnectionString", Properties.Settings.Default.appConnectionString).ToString();
TemplateTableName = Registry.GetValue("TemplateTableName", string.Empty).ToString();
TemplateSelectStatement = Registry.GetValue("TemplateSelectStatement", string.Empty).ToString();
AppLog.ConnectionString = Properties.Settings.Default.myConnectionString;
}
Here is the code from the "Sheet1.cs" file:
private const int StartingDataRow = 4;
private int LastRow;
private int NextAvailableColumn = 18;
DataSet myDS = new DataSet();
Dictionary<string, object[,]> xlsColumnData = new Dictionary<string, object[,]>();
private void Sheet1_Startup(object sender, System.EventArgs e)
{
try
{
if (Globals.ThisWorkbook.TemplateTableName == string.Empty) throw new Exception("TemplateTableName is not set in the registry.");
if (Globals.ThisWorkbook.TemplateSelectStatement == string.Empty) throw new Exception("TemplateSelectStatement is not set in the registry.");
Application.ScreenUpdating = false;
if (Globals.ThisWorkbook.TemplateTableName.Length > 31)
this.Name = Globals.ThisWorkbook.TemplateTableName.Substring(0, 31);
else
this.Name = Globals.ThisWorkbook.TemplateTableName;
LoadTableData();
LoadDataArrays();
BindDataToColumns();
ApplyFormulas();
ApplyFormatting();
this.Range["B4", missing].Select();
Application.ScreenUpdating = true;
AppLog.WriteEvent(DateTime.Now, Environment.UserName, Environment.MachineName, Globals.ThisWorkbook.TemplateTableName, TraceEventType.Information, "Creating customer list");
Globals.ThisWorkbook.RemoveCustomization();
}
catch (Exception ex)
{
AppLog.Show(ex.Message, "Sheet1_Startup", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, TraceEventType.Error);
}
finally
{
Application.ScreenUpdating = true;
}
}
private void LoadTableData()
{
try
{
Application.Cursor = XlMousePointer.xlWait;
string selectCommandText = Globals.ThisWorkbook.TemplateSelectStatement.Replace("[Bind_Type]", "dbo.GetBindingCodeDescription([Bind_Type]) AS Binding_Description");
SqlDataAdapter da = new SqlDataAdapter(selectCommandText, Public_No_Holdings.Properties.Settings.Default.myConnectionString);
da.SelectCommand.CommandTimeout = 60;
if (da.SelectCommand.Connection.State != ConnectionState.Closed) da.SelectCommand.Connection.Close();
da.Fill(this.myDS);
LastRow = (StartingDataRow + this.myDS.Tables[0].Rows.Count) - 1;
}
catch (Exception ex)
{
AppLog.Show(ex.Message, "Loading Table", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Application.Cursor = XlMousePointer.xlDefault;
}
}
private void LoadDataArrays()
{
System.Data.DataTable dt = this.myDS.Tables[0];
// insert the data into the object[,]
object[,] rowData;
dt.Columns["Imprint"].ColumnName = "Publisher"; //Alias the Imprint dataset column to populate the "Publisher" xls column
for (int iCol = 0; iCol < dt.Columns.Count; iCol++)
{
rowData = new object[dt.Rows.Count, 1];
for (int iRow = 0; iRow < dt.Rows.Count; iRow++)
{
switch (dt.Columns[iCol].ColumnName)
{
case "EAN":
rowData[iRow, 0] = "'" + dt.Rows[iRow][iCol];
break;
case "IPage_Link":
rowData[iRow, 0] = String.Format("=HYPERLINK(\"{0}\", \"{1}\")", dt.Rows[iRow][iCol], "iPage");
break;
default:
rowData[iRow, 0] = dt.Rows[iRow][iCol];
break;
}
}
xlsColumnData.Add(dt.Columns[iCol].ColumnName, rowData);
}
}
private void BindDataToColumns()
{
NamedRange nr;
Range rng;
foreach (KeyValuePair<string, object[,]> kvp in xlsColumnData)
{
try
{
if (this.Controls.Contains(kvp.Key))
{
nr = (NamedRange)this.Controls[kvp.Key];
// Reduce range (remove header rows)
rng = this.Range[this.Cells[StartingDataRow, nr.Column], this.Cells[LastRow, nr.Column]];
rng.Value2 = kvp.Value;
}
else
{
this.Cells[StartingDataRow - 1, NextAvailableColumn].Value2 = kvp.Key;
rng = this.Range[this.Cells[StartingDataRow, NextAvailableColumn], this.Cells[LastRow, NextAvailableColumn]];
rng.Value2 = kvp.Value;
NextAvailableColumn++;
}
}
catch (Exception ex)
{
AppLog.Show(ex.Message, "BindDataToColumns - " + kvp.Key, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ApplyFormulas()
{
Range rng;
int iCol;
// Book Invoice
iCol = this.BookInvoice.Column;
rng = this.Range[this.Cells[StartingDataRow, iCol], this.Cells[LastRow, iCol]];
rng.Select();
rng.FillDown();
// Your Cost
iCol = this.YourCost.Column;
rng = this.Range[this.Cells[StartingDataRow, iCol], this.Cells[LastRow, iCol]];
rng.Select();
rng.FillDown();
}
private void ApplyFormatting()
{
// For some reason Hyperlink columns get reset
this.IPage_Link.Font.Name = this.EAN.Font.Name;
this.IPage_Link.Font.Size = this.EAN.Font.Size;
((Range)this.Cells[StartingDataRow, 1]).EntireRow.Select();
Application.ActiveWindow.FreezePanes = true;
}

Related

Excel uploading error in the live version ASP.NET MVC

In my ASP.NET MVC web application, I have used an action to give the user to select the excel file that he wants to upload. Then he submits it and uploaded it to the database.
This works when I run the application from Visual Studio. I have tried in the debug mode.
But when I apply this to the live version, It get an error. User Cannot Upload the excel to the application.
Does any one know the reason why this happens?
This is my controller code
public ActionResult ImportKPIDetails(HttpPostedFileBase excelFile) {
if (excelFile.ContentLength == 0 || excelFile == null) {
ViewBag.Error = "Please select the excel file";
return View("KPIDetails");
} else {
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx")) {
string path = Server.MapPath("~/ExcelFile/" + excelFile.FileName);
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
excelFile.SaveAs(path);
ExcelPath = Server.MapPath("~/ExcelFile/") + path;
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;
Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;
List < KPIUploadVM > xcel = new List < KPIUploadVM > ();
for (int i = 2; i <= range.Rows.Count; i++) {
try {
KPIUploadVM kpi = new KPIUploadVM();
int EmpNo = int.Parse(((Microsoft.Office.Interop.Excel.Range) range.Cells[i, 1]).Text);
var EmpId = (from c in db.CreateEmployee where c.EmpNo == EmpNo select c.Id).First();
kpi.EmpId = EmpId;
kpi.KPI = ((Microsoft.Office.Interop.Excel.Range) range.Cells[i, 2]).Text;
kpi.Year = int.Parse(((Microsoft.Office.Interop.Excel.Range) range.Cells[i, 3]).Text);
KPIUploadVM Udata = new KPIUploadVM();
Udata.EmpId = kpi.EmpId;
Udata.KPI = kpi.KPI;
Udata.Year = kpi.Year;
xcel.Add(Udata);
} catch (Exception) {
workbook.Close(true, Missing.Value, Missing.Value);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
application.Quit();
ViewBag.Error = "Error in " + i + " record";
return View("KPIDetails");
}
}
if (xcel != null) {
try {
foreach(var item in xcel) {
int empID = item.EmpId;
string Kpi = item.KPI;
int year = item.Year;
MainKPI e = new MainKPI();
e.EmpId = empID;
e.KPI = Kpi;
e.Year = year;
e.Status = true;
e.CreatedDate = DateTime.Now;
dbs.MainKPI.Add(e);
dbs.SaveChanges();
}
} catch (Exception ex) {
ViewBag.Error = "Error " + ex;
}
TempData["msg"] = "success";
return View("KPIDetails", xcel);
} else {
}
return View("KPIDetails");
} else {
ViewBag.Error = "Selected excel file not supported";
return View("KPIDetails");
}
}
}

C#- Pull column from Excel to a Checkbox list

I'm trying to pull the info in a column in excel and show it on a Checkbox List in Windows forms.
Right now I have a list of application names in an excel sheet, I am trying to put the cell values into a string array and attach it to the checklist box.
This is my forms class which handles the windows form:
public Form1()
{
InitializeComponent();
//FilesList filesList = new FilesList();
//AppList testApp = new AppList();
//filesList.DirSearch(#"C:\Users\dbell\Downloads\");
Excel e = new Excel(#"SupportedApps.xlsx", 1);
String[] list = e.ReadApplication();
try
{
checkedListBox1.Items.AddRange(list);
}
catch (ArgumentNullException F)
{
Console.WriteLine("Error: " + F.ToString());
}
}
And this below is my poor attempt to create a method which returns a string array from my worksheet:
public string[] ReadApplication()
{
int column = 0;
int row = 1;
int stringNum = 0;
string[] result = null;
try
{
while (ws.Cells[row, column].Value2 != null)
{
result[stringNum] = ws.Cells[row, column].Value2;
row++;
stringNum++;
}
}
catch(NullReferenceException e)
{
Console.WriteLine("Error: " + e.ToString());
}
return result;
}
At the moment I keep getting null results. I have been able to get this working as a CSV file, however I would like to work with only one excel sheet.
Thanks in advance
Try to use https://www.nuget.org/packages/ClosedXML/ library.
ClosedXML.Excel.IXLWorkbook workbook = new XLWorkbook(#"D:\Test.xlsx");
var worksheet = workbook.Worksheets.First();
int column = 1;
int row = 1;
int stringNum = 0;
List<string> result = new List<string>();
try
{
while (worksheet.Cell(row, column).Value != null && row < worksheet.RowCount())
{
result.Add(worksheet.Cell(row, column).Value.ToString());
row++;
stringNum++;
}
}
catch (NullReferenceException e)
{
Console.WriteLine("Error: " + e.ToString());
}

Read a TXT file and transform it into a SQL script

I have a txt file:
LoginId; No_Intervenant
EF2KBT0; 1003820030
ENHD0KE; 1003820129
E9PM7EP; 1003820153
EFT10OO; 1003820218
I need to create another txt file, that contains an sql UPDATE script from this information like:
UPDATE Contact
Set
Contact.No_Intervenant = '1003820030'
where
ISNULL (Contact.LoginId, '') = 'ER7OZXZ';
I only got this result using a Stringbuilder method, but performing hardcode. What I would like is for the header to be added automatically.
public Form1()
{
InitializeComponent();
}
private static void AddSqlCommand(StringBuilder sql, string[] columns, string[] types, string[] values)
{
sql.AppendLine("UPDATE Contact");
sql.AppendLine("SET");
//skip LoginId columns
for (int i = 1; i < columns.Length; i++)
{
switch (types[i].Trim())
{
case "int":
sql.Append($" Contact.{columns[i].Trim()} = {values[i]}");
//sql.Append($" Contact.{columns[0].TrimStart() } = {values[i]}");
break;
default:
sql.Append($" Contact.No_Intervenant = '{values[i]}'");
break;
}
if (columns.Length > 1 && i != columns.Length - 1)
{
sql.Append(",");
}
sql.AppendLine();
}
sql.AppendLine("WHERE");
sql.AppendLine($" ISNULL(Contact.LoginId, '') = '{values[0]}';");
sql.AppendLine();
}
private static StringBuilder GenerateSqlScript(string[] fileContent)
{
var sqlCommand = new StringBuilder();
string[] types = fileContent[0].Split(';');
string[] columns = fileContent[1].Split(';');
//skip the first line (header)
for (int i = 2; i < fileContent.Length; i++)
{
string[] values = fileContent[i].Split(';');
if (values.Length >= 1)
{
AddSqlCommand(sqlCommand, columns, types, values);
}
}
return sqlCommand;
}
How could I get and Add the header automaticaly? Because I'll probably have to do this for longer files, with more columns and more Update lines for other files, and I would not like to hardcode all the headers of the files, like the example I'll have to do next:
Header:
No_Intervenant;First_Name;Last_Name;Role_SE;EMail;Phone;Extension;Statut;Address_1;Address_2;Zip;CPF;Inscription_Particulier;DHM_Stat_Part;Date_via_ClicSeQur;Last_Update;
Data:
1003820030;NOEL;SANTOS;Particulier;;;;Actif;1528 STREET;VAL-D''OR CA;AAA 5T9;123456789;Actif;;2016-07-19 09:49:43;2019-02-08 14:24:19;
I believe you only need a couple of simple changes to your string interpolation, see below. If you have a update that affects multiple tables you should append your table name to the column in the array.
Here is how I tested, according to your logic the first row of the file should contain your data types (the example you posted doesn't). So either your logic is wrong or the data sample is wrong. It works with the test code.
private void button4_Click(object sender, EventArgs e)
{
var line = new List<string>();
line.Add("string;string");
line.Add("LoginId; No_Intervenant");
line.Add("EF2KBT0; 1003820030");
line.Add("ENHD0KE; 1003820129");
line.Add("E9PM7EP; 1003820153");
line.Add("EFT10OO; 1003820218");
var fileContent = line.ToArray();
var sqlCommand = new StringBuilder();
string[] types = fileContent[0].Split(';');
string[] columns = fileContent[1].Split(';');
//skip the first line (header)
for (int i = 2; i < fileContent.Length; i++)
{
string[] values = fileContent[i].Split(';');
if (values.Length >= 1)
{
AddSqlCommand(sqlCommand, columns, types, values, "client");
}
}
}
Edited Fuction:
private static void AddSqlCommand(StringBuilder sql, string[] columns, string[] types, string[] values, string table)
{
sql.AppendLine($"UPDATE {table}");
sql.AppendLine("SET");
//skip LoginId columns
for (int i = 1; i < columns.Length; i++)
{
switch (types[i].Trim())
{
case "int":
sql.Append($" {columns[i].Trim()} = {values[i]}");
break;
default:
sql.Append($" {columns[i].Trim()} = '{values[i]}'");
break;
}
if (columns.Length > 1 && i != columns.Length - 1)
{
sql.Append(",");
}
sql.AppendLine();
}
sql.AppendLine("WHERE");
sql.AppendLine($" ISNULL({columns[0].Trim()}, '') = '{values[0]}';");
sql.AppendLine();
}
}
I believe in this case the 'MERGE' will be a perfect solution.
It could be something like:
-- HEADER --
MERGE [your table] as trg
USING (VALUES
-- DATA FROM THE FILE --
(id, intervenant),
(id, intervenant)
-- FOOTER
) as src(id, intervenant)
ON [your logic from the WHERE statement]
WHEN MATCHED UPDATE SET
trg.[your column] = src.[your column];
The data from the source file can be loaded into a DataTable object, with UPDATE statements then constructed from this. The header names from the file are obtained from the Columns property of the DataTable, then used to specify the columns used in the UPDATE script. In the example below, additional lines and the GO separator are added in the script for formatting. These aren't essential and can be removed if you prefer to.
using System.Linq;
using System.Data;
using System.IO;
using System.Text;
//get source file
string fullFileName = #"C:\Input Folder\SourceFile.txt";
DataTable dt = new DataTable();
StringBuilder sb = new StringBuilder();
//output .sql script
string sqlScript = #"C:\Output Folder\UpdateScript.SQL";
using (StreamReader sr = new StreamReader(fullFileName))
{
string firstLine = sr.ReadLine();
string[] headers = firstLine.Split(';');
//define columns for data table
foreach (string h in headers)
{
dt.Columns.Add(h);
}
int columnCount = dt.Columns.Count;
string line = sr.ReadLine();
while (line != null)
{
string[] fields = line.Split(';');
int currentLength = fields.Count();
if (currentLength < columnCount)
{
while (currentLength < columnCount)
{
line += sr.ReadLine();
currentLength = line.Split(';').Count();
}
fields = line.Split(';');
}
//load data table
dt.Rows.Add(fields);
line = sr.ReadLine();
}
foreach (DataRow dr in dt.Rows)
{
sb.AppendLine("UPDATE Contact SET " + dt.Columns[1] + " = '" + dr[1] +
"' WHERE ISNULL(" + dt.Columns[0] + ", '') = '" + dr[0] + "'");
//extra lines and GO batch separator added between UPDATE statements for formating
sb.AppendLine(Environment.NewLine);
sb.AppendLine("GO");
sb.AppendLine(Environment.NewLine);
}
//output UPDATE commands as .sql script file
File.WriteAllText(sqlScript, sb.ToString());
}
Just to post an update of the code that I updated and that at the moment works perfectly. Thank you all for the answers and for helping me.
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace GenererScriptSQL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private static void AddSqlCommand(StringBuilder sql, string[] columns, string[] types, string[] values)
{
sql.AppendLine("UPDATE Contact");
sql.AppendLine("SET");
//skip LoginId columns
for (int i = 1; i < columns.Length; i++)
{
switch (types[i].Trim())
{
case "int":
sql.Append($" Contact.{columns[i].Trim()} = {values[i]}");
break;
default:
sql.Append($" Contact.{columns[i].Trim()} = '{values[i]}'");
break;
}
if (columns.Length > 1 && i != columns.Length - 1)
{
sql.Append(",");
}
sql.AppendLine();
}
sql.AppendLine();
sql.AppendLine("WHERE");
sql.AppendLine();
sql.AppendLine($" Contact.{columns[0].Trim()} = '{values[0]}'");
sql.AppendLine();
}
private static StringBuilder GenerateSqlScript(string[] fileContent)
{
var sqlCommand = new StringBuilder();
string[] types = fileContent[0].Split(';');
string[] columns = fileContent[0].Split(';');
//skip the first line(header)
for (int i = 1; i < fileContent.Length; i++)
{
string[] values = fileContent[i].Split(';');
if (values.Length >= 1)
{
AddSqlCommand(sqlCommand, columns, types, values);
}
}
return sqlCommand;
}
private void buttonCreateSqlFile_Click(object sender, EventArgs e)
{
try
{
if (IsFileSelected())
{
string[] fileContent = File.ReadAllLines(textBoxFile.Text);
if (fileContent != null)
{
StringBuilder sqlCommand = GenerateSqlScript(fileContent);
if (!string.IsNullOrWhiteSpace(sqlCommand.ToString()))
{
WriteSqlFile(sqlCommand);
}
}
}
else
{
MessageBox.Show("Sélectionner le fichier de chargement.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void buttonSelectFile_Click(object sender, EventArgs e)
{
try
{
using (var fileBrowser = new OpenFileDialog())
{
if (fileBrowser.ShowDialog() == DialogResult.OK)
{
textBoxFile.Text = fileBrowser.FileName;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private bool IsFileSelected()
{
return !string.IsNullOrWhiteSpace(textBoxFile.Text) && File.Exists(textBoxFile.Text);
}
private void WriteSqlFile(StringBuilder sqlCommand)
{
var fileInfo = new FileInfo(textBoxFile.Text);
string BackupDate = fileInfo.Name + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm") + "_Update" + ".sql";
string sqlFilePath = Path.Combine(fileInfo.Directory.FullName, BackupDate);
if (File.Exists(sqlFilePath))
{
File.Delete(sqlFilePath);
}
File.WriteAllText(sqlFilePath, sqlCommand.ToString());
MessageBox.Show($#" Le fichier sql a été générée! {sqlFilePath}");
}
}
}

adding uers to groups in sharepoint

I'm trying to add a user to a sharepoint group based on data from a csv file. I hope that the code marked in bold might be the error.
1.User x=web.Ensureuser("domain\logonname") function--> shows the following error when tried to print any of its file like (x.Title, x.email) --> "The fiels is not assigned" error.
2.Execytequery()--> "The given key is not fount in the dictionary" error.
Please help me with this.
static void Main(string[] args)
{
DataTable dtErrors = new DataTable();
dtErrors.Columns.Add("Links");
dtErrors.Columns.Add("Message");
DataRow drOutputError = dtErrors.NewRow();
DataTable dtCsv = csvToDataTable(System.Configuration.ConfigurationSettings.AppSettings["FilePath"].ToString(), true);
string url = string.Empty;
try
{
foreach (DataRow drCSV in dtCsv.Rows)
{
try
{
url = drCSV[0].ToString();
string grpName = drCSV[1].ToString();
string users = drCSV[2].ToString();
string[] users1 = users.Split(';');
Console.WriteLine("URL picked from CSV: " + url);
using (ClientContext context = new ClientContext(url))
{
Web web = context.Web;
GroupCollection groupColl = web.SiteGroups;
context.Load(groupColl, groups => groups.Include(group => group.Title, group => group.Id));
context.ExecuteQuery();
Console.WriteLine("Groups Count: " + groupColl.Count);
foreach (Group grp in groupColl)
{
try
{
int grpId = grp.Id;
Console.WriteLine("SiteURL: " + url);
Console.WriteLine("Group Name: " + grpName);
//For test purpose
Console.WriteLine(grp.Title);
if (grpName == grp.Title)
{
Console.WriteLine("Match found");
for (int i = 1; i < users1.Length; i++)
{
string temp = users1[i].Remove(0,8);
Console.WriteLine(temp);
**User user = web.EnsureUser(temp);**
Console.WriteLine(user);
addUsersToGroup(grpId, url, user);
}
break;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
drOutputError["Links"] = url;
drOutputError["Message"] = ex.Message.ToString();
dtErrors.Rows.Add(drOutputError);
drOutputError = dtErrors.NewRow();
}
}
}
}
catch (Exception ex)
{
drOutputError["Links"] = url;
drOutputError["Message"] = ex.Message.ToString();
dtErrors.Rows.Add(drOutputError);
drOutputError = dtErrors.NewRow();
}
}
}
catch (Exception ex)
{
drOutputError["Links"] = url;
drOutputError["Message"] = ex.Message.ToString();
dtErrors.Rows.Add(drOutputError);
drOutputError = dtErrors.NewRow();
}
ToCSVError(dtErrors, ",", true);
Console.WriteLine("=======================Completed==================");
Console.ReadLine();
}
public static void addUsersToGroup(int grpId, string url,User user)
{
try
{
using (ClientContext clientContext = new ClientContext(url))
{
Web web = clientContext.Web;
Group testingOwnersGroup = web.SiteGroups.GetById(grpId);
clientContext.Load(testingOwnersGroup);
clientContext.ExecuteQuery();
Console.WriteLine(testingOwnersGroup.Title);
UserCollection collUser = testingOwnersGroup.Users;
collUser.AddUser(user);
clientContext.Load(collUser);
clientContext.Load(testingOwnersGroup);
**clientContext.ExecuteQuery();**
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
public static DataTable csvToDataTable(string file, bool isRowOneHeader)
{
DataTable csvDataTable = new DataTable();
//no try/catch - add these in yourselfs or let exception happen
String[] csvData = System.IO.File.ReadAllLines(file);
//if no data in file ‘manually’ throw an exception
if (csvData.Length == 0)
{
// throw new Exception(CSV File Appears to be Empty”);
}
String[] headings = csvData[0].Split(',');
int index = 0; //will be zero or one depending on isRowOneHeader
if (isRowOneHeader) //if first record lists headers
{
index = 1; //so we won’t take headings as data
//for each heading
for (int i = 0; i < headings.Length; i++)
{
//replace spaces with underscores for column names
headings[i] = headings[i].Replace(" ", "_");
//add a column for each heading
csvDataTable.Columns.Add(headings[i], typeof(string));
}
}
else //if no headers just go for col1, col2 etc.
{
for (int i = 0; i < headings.Length; i++)
{
//create arbitary column names
csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string));
}
}
//populate the DataTable
for (int i = index; i < csvData.Length; i++)
{
//create new rows
DataRow row = csvDataTable.NewRow();
for (int j = 0; j < headings.Length; j++)
{
//fill them
row[j] = csvData[i].Split(',')[j];
}
//add rows to over DataTable
csvDataTable.Rows.Add(row);
}
//return the CSV DataTable
return csvDataTable;
}
static void ToCSVError(DataTable table, string delimiter, bool includeHeader)
{
StringBuilder result = new StringBuilder();
if (includeHeader)
{
foreach (DataColumn column in table.Columns)
{
result.Append(column.ColumnName);
result.Append(delimiter);
}
result.Remove(--result.Length, 0);
result.Append(Environment.NewLine);
}
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
if (item is System.DBNull)
result.Append(delimiter);
else
{
string itemAsString = item.ToString();
// Double up all embedded double quotes
itemAsString = itemAsString.Replace("\"", "\"\"");
// To keep things simple, always delimit with double-quotes
// so we don't have to determine in which cases they're necessary
// and which cases they're not.
itemAsString = "\"" + itemAsString + "\"";
result.Append(itemAsString + delimiter);
}
}
result.Remove(--result.Length, 0);
result.Append(Environment.NewLine);
}
using (StreamWriter writer = new StreamWriter(System.Configuration.ConfigurationSettings.AppSettings["ErrorLog"].ToString(), true))
{
writer.Write(result.ToString());
}
}
}
}

Exception occurs when trying to pass value to crystal report text box object

I am trying to pass value from C# code to a CrystalReport report.
Edit
private void PrintOrder(List<OrderPrintBO> pListOrderBO)
{
DSOrderReport oDSOrderReport = new DSOrderReport();
DataTable oDataTable = oDSOrderReport.Tables[0];
String sOrderNo = "";
if (pListOrderBO.Count > 0)
{
for (int i = 0; i < pListOrderBO.Count; i++)
{
DataRow oRow = oDataTable.NewRow();
oRow["OrderID"] = pListOrderBO[i].OrderID;
oRow["OrderNumber"] = pListOrderBO[i].OrderNumber;
sOrderNo = pListOrderBO[i].OrderNumber;
oDataTable.Rows.Add(oRow);
}
}
oDSOrderReport.Merge(oDataTable);
oDSOrderReport.AcceptChanges();
if (oDSOrderReport.Tables[0].Rows.Count > 0)
{
// Main Copy
PrintDialog printDialog = new PrintDialog();
rptOrder oMainOrder = new rptOrder();
String sCompanyName = System.Configuration.ConfigurationManager.AppSettings["CompanyName"].ToString();
String sPhone1 = System.Configuration.ConfigurationManager.AppSettings["Phone1"].ToString();
String sPhone2 = System.Configuration.ConfigurationManager.AppSettings["Phone2"].ToString();
String sShowOrderNo = System.Configuration.ConfigurationManager.AppSettings["ShowOrderNo"].ToString();
((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtCompanyName"]).Text = sCompanyName;
((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtPhone1"]).Text = "Tel:" + sPhone1;
((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtPhone2"]).Text = "Tel:" + sPhone2;
////This commented out section gives exception
//string sVarOrderNo = "";
//if (sShowOrderNo.ToLower() == "yes")
//{
// sVarOrderNo = sOrderNo;
//}
//((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtOrderNo"]).Text = "O.N. : " + sVarOrderNo;
oMainOrder.SetDataSource(oDSOrderReport);
oMainOrder.PrintOptions.PrinterName = printDialog.PrinterSettings.PrinterName;
try
{
oMainOrder.PrintToPrinter(1, false, 0, 0);
MessageBox.Show("Order Printed Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
else
{
MessageBox.Show("Error in Printing Order", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
End Edit
For the first three text boxes (CompanyName, Phone1 & Phone2), every thing working just fine, but when I tried to pass the OrderNo to the report, Index was outside the bounds of the array. exception is occured, even though my report have a TextBox object named txtOrderNo
I am not sure why this is happening. Please help. Thanks.
Try to change your sOrderNo related code is as below.
string sVarOrderNo = "";
if (sShowOrderNo.ToLower() == "yes")
{
sVarOrderNo = sOrderNo;
}
((CrystalDecisions.CrystalReports.Engine.TextObject)oMainOrder.ReportDefinition.ReportObjects["txtOrderNo"]).Text = "O.N. : " + sVarOrderNo;
UPDATE
Your problem is below mentioned code snippet.Inside the for loop you try to assign a value to sOrderNo. Which is meaningless.B'cos it overrides every time when loop goes.So what is the purpose of this ? If you need this value then you have to bring this value through as your table's row or as a parameter to the report.
if (pListOrderBO.Count > 0)
{
for (int i = 0; i < pListOrderBO.Count; i++)
{
DataRow oRow = oDataTable.NewRow();
oRow["OrderID"] = pListOrderBO[i].OrderID;
oRow["OrderNumber"] = pListOrderBO[i].OrderNumber;
sOrderNo = pListOrderBO[i].OrderNumber;
oDataTable.Rows.Add(oRow);
}
}
I hope this will help to you.

Categories