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

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.

Related

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 can Dynamics CRM Statuscodes / Statecode Optionsets sort order be updated?

The UI Editor in Dynamics CRM won't allow system admins to directly edit status/statecode picklists on the Activity Entity. How can the order be edited programatically?
In another question, information is provided about how to get metadata about statuscodes and statecodes:
Dynamics Crm: Get metadata for statuscode/statecode mapping
Microsoft provides a class for sorting order of picklists:
https://learn.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg327607(v%3dcrm.8)
I have successsfully coded and can retrieve metadata for both standard picklists and for statuscodes picklists (both the statecode and statuscode). I can programatically update the sort order on standard picklists, but when attempting to do so on a statuscode optionset, no errors are thrown and no changes are published to the system.
How can the sort order on the activity statuscode field be updated?
Example code follows, complete with both tests:
namespace ConsoleApps
{
class EditAptStatusCodeOptionSetOrder
{
static void Main()
{
//Connect to Database
string CRMConnectionString = #"AuthType = Office365; URL = https://URLOFSERVER; Username=USERNAME; Password=PASSWORD;";
Console.WriteLine("Connecting to Auric Solar Sandbox Environment Using Ryan Perry's Credentials. ");
CrmServiceClient crmServiceClient = new CrmServiceClient(CRMConnectionString);
IOrganizationService crmService = crmServiceClient.OrganizationServiceProxy;
//Test Retrieving Stage (Statuscode) from Test Entity.
//Get the Attribute
RetrieveAttributeRequest retrieveStatusCodeAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "new_testentity",
LogicalName = "statuscode",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveStatusCodeAttributeResponse =
(RetrieveAttributeResponse)crmService.Execute(retrieveStatusCodeAttributeRequest);
Console.WriteLine("Retreived Attribute:" +
retrieveStatusCodeAttributeResponse.AttributeMetadata.LogicalName);
Console.WriteLine("Retreived Attribute Description:" +
retrieveStatusCodeAttributeResponse.AttributeMetadata.Description);
StatusAttributeMetadata statusCodeMetaData =
(StatusAttributeMetadata)retrieveStatusCodeAttributeResponse.AttributeMetadata;
Console.WriteLine("Metadata Description:" +
statusCodeMetaData.Description);
Console.WriteLine("Metadata IsValidForUpdate:" +
statusCodeMetaData.IsValidForUpdate.ToString());
Console.WriteLine("OptionSet Type:" +
statusCodeMetaData.OptionSet.Name.ToString());
Console.WriteLine("OptionSet Name:" +
statusCodeMetaData.OptionSet.OptionSetType.ToString());
Console.WriteLine("Retrieved Options:");
foreach (OptionMetadata optionMeta in statusCodeMetaData.OptionSet.Options)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Save Options in an array to reorder.
OptionMetadata[] optionList = statusCodeMetaData.OptionSet.Options.ToArray();
Console.WriteLine("Option Array:");
foreach (OptionMetadata optionMeta in optionList)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
var sortedOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
Console.WriteLine("Sorted Option Array:");
foreach (OptionMetadata optionMeta in sortedOptionList)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Create the request.
OrderOptionRequest orderStatusCodeOptionRequest = new OrderOptionRequest
{
AttributeLogicalName = "statuscode",
EntityLogicalName = "new_testentity",
Values = sortedOptionList.Select(X => X.Value.Value).ToArray()
};
Console.WriteLine("orderStatusCodeOptionRequest Created.");
//Execute Request. //////THIS DOESN'T THROW ERRORS, BUT DOESN'T UPDATE SYSTEM.
OrderOptionResponse orderStatusCodeResponse = (OrderOptionResponse)crmService.Execute(orderStatusCodeOptionRequest);
Console.WriteLine("Request Executed");
////////////////////////////////////////PICKLIST TEST//////////////////////////////////
Console.WriteLine("\n\nTestingPickList");
RetrieveAttributeRequest retrieveTestPicklistAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "new_testentity",
LogicalName = "new_testpicklist",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveTestPicklistAttributeResponse =
(RetrieveAttributeResponse)crmService.Execute(retrieveTestPicklistAttributeRequest);
PicklistAttributeMetadata pickListMetaData =
(PicklistAttributeMetadata)retrieveTestPicklistAttributeResponse.AttributeMetadata;
Console.WriteLine("Retrieved Picklist Options:");
foreach (OptionMetadata optionMeta in pickListMetaData.OptionSet.Options)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Save Options in an array to reorder.
OptionMetadata[] picklistOptionList = pickListMetaData.OptionSet.Options.ToArray();
Console.WriteLine("Picklist Option Array:");
foreach (OptionMetadata optionMeta in picklistOptionList)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
var sortedPicklistOptionList = picklistOptionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
Console.WriteLine("Picklist Sorted Option Array:");
foreach (OptionMetadata optionMeta in sortedPicklistOptionList)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Create the request.
OrderOptionRequest orderPicklistOptionRequest = new OrderOptionRequest
{
AttributeLogicalName = "new_testpicklist",
EntityLogicalName = "new_testentity",
Values = sortedPicklistOptionList.Select(X => X.Value.Value).ToArray()
};
Console.WriteLine("orderPicklistOptionRequest Created.");
//Execute Request.
OrderOptionResponse orderPicklistResponse = (OrderOptionResponse)crmService.Execute(orderPicklistOptionRequest);
Console.WriteLine("Order Picklist Request Executed");
//Publish All.
Console.WriteLine("Publishing. Please Wait...");
PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
crmService.Execute(publishRequest);
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}

format export to excel using closedxml with Title

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.");
}
}

