I have created a textfile programmatically and I saved it into a folder and now I need to save it into a table inside a database(I have already created the table)and after that fill a checkbox with those textfiles and send them to an FTP server.
Is that possible? If so how can I start doing it/what should I do?
Here is the code for creating the textfile and the code to the create the table. If you have any question about the code feel free to ask.
var numfatura = _transaction.TransDocument + _transaction.TransSerial + _transaction.TransDocNumber;
using (StreamWriter writer = new StreamWriter("C:\\Users\\HP8200\\Desktop\\Faturas Teste\\" +numfatura + ".txt"))
{
string numcont = _transaction.PartyFederalTaxID;
double numenc = _transaction.BillToPartyID;
DateTime data = _transaction.CreateDate;
double valor = _transaction.TotalAmount;
int zona = transaction.UnloadPlaceAddress.AddressID;
string zona2 = transaction.UnloadPlaceAddress.AddressLine2;
double quantidade = transaction.Details.Count;
string bonus = "0";
string valorStr = valor.ToString(CultureInfo.InvariantCulture);
writer.WriteLine($"{numcont};{numenc};{numfatura};{data:dd/MM/yyyy};{valorStr};{zona};");
foreach (ItemTransactionDetail detail in transaction.Details)
{
var item = MyApp.DSOCache.ItemProvider.GetItem(detail.ItemID, MyApp.SystemSettings.BaseCurrency);
double taxRate = MyApp.DSOCache.TaxesProvider.GetTaxRateFromTaxableGroupID(detail.TaxableGroupID, "PRT", "CON");
string barcode = item.BarCode;
var preconet = detail.TaxIncludedPrice;
var precoantesdisc = detail.UnitPrice;
string preconetStr = preconet.ToString(CultureInfo.InvariantCulture);
string precoantesdiscStr = precoantesdisc.ToString(CultureInfo.InvariantCulture);
writer.WriteLine($"{barcode};{taxRate};{precoantesdiscStr};{preconetStr};{quantidade};{bonus}");
}
} // create the text file
SqlConnection conn = new SqlConnection(#"Data source = 2c4138928627\Sage ; Database=ARMINDOData ; User Id=sa ; Password=sage2008+");
SqlCommand command = new SqlCommand("IF OBJECT_ID('UXFaturas', 'U') IS NULL CREATE TABLE UXFaturas(Faturas char(250));", conn);
conn.Open();
SqlCommand insertCommand = new SqlCommand("INSERT INTO UXFaturas(Faturas) VALUES (*.txt)", conn);
command.ExecuteNonQuery();
MessageBox.Show("saved"); // create the table and insert the textfile
Create a stored procedure that takes in two parameters fileName and fileContent and then store it inside your UXFaturas table.
CREATE PROC USP_InsertFile(#fileName nvarchar(200),#fileContent nvarchar(max))
AS
BEGIN
INSERT INTO UXFaturas VALUES(#fileName,#fileContent)
END
Here i am assuming that you UXFaturas table only has two columns.
Now you can simple call this stored procedure from your C# ADO code and pass in the right parameters.
using (SqlConnection conn = new SqlConnection(#"Data source = 2c4138928627\Sage ; Database=ARMINDOData ; User Id=sa ; Password=sage2008+"))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "USP_InsertFile";
command.Parameters.AddWithValue("#fileName",fileName);
command.Parameters.AddWithValue("#fileContent",fileContent);
command.ExecuteNonQuery();
}
Related
I'm getting my first steps on programming, so I'm a little green at this. Thanks in advance for the help you can give.
The code is this:
SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString);
SqlCommand myCommand = new SqlCommand();
myCommand.Parameters.AddWithValue("#nome", nome.Value);
myCommand.Parameters.AddWithValue("#data_de_nascimento", Convert.ToDateTime(data_de_nascimento.Value));
myCommand.Parameters.AddWithValue("#rua", rua.Value);
myCommand.Parameters.AddWithValue("#localidade", localidade.Value);
myCommand.Parameters.AddWithValue("#concelho", concelho.Value);
myCommand.Parameters.AddWithValue("#codigo_postal", codigopostal1.Value + " - " + codigopostal2.Value);
myCommand.Parameters.AddWithValue("#pais", pais.Value);
myCommand.Parameters.AddWithValue("#telefone", telf.Value);
myCommand.Parameters.AddWithValue("#telemovel", telem.Value);
myCommand.Parameters.AddWithValue("#email", email.Value);
myCommand.Parameters.AddWithValue("#nif", nif.Value);
SqlParameter val_output = new SqlParameter();
val_output.ParameterName = "#retorno";
val_output.Direction = ParameterDirection.Output;
val_output.SqlDbType = SqlDbType.Int;
myCommand.Parameters.Add(val_output);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.CommandText = "inserir_candidato";
myCommand.Connection = myConn;
myConn.Open();
myCommand.ExecuteNonQuery();
int valor_retornado = Convert.ToInt32(myCommand.Parameters["#retorno"].Value);
myConn.Close();
if (valor_retornado == 0)
{
Lbl_message.Text = "O utilizador já existe";
}
else
{
string caminho = ConfigurationSettings.AppSettings.Get("PathFicheiros");// string que aponta para localhost
string caminhoPDFs = ConfigurationSettings.AppSettings.Get("PathFicheirosPDFs");// string que aponta para local fisico do ficheir
string pdfTemplate = caminhoPDFs + "Template\\template.pdf";
//Response.Write(pdfTemplate);
//Response.End();
Guid g = Guid.NewGuid();
string nomePDF = g + ".pdf";
string newFile = caminhoPDFs + nomePDF;
PdfReader pdfr = new PdfReader(pdfTemplate);
PdfStamper pdfst = new PdfStamper(pdfr, new FileStream(newFile, FileMode.Create));
AcroFields pdfform = pdfst.AcroFields;
pdfform.SetField("nome", nome.Value);// o nome é o atributo que esta na template.
pdfform.SetField("data_de_nascimento", data_de_nascimento.Value);
pdfform.SetField("rua", rua.Value);
pdfform.SetField("localidade", localidade.Value);
pdfform.SetField("concelho", concelho.Value);
pdfform.SetField("codigo_postal", codigopostal1.Value + "-" + codigopostal2.Value);
pdfform.SetField("pais", pais.Value);
pdfform.SetField("telefone", telf.Value);
pdfform.SetField("telemovel", telem.Value);
pdfform.SetField("email", email.Value);
pdfform.SetField("contribuinte", nif.Value);
pdfst.Close();
SqlConnection myConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString);
SqlCommand myCommand2 = new SqlCommand();
myCommand2.Parameters.AddWithValue("#nif", nif.Value);
myCommand2.Parameters.AddWithValue("#gui", g);
myCommand2.CommandType = CommandType.StoredProcedure;
myCommand2.CommandText = "registro_inscricao";
myCommand2.Connection = myConn2;
myConn2.Open();
myCommand2.ExecuteNonQuery();
myConn2.Close();
The stored procedure
CREATE PROCEDURE registro_inscricao
#nif as int,
#gui as uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;
BEGIN
UPDATE registos
SET registo = #gui
WHERE nif = #nif
END
END
And I get this error:
System.Data.SqlClient.SqlEXception: 'Procedure or function registro_inscricao has too many arguments specified'
Already fix one error. Thx to #Klaus. But still can't pass the value of guid to the DB
You could try something below.
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("registro_inscricao", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#nif", SqlDbType.Int).Value = nif.Value;
cmd.Parameters.Add("#gui", SqlDbType.UniqueIdentifier).Value = g;
con.Open();
cmd.ExecuteNonQuery();
}
}
As #xantos said, the code you supplied above does work, however - you didn't include how your variables are declared, if "g" definitely a GUID or are you trying to pass an object that contains a GUID as a property, as you have for the Value property of #nif?
I refactored your C# code as follows, to include the variable definitions (and dispose of the SQL Objects when done - a good practice to clean up after yourself):
static void TestDB()
{
var nif = new { Value = 100 };
Guid g = Guid.NewGuid();
using (SqlConnection myConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString))
{
myConn2.Open();
using (SqlCommand myCommand2 = new SqlCommand())
{
myCommand2.Parameters.AddWithValue("#nif", nif.Value);
myCommand2.Parameters.AddWithValue("#gui", g);
myCommand2.CommandType = CommandType.StoredProcedure;
myCommand2.CommandText = "registro_inscricao";
myCommand2.Connection = myConn2;
myCommand2.ExecuteNonQuery();
}
myConn2.Close();
}
}
I also created a sample Stored Procedure from your definition, as follows:
CREATE PROCEDURE registro_inscricao
#nif as int,
#gui as uniqueidentifier
AS
BEGIN
SET NOCOUNT ON;
BEGIN
PRINT 'GUID: ' + CAST(#gui AS NVARCHAR(50))
--UPDATE registos
--SET registo = #gui
--WHERE nif = #nif
END
END
The result was, it worked first time.
Looks like your problem isn't in the code above, more likely you are attempting to pass a collection or an object.
Check nif.Value is a single INT value and not a collection (e.g. INT[])
Check g is a single GUID value (e.g. it's not defined as a collection type GUID[] or contains a property for your GUID { SomeProperty = GUID }
i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}
I want to update an Oracle Database table after querying the table and applying an encryption function to the retrieved data from some fields. However, my code (below) does not work correctly:
private void button2_Click(object sender, EventArgs e)
{
using (OracleConnection conn = new OracleConnection(oradb))
conn.Open();
OracleCommand select = new OracleCommand("select empno,FNAME,LNAME from employee", conn);
OracleDataReader reader = select.ExecuteReader();
Int64 vempno = 0;
String fnameValue = "";
String lnameValue = "";
String afterConcatfname = "";
String afterConcatlname = "";
if (reader.HasRows)
{
while (reader.Read())
{
vempno = reader.GetInt64(0);
fnameValue = reader.GetString(1);
lnameValue = reader.GetString(2);
REA rea = new REA();
afterConcatfname = rea.Encrypt(fnameValue, rea.GenerateKey());
afterConcatlname = rea.Encrypt(lnameValue, rea.GenerateKey());
}
reader.Close();
}
OracleCommand update = new OracleCommand("update employee set fname =:fname, lname =:lname where empno =:empno", conn);
OracleParameter fname = new OracleParameter("fname", afterConcatfname);
OracleParameter lname = new OracleParameter("lname", afterConcatlname);
OracleParameter empno = new OracleParameter("empno", vempno);
update.Parameters.Add(fname);
update.Parameters.Add(lname);
update.Parameters.Add(empno);
update.ExecuteNonQuery();
}
I don't receive any error but the program encrypts only the last record with all the encrypted values. I want to encrypt every row.
"I dident receive any error ,but the program encrypts only the last record by all the encrypted values "
That's the logic of your code. Basically, what you are doing is this:
loop
read one row
encrypt one row
end loop
update one row
" I want to encrypt row by row "
So you need to move the update logic into the loop, so that it is executed for each row.
A better solution would be to replace row-by-row processing with a set operation, but that's a different question.
I want to insert each line of a Textbox lines to a row of database (line by line) when its TextMode property is Multiline using a foreach loop? I used this code but it inserts all the lines in one row of my "ChTB" table. What is wrong with it?
string ID = null;
DateTime RegDtTime = DateTime.UtcNow;
SqlConnection con1 = new SqlConnection(connectionString);
string sql1 = "SELECT * FROM ChTB";
SqlCommand command1 = new SqlCommand(sql1, con1);
con1.Open();
foreach (object line_loopVariable in this.Textbox1.Text.Split({ Environment.NewLine }, StringSplitOptions.None)) {
line = line_loopVariable;
ID = line;
string commandText = "insert into ChTB(ID,Visible,RegDtTime,LastDateTime) values(#ID,#Visible,#RegDtTime,#LastDateTime)";
SqlCommand cmdObj = new SqlCommand(commandText, con1);
cmdObj.Parameters.AddWithValue("#ID", ID);
cmdObj.Parameters.AddWithValue("#Visible", "NO");
cmdObj.Parameters.AddWithValue("#RegDtTime", RegDtTime);
cmdObj.Parameters.AddWithValue("#LastDateTime", RegDtTime);
cmdObj.ExecuteNonQuery();
}
con1.Close();
Why are you using three different variables for the same value? Just do this:
foreach (var line in myTextBox.Lines)
{
// Use line here.
}
As for the insert, don't create a new command object every time and add new parameters. Create one object, add the parameters and then set their Value properties each time, e.g.
var command = new SqlCommand("INSERT INTO MyTable (SomeColumn) VALUES (#SomeColumn)", connection)
var parameter = command.Parameters.Add("#SomeColumn", SqlDbType.VarChar, 50)
foreach (var line in myTextBox.Lines)
{
parameter.Value = line
// Execute command here.
}
How do I get the last id created in the policy table and store it into a variable so that I can use it for another table called backupspec table.
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("Insert Policies ( PolicyName, PolicyDesc, TimeAdded,OSFlag, CreateVSSSnapshot, CreateAuditLogForRecoveries, AllowUsersToOverwriteFiles, AutoHandleEnvErrors, NotifyOnEnvErrorCount, NotifyOnFileFailure, NotifyOnFileFailureCount, NotifyOnLackOfPCContact, NotifyOnLackOfPCContactDays, NotifyOnRecoveryFailures, NotifyOnRecoveryFailureReason) values (#pn,#pd,#TimeAdded,#os,#vss,#al,#uow,#hee,#oeec,#off,#offc,#oloc,#olocd,#orf,#orfr)");
dataCommand.Parameters.AddWithValue("#pn",pn);
dataCommand.Parameters.AddWithValue("#pd",pd);
dataCommand.Parameters.AddWithValue("#TimeAdded",TimeAdded);
dataCommand.Parameters.AddWithValue("#os",os);
dataCommand.Parameters.AddWithValue("#vss",vss);
dataCommand.Parameters.AddWithValue("#al",al);
dataCommand.Parameters.AddWithValue("#uow",uow);
dataCommand.Parameters.AddWithValue("#hee",hee);
dataCommand.Parameters.AddWithValue("#oeec",oeec);
dataCommand.Parameters.AddWithValue("#off",off);
dataCommand.Parameters.AddWithValue("#offc",offc);
dataCommand.Parameters.AddWithValue("#oloc",oloc);
dataCommand.Parameters.AddWithValue("#olocd",olocd);
dataCommand.Parameters.AddWithValue("#orf",orf);
dataCommand.Parameters.AddWithValue("#orfr",orfr);
dataConnection.Open();
dataCommand.ExecuteNonquery();
dataConnection.Close();
ArrayList jaja = (ArrayList)Session["BackupSpecList"];
for (int i = 0; i < jaja.Count; i++)
{
BackupSpecEntry bsp = (BackupSpecEntry)jaja[i];
string path = bsp.path;
string inclExcl = bsp.inclExcl;
byte inclExclFlags = bsp.inclExclFlags;
bool indexContents = bsp.indexContents;
int serverBackupSpecId = bsp.serverBackupSpecId;
int freq = bsp.freq;
int retention = bsp.retention;
int policyID =DONT KNOW HOW TO GET THIS VALUE;
long specChangeTime = 0;
long backupTime = 0;
dataCommand.CommandText = ("Insert BackupSpec (PolicyID, Path, ServerBackupSpecID, Freq, Retention, InclExclFlags, InclExcl, IndexContents, SpecChangeTime, BackupTime) values (#policyID,#path,#serverBackupSpecId,#freq,#retention,#inclExclFlags,#inclExcl,#indexContents,#specChangeTime,#backupTime)");
dataCommand.Parameters.AddWithValue("#policyID", policyID);
dataCommand.Parameters.AddWithValue("#path", path);
dataCommand.Parameters.AddWithValue("#serverBackupSpecId", serverBackupSpecId);
dataCommand.Parameters.AddWithValue("#freq", freq);
dataCommand.Parameters.AddWithValue("#retention", retention);
dataCommand.Parameters.AddWithValue("#inclExclFlags", inclExclFlags);
dataCommand.Parameters.AddWithValue("#inclExcl", inclExcl);
dataCommand.Parameters.AddWithValue("#indexContents", indexContents);
dataCommand.Parameters.AddWithValue("#specChangeTime", specChangeTime);
dataCommand.Parameters.AddWithValue("#backupTime", backupTime);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
I am getting error with the label id...
can some 1 help me with this..??
I am not getting the last policyID created after inserting please help...
Please help
Use scope_identity:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT #result = scope_identity()"
SQLCommand.CommandText = strSQL;
SQLCommand.Parameters.Add("#result", SqlDbType.Int);
SQLCommand.ExecuteScalar();
int id = SQLCommand.Parameters["#result"].Value;
You can use either SCOPE_IDENTITY or ##IDENTITY
SCOPE_IDENTITY:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT SCOPE_IDENTITY()";
SQLCommand.CommandText = strSQL;
IdReturned = SQLCommand.ExecuteScalar();
##IDENTITY:
strSQL = "INSERT INTO Policies (...) VALUES (#vals....);SELECT ##Identity";
SQLCommand.CommandText = strSQL;
IdReturned = SQLCommand.ExecuteScalar();
For the differences between the two i recommend reading this article
If you do a INSERT INTO Policies() call first, in order to get the lastid, you could do something like this:
int lastId = 0;
using(SqlConnection Connection = new SqlConnection("(connection string)"))
{
string queryStatement =
"INSERT INTO dbo.Policies(fields) OUTPUT Inserted.LastID VALUES(....)";
using(SqlCommand Command = new SqlCommand(queryStatement, Connection))
{
Connection.Open();
lastId = Command.ExecuteScalar();
Connection.Close();
}
}
Use the OUTPUT ....... clause to return the newly inserted lastId.
Then go on and use that value in your main query.
Marc