I am trying to insert a text file formatted in C Sharp to a Microsoft SQL server. I have 2 tables Transaction and TMatch in which I want to populate the data. 4 attributes each. I have created 2 classes for each. I am aware of how to input data manually into the database through the .Add() and .SaveChanges().
Here is what I have so far:
//Database insertions
TTransaction txn = new TTransaction();
**txn.Amount = 56; //I want a variable used below (AMOUNT) to go into amount.
txn.TRN = "sdfgsdfg";** //(TxnNo) to go into TRN
ScotiaNYAEntities context = new ScotiaNYAEntities();
context.TTransactions.Add(txn);
context.SaveChanges();
Traversing the text file using a while loop.
{
if (line.Contains("AMOUNT:")) //Look where to end for Transaction Text
{
// For Amount
IsAmount=true;
if(IsAmount)
{
Amount = line.Replace("AMOUNT:", String.Empty).Trim();
Console.WriteLine("AMOUNT: ********");
Console.WriteLine(Amount);
}
}..............................................
I am not sure how to reference a variable instead of just values.
Thank you.
leap of faith but you could have something like this
using (ScotiaNYAEntities context = new ScotiaNYAEntities())
{
foreach (string line in File.ReadLines(pathToFile))
{
if (line.Contains("AMOUNT:"))
{
if (IsAmount)
{
string amount = line.Replace("AMOUNT:", string.Empty).Trim();
TTransaction txn = new TTransaction();
txn.Amount = amount;
txn.TRN = "sdfgsdfg";
context.TTransactions.Add(txn);
}
}
}
context.SaveChanges();
}
This is what I did:
In the for loop for reading the file line by line
String TxnLOC = null;
IsTransactionLocation= false;
if (line.Contains("TRANSACTION LOC:"))
{
IsTransactionLocation = true;
if (IsTransactionLocation)
{
TxnLOC = line.Replace("TRANSACTION LOC:", String.Empty).Trim();
Console.WriteLine("The Transaction Location: ********");
Console.WriteLine(TxnLOC);
//Database insertion fot TTransaction Table
TTransaction txn = new TTransaction();
txn.TRN = txnNo;
txn.Amount = Convert.ToDecimal(Amount);
txn.TransactionLocation = TxnLOC;
context.TTransaction.Add(txn); //Adding to the database
context.SaveChanges();
IsTxnSection = false;//For 1 to many relationship
}
}
Related
I need to modify the UpgradeCode property of the Upgrade MSI table via C#.
This code works ok with other tables' properties, but throws an error when I'm trying to modify these.
using (var database = new Database(TEMPDATABASE, DatabaseOpenMode.Direct))
{
string upgradeCode = Guid.NewGuid().ToString("B").ToUpper();
database.Execute("Update `Upgrade` Set `Upgrade`.`UpgradeCode` = '{0}'", upgradeCode);
}
The error is:
Microsoft.Deployment.WindowsInstaller.InstallerException: 'Function failed during execution.'
I got curious and pillaged github.com - and it giveth the following: Full project - just download it as a whole.
The actual code was (some unicode line feed issues in the file on github.com, I have fixed them up here):
public static void UpdateUpgradeTable(this Database db, Guid upgradeCode)
{
using (View view = db.OpenView("SELECT * FROM `Upgrade`", new object[0]))
{
view.Execute();
using (Record record = view.Fetch())
{
record[1] = upgradeCode.ToString("B").ToUpperInvariant();
view.Replace(record);
}
db.Commit();
}
}
I took the above and made the following mock-up (very ugly, but it worked):
using (Database db = new Database(#"C:\Test.msi", DatabaseOpenMode.Direct))
{
using (View view = db.OpenView("SELECT * FROM `Upgrade`", new object[0]))
{
view.Execute();
using (Record record = view.Fetch())
{
record[1] = "{777888DD-1111-1111-1111-222222222222}";
record[2] = "";
record[3] = "4.0.1";
record[4] = "";
record[5] = "1";
record[6] = "";
record[7] = "WIX_UPGRADE_DETECTED";
view.Replace(record);
}
db.Commit();
using (Record record = view.Fetch())
{
record[1] = "{777888DD-1111-1111-1111-222222222222}";
record[2] = "";
record[3] = "";
record[4] = "4.0.1";
record[5] = "1";
record[6] = "";
record[7] = "WIX_DOWNGRADE_DETECTED";
view.Replace(record);
}
db.Commit();
}
}
The SDK doc says:
UPDATE queries only work on nonprimary key columns.
UpgradeCode is the primary key for the Upgrade table.
I am working with Entity Framework database first, and I have a table that stores historical values using baseline ids. We store parent/child links on this table using the baseline id. The following columns makeup this design:-
Id int (primary key - unique)
BaselineId int (not unique, but does uniquely identity revisions of the same item)
ParentBaselineId int nullable (refers to the baseline of the linked entity, no FK)
Latest bit (indicated that this is the most recent baseline in a series)
Example data for clarity
Id BaselineId ParentBaselineId Latest
1 1 NULL 0
2 1 NULL 1
3 2 1 0
4 2 1 1
This shows two items, each with two revisions. Baseline 1 is the parent of baseline 2.
My issue is that for the reasons listed below I lookup the next available baseline in C# and manually specify the BaselineId/ParentBaselineId to be saved. When two users trigger this method at the same time, they save the same Baseline ids, as the save does not complete before the second users looks up the next available baseline id.
The method can add many items at once that must be linked together by baseline ids
This must be a single SQL transaction so it can rollback completely on error
SQL trigger cannot be used to set the baselines because they are needed ahead of time to indicate the relationships
What measures can I take to ensure that the same baseline won't be used by two users running the method at the same time?
My C# looks something like this
using (var tx = new TransactionScope())
{
using (var context = new DbContext(connectionString))
{
int baseline = context.MyTable.Max(e => e.BaselineId);
context.MyTable.Add(new MyTable() {BaselineId = baseline + 1, Latest = true});
context.MyTable.Add(new MyTable() { BaselineId = baseline + 2, ParentBaselineId = baseline + 1, Latest = true });
context.SaveChanges();
}
tx.Complete();
}
Using #Steve Greene 's suggestion, I was able to use an SQL sequence. After creating a new sequence in my database and setting the start value to match my existing data, I updated my code to the following.
public long NextBaseline(DbContext context)
{
DataTable dt = new DataTable();
var conn = context.Database.Connection;
var connectionState = conn.State;
try
{
if (connectionState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT NEXT VALUE FOR MySequence;";
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
}
}
}
catch (Exception ex)
{
throw new HCSSException(ex.Message, ex);
}
finally
{
if (connectionState != ConnectionState.Open)
conn.Close();
}
return Convert.ToInt64(dt.AsEnumerable().First().ItemArray[0]);
}
public void Save()
{
using (var tx = new TransactionScope())
{
using (var context = new DbContext(connectionString))
{
var parent = new MyTable() { BaselineId = NextBaseline(context), Latest = true };
var child = new MyTable() { BaselineId = NextBaseline(context), ParentBaselineId = parent.BaselineId, Latest = true }
context.MyTable.Add(parent);
context.MyTable.Add(child);
context.SaveChanges();
}
tx.Complete();
}
}
I basically have two different databases that have different tables in them, but they both have "Table1" with the exact same structure.
var db = new ???;
if(mode == "PRODUCTION"){
db = new Database1("Connection string for Database1");
}
else{
db = new Database2("Connection string for Database2");
}
var result = db.Table1.Where(a=>a.Value==1).First();
How can I make the above work so I can assign "result" from two different databases (depending on "mode") without writing two different definitions for "result"?
Store the connection strings separately in your config file. You can then swap the connection strings at runtime to point the database object to the right database:
if(mode == "PRODUCTION")
{
db = new Database(ConfigurationManager.ConnectionStrings["production-key"]);
}
else
{
db = new Database(ConfigurationManager.ConnectionStrings["dev-key"]);
}
Justin's point is a good one, here is another -
Why do this at the db level?
Something like this would work
var table;
if(mode == "PRODUCTION"){
db = new Database1("Connection string for Database1");
table = db.table1;
}
else{
db = new Database1("Connection string for Database2");
table = db.table1
}
var result = table.Where(a=>a.Value==1).First();
If you don't have the same exact db then you would need to do something like this (you could also add an interface to db1 and db2 to return commonElements -- as you wish.
class commonElements {
/// some code
}
public commoneElements GetCommon(Database1 inDB1) {
/// some code
}
public commoneElements GetCommon(Database2 inDB2) {
/// some code
}
commonElements common;
if(mode == "PRODUCTION"){
db1 = new Database1("Connection string for Database1");
common = GetCommon(db1);
}
else{
db2 = new Database2("Connection string for Database2");
common = GetCommon(db2);
}
var result = common.Where(a=>a.Value==1).First();
I have been struggling with this problem for some time now and am not able to resolve this. Have read multiple posts and tried several different solutions but nothing has worked. Now I feel like I have come to a stop and really need help with this.
I am using EF 5+ with an DB first and edmx file. I have 3 different tables in my DB:
1. Settlement
2. Cost
3. Shift
Settlement has a collection of both Cost and Shift (with a link table) connected by Association in my edmx file.
I need to insert a new Settlement in my db with a reference to an already existing Cost and Shift collections.
Shifts and Costs included in my Settlement entity I am trying to insert contains all there related data and none of those are modified in any way (same as I retrieved from db).
Here in my method of inserting the entity into my db.
public bool CreateSettlement(Settlement settlement)
{
bool _success;
var _context = new EtaxiEnteties();// ObjectFactory.Get<IETaxiEntitiesContext>();
try
{
var _newSettlement = new Settlement
{
CreateDate = settlement.CreateDate,
Driver = settlement.Driver,
DriverID = settlement.DriverID,
Car = settlement.Car,
CarID = settlement.CarID,
DocPath = settlement.DocPath
};
foreach (var _shift in settlement.Shifts)
{
//var _sh = _context.Shifts.Find(_shift.ShiftID);
//_context.Entry(_sh).CurrentValues.SetValues(_shift);
_newSettlement.Shifts.Add(_shift);
}
foreach (var _cost in settlement.Costs)
{
////var _sh = _context.Costs.Find(_cost.CostID);
////_context.Entry(_sh).CurrentValues.SetValues(_cost);
_newSettlement.Costs.Add(_cost);
}
_context.Settlements.Add(_newSettlement);
_success = _context.SaveChanges() > 0;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return _success;
}
Any help on the issue would be MUCH appreciated.
Here is how I am adding the Cost and Shift to my collection:
I create a Settlement in page:
_settlement = new Settlement
{
CreateDate = DateTime.Now,
Driver = _driver,
DriverID = _driver.DriverID,
Car = _car,
CarID = _car.CarID,
DocPath = _path
};
then when I create a pdf file with selected rows from 2 separated grid views:
foreach (GridDataItem _selectedRow in gwShifts.MasterTableView.Items)
{
if (_selectedRow.Selected)
{
var _shift =
_diaryRepository.GetShiftByID((int) _selectedRow.GetDataKeyValue("ShiftID")).FirstOrDefault();
if (_shift != null)
{
_settlement.Shifts.Add(_shift);
_settlementData.Shifts.Add(_shift);
_settlementData.SplitPercentace = GetTemplateValue(_selectedRow, "lblSplit");
_settlementData.SettlementAmount = GetTemplateValue(_selectedRow, "lblSettlementAmount");
if (_settlementData.Shifts != null)
{
_tableShifts.AddCell(
new PdfPCell(
new Phrase(
_settlementData.Shifts.FirstOrDefault().ShiftDate.ToShortDateString(),
_bodyFont)) {Border = 0});
_tableShifts.AddCell(
new PdfPCell(
new Phrase(
string.Format("{0:c}", _settlementData.Shifts.FirstOrDefault().GrossAmount),
_bodyFont)) {Border = 0});
_tableShifts.AddCell(
new PdfPCell(
new Phrase(
string.Format("{0:c}", _settlementData.Shifts.FirstOrDefault().MoneyAmount),
_bodyFont)) {Border = 0});
_tableShifts.AddCell(new PdfPCell(new Phrase(_settlementData.SplitPercentace, _bodyFont))
{Border = 0});
_tableShifts.AddCell(
new PdfPCell(new Phrase(_settlementData.SettlementAmount, _boldTableFont))
{Border = 0});
_totalAmount.AddRange(new[]
{
Convert.ToInt32(
_settlementData.SettlementAmount.Replace(".", "").
Replace(",", "").Replace("kr", ""))
});
_settlementData.Shifts.Remove(_shift);
}
}
}
}
var _summaryCell =
new PdfPCell(new Phrase("Upphæð: " + string.Format("{0:c}", _totalAmount.Sum()), _boldTableFont))
{
Border = 0,
Colspan = 5,
HorizontalAlignment = Element.ALIGN_RIGHT,
Padding = 5,
BorderWidthTop = 1
};
_tableShifts.AddCell(_summaryCell);
if (_totalAmount.Count != 0)
_totalAmount.Clear();
}
there you see how I add the Shift to this Settlement entity:
var _shift =
_diaryRepository.GetShiftByID((int) _selectedRow.GetDataKeyValue("ShiftID")).FirstOrDefault();
if (_shift != null)
{
_settlement.Shifts.Add(_shift);
then I send this to the reporistory (see method above)
if(_driverRepository.CreateSettlement(_settlement))
{
SetMessage("Uppgjör hefur verið skapað og sent bílstjóra ef e-póstur er skráður á viðkomandi bílstjóra.", "Uppgjör skapað");
pnlSettlement.Visible = false;
pnlDocCreation.Visible = false;
pnlResult.Visible = false;
}
I also tried to simply add param settlement directly to the context but got similar error.
I think this has to do with how you're populating the Shifts and Costs collection. You're trying to add already created records (i.e. they already have their primary key values set) to be saved with the new Settlement entity, but I believe that Entity Framework isn't trying to create new ones that are linked to your new Settlement entity but rather save them to the table as is. In such a case you would indeed have a situation where multiple entities have the same primary key.
I would try the following (I'll show you using the Shifts loop only, but you should be able to apply it to the Costs loop as well):
foreach (var _shift in settlement.Shifts)
{
var newShift = new Shift { /*Copy all of the values from _shift here*/ };
_newSettlement.Shifts.Add(_shift);
context.Shifts.Add(newShift);
}
If that doesn't work I would suggest debugging Costs and Shifts to make sure that you don't have any duplicates in those collections.
If you don't want new Shifts & Costs then I can only assume you need to repoint the existing ones to the new Settlement
foreach (var shift in settlement.Shifts)
{
//either
shift.Settlement = newSettlement;
//or
shift.SettlementId = newSettlement.SettlementId;
//depending on your object model
}
I've just realised that I have misunderstood the question. There are 2 additional tables not shown in the diagram (Costs & Shifts). The problem is trying to create SettlementCost and SettlementShift entities that connect Settlement to Costs\Shifts.
OK, came up with a "ugly" solution on this..but it is resolved.
Changed the Model to be one(Settlement) -> many(Shift or Cost) relationship.
I create a new Settlement and save this one to the DB.
Retrieve each Shift and Cost from the DB update SettlementID on each and save these to the DB.
try
{
var _newSettlement = new Settlement
{
CreateDate = settlement.CreateDate,
DriverID = settlement.DriverID,
CarID = settlement.CarID,
DocPath = settlement.DocPath
};
Add(_newSettlement);
_success = SaveWithSuccess() > 0;
var _settlement = GetAll().FirstOrDefault(x => x.SettlementID == _newSettlement.SettlementID);
if (_success)
{
foreach (var _shift in settlement.Shifts)
{
var _sh = _diaryRepository.GetShiftByID(_shift.ShiftID).FirstOrDefault();
_sh.SettlementID = _settlement.SettlementID;
_diaryRepository.UpdateShift(_sh);
}
foreach (var _cost in settlement.Costs)
{
var _ch = _costRepository.GetCostByID(_cost.CostID);
_ch.SettlementID = _settlement.SettlementID;
_costRepository.UpdateCost(_ch);
}
}
}
not a pretty one, but it resolves the problem.
I am not concerned about the DB request load..it will not be that high in this case.
I would think there is a nicer solution to this but I was not able to find it at this time.
Thanks for all your efforts to help :)
I have a ProductLevel table in an SQL database. It contains the products for a store. I want to copy these records into a ProductLevelDaily table at the time the user logs onto the hand held device in the morning.
As they scan items the bool goes from false to true so at anytime they can see what items are left to scan/check.
From the mobile device I pass the siteID and date to the server:
int userID = int.Parse(oWebRequest.requestData[5]); and a few other things
IEnumerable<dProductLevelDaily> plditems
= DSOLDAL.CheckProductDailyLevelbySiteCount(siteID, currentDate);
This checks if there are any records already moved into this table for this store. Being the first time this table should be empty or contain no records for this store on this date.
if (plditems.Count() == 0) // is 0
{
IEnumerable<dProductLevel> ppitems = DSOLDAL.GetProductsbySite(siteID);
// this gets the products for this store
if (ppitems.Count() > 0)
{
dProduct pi = new dProduct();
foreach (dProductLevel pl in ppitems)
{
// get the product
pi = DSOLDAL.getProductByID(pl.productID, companyID);
dProductLevelDaily pld = new dProductLevelDaily();
pld.guid = Guid.NewGuid();
pld.siteID = siteID;
pld.statusID = 1;
pld.companyID = companyID;
pld.counted = false;
pld.createDate = DateTime.Now;
pld.createUser = userID;
pld.productID = pl.productID;
pld.name = "1000"; // pi.name;
pld.description = "desc"; // pi.description;
DSOLDAL.insertProductLevelDailyBySite(pld);
}
}
}
On the PDA the weberequest response returns NULL
I can't see what the problem is and why it wont work.
The insert is in DSOLDAL:
public static void insertProductLevelDailyBySite(dProductLevelDaily pld)
{
dSOLDataContext dc = new dSOLDataContext();
try
{
dc.dProductLevelDailies.InsertOnSubmit(pld);
// dProductLevelDailies.Attach(pld, true);
dc.SubmitChanges();
}
catch (Exception exc)
{
throw new Exception(getExceptionMessage(exc.Message));
}
finally
{
dc = null;
}
}
This code works until I put the foreach loop inside with the insert
IEnumerable<dProductLevelDaily> plditems
= DSOLDAL.CheckProductDailyLevelbySiteCount(siteID, s);
if (plditems.Count() == 0) // plditems.Count() < 0)
{
IEnumerable<dProductLevel> ppitems = DSOLDAL.GetProductsbySite(siteID);
if (ppitems.Count() > 0)
{
oWebResponse.count = ppitems.Count().ToString();
oWebResponse.status = "OK";
}
else
{
oWebResponse.count = ppitems.Count().ToString();
oWebResponse.status = "OK";
}
}
else
{
oWebResponse.count = "2"; // plditems.Count().ToString();
oWebResponse.status = "OK";
}
These kind of bulk operations aren't very well matched to what Linq-to-SQL does.
In my opinion, I'd do this using a stored procedure, which you could include in your Linq-to-SQL DataContext and call from there.
That would also leave the data on the server and just copy it from one table to the other, instead of pulling down all data to your client and re-uploading it to the server.
Linq-to-SQL is a great tool - for manipulating single objects or small sets. It's less well suited for bulk operations.