whats failed due to data type mismatch in criteria expression c#?

am trying to develop a c# standalone application and my insert code has no error but when i click it will insert to first table or crtPro perfectly but it didn't add to the second table , can anyone give me some hint...???
here is my code for insert code...
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Documents and Settings\abel\My Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Address = txtAddress.Text.ToString();
//String Wereda = txtWereda.Text.ToString();
//String Kebele = txtKebele.Text.ToString();
//String House_No = txtHouse.Text.ToString();
//String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
//String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String Status = ToString();
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "INSERT INTO crtPro(Name,Address,Email,Tel,Item,Dep,Status,Remark)VALUES('" + Name + "','" + Address + "','" + Email + "','" + Tel + "','" + Item + "','" + Dep + "','" + Remark + "')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Open();
String my_querry1 = "SELECT LAST(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
//txtStatus.Text = var;
String PID = ToString();
String my_querry2 = "INSERT INTO crtItemLicense(PID,Type,Brand,License_No,Date_issued)VALUES('" +PID + "','" + Type + "','" + Brand + "','" + License_No + "','" + Date_issued + "')";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
There are a couple of calls like:
String PID = ToString();
That will try to get a string representation of 'this', which is your form. That is probably not what you want to be inserting into the database. You probably meant
String PID = var.ToString();
If that isn't it, then try putting more tracewrites (or using a debugger) to narrow the problem down to find which one of your sql statements is causing the problem.
Also once you have it working, try entering this in the name field of your form:
Robert"); DROP TABLE crtPro;--
and then do some googling about SQL injection (apologies to XKCD).

How to replace a String at the end when Building a String with multiple Data?

HI all i am Building A string Which looks like this
[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
i am building this string with this data
public JsonResult ResourceBugReports()
{
int projectid;
int Releasphaseid;
projectid = 16;
Releasphaseid = 1;
var ResourceReports = db.ExecuteStoreQuery<ResourceModel>("ResourceBugReports #ProjectId,#ReleasePhaseId", new SqlParameter("#ProjectId", projectid), new SqlParameter("#ReleasePhaseId", Releasphaseid)).ToList();
DataSet ds = new DataSet();
var model1 = new WeeklyBugCount
{
Resources = ResourceReports
};
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
foreach (var row in model1.Resources)
{
BugsCount = BugsCount + row.Assignedbugs + ",";
}
foreach (var row in model1.Resources)
{
BugsCount1 = BugsCount1+ row.Closedbugs + ",";
}
foreach (var row in model1.Resources)
{
Bugscount2 = Bugscount2 + row.Fixedbugs + "," ;
}
foreach (var row in model1.Resources)
{
BugsCount3 = BugsCount3 + row.Reopenedbugs + ",";
}
ComboinedString = ResourceName1 + "/" + BugsCount + "/" + BugsCount1 + "/" + Bugscount2 + "/" + BugsCount3;
return Json(ComboinedString, JsonRequestBehavior.AllowGet);
}
my
ComboinedString =[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
but i want this string
ComboinedString =[Anil Kumar K,Niharika,Raghu/4,0,0/3,0,0,/1,1,1/1,0,0]
i want to remove this "," before the "/" in this strin or replace it..can any one help me
Add this statement
I hope it will help you
String CombinedString1 = CombinedString.Replace(",/", "/");
A simple solution is a search and replace on the string replacing ",/" with "/".
A better solution is, rather than using a for() loop and appending a comma at the end of each value, is use String.Join(). For example, replace:
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
with
ResourceName1 = string.Join(",", model1.Resources.ToArray())
This will remove the trailing comma.
A simple solution would be to use String.EndsWith() function i.e.
string str = "ksjf,sjsfj,sfs,";
if (str.EndsWith(","))
{
str = str.Remove(str.Length - 1);
}
Off the top of my head, you could try to replace with a simple regular expression:
string input = "dsgd,sdgsdg,dsgsdg,sdg,";
string output = Regex.Replace(input, ",$", "");
//output: "dsgd,sdgsdg,dsgsdg,sdg"
#user1542652's solution is simple and works just as well.

Resources