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;
Related
I am developing a spreadsheet uploader tool which creates/updates contacts, which will be added as a new option to my website.
The spreadsheet has the following columns:
Full Name
Job Title
Salutation
Qualifications
Company Name
Address Line 1
Address Line 2
Address Line 3
The database table structure is as below:
Contact(contact_id INT PK IDENTITY(1,1), fullname VARCHAR(30), jobtitle VARCHAR(100), salutation VARCHAR(100), qualifications VARCHAR(100), companyname VARCHAR(100) , address1 VARCHAR(100), address2 VARCHAR(100), address3 VARCHAR(100))
The rules are:
1. The Full name must contain at least one space (leading and/or trailing spaces will be trimmed).
2. Total length of the full name must not exceed 30 characters (including any space(s)).
3. 'Full Name' is the key field to identify an existing contact in the system. As such, raise a validation error if this field is
blank.
4. If a match is found on the 'Full Name', then the other fields of the contact will be updated with the values populated in the
spreadsheet.
5. If a match is not found on the key field, then create a new contact with the details.
6. When creating/updating a contact a value must be populated in at least one other column (in addition to the 'Full Name'), otherwise
raise a validation error.
The process:
There are two phases called 'Validation Phase' and 'Actual Upload' phase.
- When the spreadsheet is uploaded the spreadsheet has to be validated as per the rules above and display the validation/status messages (on screen):
For example:
Row 1 is the header row so it will not be validated.
Row 2: Error - Full Name cannot be empty
Row 3: OK - A contact will be created
Row 4: OK - Contact will be updated
Row 5: Error - Full Name must contain at least one space
Row 6: Error - At least one other column must be populated in addition to the 'Full Name'
The user will have two options here:
Cancel - Then the upload will not be proceeded any further (so the user will have a choice to correct the rows as per validation messages then re-upload it).
Continue - Then the upload will move to 'Actual Upload' phase and the contacts will either be created or updated (if there are no validation errors as per the rules above).
Also, the validation/status message (similar to the messages in validation phase) should be displayed on screen after the successful upload.
I have managed to work out everything I had illustrated above, but I had to re-validate each row in 'Actual Upload' phase (i.e. I'm doing the same checks twice).
My question is, is there a way to preserve the results from the validation phase so I don't have to re-validate each record in the second phase?
I'm develioping this using the NativeExcel libraries on .NET Framework (Version 4.0.30319.34209) using VB.NET/ASP.NET (and No VISUAL STUDIO).
Please note all the code will be written in the code-behind page using VB.NET (I have no choice here, sorry).
Any suggestions/help will be much appreciated.
Save the validation status messages as a List(Of String) and then make that a session variable so that you can use it as a prompt during the upload phase.
To read the Excel file:
right-click References>COM>Office xx.x Object Application
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\user\Excelfile.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs = exlWb.Sheets["Sheet1"];
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row - 1; j++)
{
for (int k = 1; k <= col - 1; k++)
{
cellValue[j, k] = exlWs.Cells[j, k + 1].ToString();
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
I have the following code in which I am passing a local variable to a linq query for a specific record, after that record I want to check whether there is a record according to that id or not.
First it gives me the error "Cannot implicitly convert type int to bool"
Second if I want to count the rows in this query or want to check whether there is a row or not, how will I do that, here is my code:
int J_Job_ID = Convert.ToInt32(Request.QueryString["J_Job_ID"]);
//Check If this ID exists in the database
var query = from m in JE.J_Posted_Jobs_Tbl
where m.J_Job_ID = Convert.ToInt32(J_Job_ID)
select m;
it should be
where m.J_Job_ID == Convert.ToInt32(J_Job_ID)
as for count
query.Count()
In SQLite I can run the following query to get a list of columns in a table:
PRAGMA table_info(myTable)
This gives me the columns but no information about what the primary keys may be. Additionally, I can run the following two queries for finding indexes and foreign keys:
PRAGMA index_list(myTable)
PRAGMA foreign_key_list(myTable)
But I cannot seem to figure out how to view the primary keys. Does anyone know how I can go about doing this?
Note: I also know that I can do:
select * from sqlite_master where type = 'table' and name ='myTable';
And it will give the the create table statement which shows the primary keys. But I am looking for a way to do this without parsing the create statement.
The table_info DOES give you a column named pk (last one) indicating if it is a primary key (if so the index of it in the key) or not (zero).
To clarify, from the documentation:
The "pk" column in the result set is zero for columns that are not
part of the primary key, and is the index of the column in the primary
key for columns that are part of the primary key.
Hopefully this helps someone:
After some research and pain the command that worked for me to find the primary key column name was:
SELECT l.name FROM pragma_table_info("Table_Name") as l WHERE l.pk = 1;
For the ones trying to retrieve a pk name in android, and while using the ROOM library.
#Oogway101's answer was throwing an error: "no such column [your_table_name] ... etc.. etc...
my way of query submition was:
String pkSearch = "SELECT l.name FROM pragma_table_info(" + tableName + ") as l WHERE l.pk = 1;";
database.query(new SimpleSQLiteQuery(pkSearch)
I tried using the (") quotations and still error.
String pkSearch = "SELECT l.name FROM pragma_table_info(\"" + tableName + "\") as l WHERE l.pk = 1;";
So my solution was this:
String pragmaInfo = "PRAGMA table_info(" + tableName + ");";
Cursor c = database.query(new SimpleSQLiteQuery(pragmaInfo));
String id = null;
c.moveToFirst();
do {
if (c.getInt(5) == 1) {
id = c.getString(1);
}
} while (c.moveToNext() && id == null);
Log.println(Log.ASSERT, TAG, "AbstractDao: pk is: " + id);
The explanation is that:
A) PRAGMA table_info returns a cursor with various indices, the response is atleast of length 6... didnt check more...
B) index 1 has the column name.
C) index 5 has the "pk" value, either 0 if it is not a primary key, or 1 if its a pk.
You can define more than one pk so this will not bring an accurate result if your table has more than one (IMHO more than one is bad design and balloons the complexity of the database beyond human comprehension).
So how will this fit into the #Dao? (you may ask...)
When making the Dao "abstract" you have access to a default constructor which has the database in it:
from the docummentation:
An abstract #Dao class can optionally have a constructor that takes a Database as its only parameter.
this is the constructor that will grant you access to the query.
There is a catch though...
You may use the Dao during a database creation with the .addCallback() method:
instance = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase2.class, "database")
.addCallback(
//You may use the Daos here.
)
.build();
If you run a query in the constructor of the Dao, the database will enter a feedback loop of infinite instantiation.
This means that the query MUST be used LAZILY (just at the moment the user needs something), and because the value will never change, it can be stored. and never re-queried.
I am building a forum and I have two tables:
Threads
-------
ThreadID
UsersID
Date
ThreadTitle
ThreadParagraph
ThreadClosed
Topics
-----
TopicsID
Theme
Topics
Date
The ThreadID is connected to the users table with a primary key:
Topics.TopicsID(PK)==Threads.TopicID(FK)
First i insert into the Topics table and then to the Threads table. My goal is to obtain the ID of Topics.TopicID with Identity_Scope() and pass it to the second insert which is Threads.TopicID
Here is what i have done, but i am not sure if it is correct:
StringBuilder insertCommand = new StringBuilder();
insertCommand.Append("DECLARE #TopicsID int");
insertCommand.Append("INSERT INTO Topics(Theme,Topics,Date)");
insertCommand.Append("VALUES('#topic,#subTopic,GETDATE()')");
insertCommand.Append("SET #TopicsID = SCOPE_IDENTITY()");
insertCommand.Append("INSERT INTO Threads(UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,ThreadClosed)");
insertCommand.Append("VALUES('#uniqueIdentifier,#TopicsID,GETDATE(),#questionTitle,#questionParagraph,0')");
I have got all the otehr parameters obtained from the controls the users presses or feeds information into, so dont worry about them. All i am worried about is passing the same TopicID from the Topic table to Thread table (Column name: TopicID).
Both Magnus & Damien_The_Unbeliever are right - you have few syntax errors (or typos). Correct insert command should be something like
insertCommand.Append(#"
DECLARE #TopicSID int
INSERT INTO Topics(Theme,Topics,Date)
VALUES(#topic,#subTopic,GETDATE())
SET #TopicSID = SCOPE_IDENTITY()
INSERT INTO Threads(UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,ThreadClosed)
VALUES(#uniqueIdentifier,#TopicSID ,GETDATE(),#questionTitle,#questionParagraph,0)
");
I have a table called Quiz that have these fields
id As Int
created As DateTime
header As Sring
body As String
fk_parent As int
url As String
All the items without parent key would be the question, and ones that have the parent key would be the answer. I am having the problem to get all the latest active questions (based both on questions created time and and answer created time).
I am struggling to write a Linq query that can do the above task.
Here's a start:
IQueryable<int> keys =
from x in dc.Quiz
let masterID = ParentId.HasValue ? ParentId.Value : Id
group x by masterID into g
order g by g.Max(x => x.created) descending
select g.Key
List<Quiz> = dc.Quiz.Where(x => keys.Take(20).Contains(x.Id)).ToList();
This assumes answers aren't parents of answers... If they can - you have an arbitrary depth tree walk on your hands, which is a wrong shaped nail for Linq and for SQL.
You could try joining the table on itself in LINQ and creating a new object that holds the Questions and answers:
var QandA = from q in tbl
join a in tbl on q.id equals a.fk_parent
select new {
QHeader = q.header,
QBody = q.body,
QUrl = q.url,
AHeader = a.header,
ABody = a.body,
AUrl = a.url
};
I think this is how your table is setup, but I might have the join wrong.