The cosmos DB table entry manages a default Timestamp property for each table operation. While I am trying to query last updated entries based on the same time stamp field the result is not behaving as expected. The TableQuery looks like below:
TableQuery.GenerateFilterConditionForDate("Timestamp",
QueryComparisons.GreaterThanOrEqual,
timestamp)
Where timestamp is a DateTimeOffset object. I am getting 0 rows retrieved even with rows existing in the table with the Timestamp column holding a higher value. What is missing here?
Data in my table.
Query params.
Result.
var query = TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, DateTimeOffset.Now.AddDays(-10).Date);
var exQuery = new TableQuery<CustomerEntity>().Where(query);
var results0 = sourcetable.ExecuteQuery(exQuery).ToList();
//var results1 = sourcetable.ExecuteQuery(exQuery).Select(ent => (CustomerEntity)ent).ToList();
I am developing a complaint management in which I have to generate unique serial number for each complaint like 00001/20 {Serial number/year}.
I am using repository pattern and i am generating this complaint number using the following code snippet but problem is if two user try to lodge a complaint at the same time it will generate a same complaint no and that thrown an error as I am keeping a serial number in a separate table which is also mentioned below for reference. Let me know the best way to achieve this
int serialNo = repository.serialNo.Find(c => c.Year == DateTime.Now.Year).FirstOrDefault().TicketCounter;
string complaintNo = string.Format("{0}", serialNo.ToString().PadLeft(5, '0'));
model.Id = repository.complaintRepo.GetMaxPK(c => c.Id);
I am using repository pattern.
I guess, one of the solutions is to setup the table so that it generates required ID automatically on every new row. This ensures that the ID is always unique.
CREATE SEQUENCE MySequence
AS int
START WITH 1
INCREMENT BY 1;
CREATE TABLE Complaint
(
Id char(8) CONSTRAINT [DF_Complaint_ID]
DEFAULT FORMAT((NEXT VALUE FOR MySequence), '0000#')
+'/'+RIGHT(YEAR(GETDATE()),2),
Foo int,
Bar int,
CONSTRAINT [PK_MyTable] PRIMARY KEY (Id)
);
Demo: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=18a5d0fec80a3985e30cef687d3c8e49
So there will be no need to assign the id manually and your code could look like
var c = repository.Insert(new model
{
Foo = ...
Bar = ...,
...
});
repository.Save();
// you can get id after inserting data in the database
string id = c.Id;
I have to import a CSV file into a SQL Server table.
The CSV has 8 columns and 2 of them are date and time values.
In my SQL table I have a column which store the difference between 2 the columns of CSV file.
I am unable to check if the cell is empty or not.
My code follows:
protected void btnImport_Click(object sender, EventArgs e)
{
string csvPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(csvPath);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[8] { new DataColumn("basid", typeof(string)),
new DataColumn("EmployeeName", typeof(string)),
new DataColumn("Designation",typeof(string)),
new DataColumn("OfficeLocation",typeof(string)),
new DataColumn("Division",typeof(string)),
new DataColumn("Intime",typeof(DateTime)),
new DataColumn("Outtime",typeof(DateTime)),
new DataColumn("timedifference",typeof(DateTime))
});
string csvData = File.ReadAllText(csvPath);
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(','))
{
if (i == 7)
{
dt.Rows[dt.Rows.Count - 1][i] = ((DateTime)(dt.Rows[dt.Rows.Count - 1][i - 1]) - (DateTime)(dt.Rows[dt.Rows.Count - 1][i - 2]));
}
else {
dt.Rows[dt.Rows.Count - 1][i] = cell;
}
i++;
}
}
}
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name.
sqlBulkCopy.DestinationTableName = "dbo.basids";
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
Understanding
Importing from a CSV file (or any other file that does not conform to the Relational Model), is not a problem. You need to understand that the file is not, and never will be, a Relational table. At best it is a file with good field types, at worst one with hopeless field types.
You may create a raw table in the database, for convenience, that is, in order to use SQL on it
At best, the fields in the file have reliable datatypes, thus the raw table may have SQL Datatypes.
At worst, the Datatypes in the raw table are all CHAR(x).
In any case, the columns in the raw table must match the import file exactly.
Usually, such raw tables do not have an Index, they are just Heaps.
Your app code will not query the raw tables, they are manipulated on by the Import code, only.
DataTable dt is such a raw table.
The Relational table (or tables) that are in the Relational database are quite a different animal. They are properly designed, Normalised, and compliant with the Relational Model. Relational tables have Primary Keys that are "made up from the data", and may have additional Unique Keys. The datatypes are "tight", and disallow illegal values.
Your app code will query the Relational tables, only.
Hence it is quite normal, that one CSV file (or import file or raw table) translates to more than one Relational table.
Therefore Import is always a two-step process:
First, just import the CSV file into the raw table, which has been suitably set up for that act.
You have not asked the question, but if I were loading this CSV file into a raw table, I wouldn't bother with all that middle-tier code, I would use the MS SQL bcp utility.
Second, INSERT-SELECT from the raw table into the Relational table(s).
In this step, the SELECT will transform the raw fields into proper Datatypes, and perform any checking that is required.
In order to ensure that the FK Constraints do not fail, the Reference tables must be populated before the data tables. For populating the Reference tables (not the raw file), eg. Operator, the code may be:
INSERT Operator
SELECT ...
FROM RawTable.Operator
WHERE RawTable.Operator NOT IN (
SELECT Operator
FROM Operator
)
ETL stands for Extract; Transform; Load. It is never Load only.
Problem
You have a raw table, only. And you think it is a Relational table. It is not.
You have no Relational tables.
Third, ...
I am unable to check if the cell is empty or not.
Yes, you can. After importing the CSV file into a raw table (possibly DataTable dt, or BAS_Raw below), which is step [1], in step [2], use ordinary SQL checks and transformations.
SELECT
...
[Hours] = CASE OutTime
WHEN NULL THEN CONVERT( TIME, "00:00" )
ELSE CONVERT( TIME, OutTime - InTime )
END
...
FROM BAS_Raw
Relational Database
The solution is, of course, to:
implement a Relational database, that has both:
Relational tables for all app queries, and
the raw table for the importation only
understand the two-step process that is required for importation of CSV files, including any checking and data transformation, as required.
Note • Content
I have no idea what basid is, therefore I have not modelled it. If you declare what it is, I will model it.
the time difference or hours worked does not need to be stored, because it is easily derived (OutTime minus InTime).
Note • Notation
All my data models are rendered in IDEF1X, the Standard for modelling Relational databases since 1993
My IDEF1X Introduction is essential reading for beginners or novices, wrt a Relational database.
i have a datatable which contains "InvalidCodes".
Before uploading the data to database(data is still in datatable), i want to perform linq on the datatable to remove Invalid entries and move them in another datatable
datatable allEntries ( entries yet to be uploaded in database)
datatable InvalidCodes(single column datatable - retrieved from database)
datatable invalidEntries
right now "allEnties" contains valid entries and invalid entries. the linq query on "allEntries" should move the nonexistend code entries to invalidEntries datatable.
plz help me perform this.
below is the query i formed but its not valid
string query = "select [CityCode] from [StateCity] ";
DataTable citylist = getDataTableFromSelect(query);
var result = from myrow in inputDt.AsEnumerable()
where !myrow.Field<string>("CityCode").Contains(from myrow2 in citylist.AsEnumerable() select myrow2.Field<string>("CityCode") )
select myrow;
I'd make a HashSet for the invalid city codes - this will allow the code to quickly/efficiently identify which of the codes are in the invalid set.
e.g. something like:
var invalidCityCodes = from myrow2 in citylist.AsEnumerable()
select myrow2.Field<string>("CityCode");
var invalidCityCodeHashSet = new HashSet<string>(invalideCityCodes);
var result = from myrow in inputDt.AsEnumerable()
where !invalidCityCodeHashSet.Contains(myrow.Field<string>("CityCode"))
select myrow;
You can also take both the results in 2 Different Lists and then you can
use
List1 = List1.RemoveAll(Item=>List2.Contains(Item))
This works fine with me and will work for you also.
How to insert and retrive multiple asp.net checkboxes values to MSSQl database as comma seperaed string 1,2,3,4,5 using vb.net ?
and retrieve the inserted checkbox chekched in disabled form ..using vb.net
example of this is :
http://www.redbus.in/Booking/SeatSelection.aspx?rt=4017230&doj=31-Dec-2010&dep=04:55%20PM&showSpInst=false
I want this type of whole layout in vb.net ... means if user registered selected seats then then next the same page load for todays date the selected seats will be disabled ...
pleas provide me the code snippet for that // insert and retrieve funda... in checkbox
Try with such a loop
string str = "";
for (int i = 0; i <= 29; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
string b = CheckBoxList1.Items[i].Value;
str += b + " , ";
}
}
than make an insert statement and you are putting all the checkbox values into a column.
than just call select statement call the column
You are doing a very bad thing storing lists of values in a single MSSQL column. I know it may be convenient now, but it is always eventually bad news. Why not store booked seats in their own table, one seat per row? When you store a list of values in a column, you restrict access to the information stored in that column to only the code that can split the list. It isn't available to database queries or to other code as a list, merely as a string. You will end up replicating the code to split this string to other places that need the list data.