How Create Sequence number in Controller action? - asp.net-mvc

I am working on a project which is an E-health patient Gateway.
I want to generate a number (int type) against a submit form from View to Controller (When phlebotomist receives the blood sample he will check the box and click on submit button). This number is the patient's blood sample number that will be generated in my controller and will be saved in the database. I am using the logic below to create the number but it always gives me zero.
Kindly let me know how I can create numbers one by one in sequence and store in database?
public ActionResult AddSampleTest(int Pid, int Tid, int Stid, string Comment ,string testDate,int DotorID)
{
int sampleNumber=1;
Random rnd = new Random();
int[] sample = new int[50000];
rnd.Next();
for (int ctr = 1; ctr <= sample.Length; ctr++)
{
sampleNumber=sample[ctr + 1];
}
string sampleno = sampleNumber.ToString();
DateTime TestDate = Convert.ToDateTime(testDate);
int Recomended_Test_DoctorID = DotorID;
// Update the Sample Status
PatientTest objpatientTest = db.PatientTests.Where(x => x.PatientID == Pid && x.Testid == Tid && x.SubTestId == Stid && x.Date==TestDate &&x.DoctorId== Recomended_Test_DoctorID).FirstOrDefault();
objpatientTest.SampleStatus = "Sample Received";
objpatientTest.SampleNumber = sampleno;
db.SaveChanges();
var name = User.Identity.Name;
int Lid = db.LabAttendantRecords.Where(x => x.Name == name).Select(x => x.User_id).FirstOrDefault();
LabTestSample obj = new LabTestSample();
obj.labtestid = Tid;
obj.PatientId = Pid;
obj.subtestid = Stid;
obj.labAtendid = Lid;
obj.date = DateTime.Now.Date;
obj.sampleReceived = true;
obj.Comment = sampleno;
db.LabTestSamples.Add(obj);
db.SaveChanges();
return RedirectToAction("TestSampleNumber", "LabAttendantDashboard", new { sampleno});
// Use This for add Result
return RedirectToAction("SubTest", "LabAttendantDashboard", new { Pid, Tid, Stid });
}

sampleNumber is always 0 because each element in sample is 0.
If you want it to be a random number you need to do something like :
Random rnd = new Random();
int sampleNumber = rnd.Next();
string sampleno = sampleNumber.ToString();
If you need to be sure that the sample number is unique, you should use a Guid :
string sampleno = Guid.NewGuid().ToString();

Related

Joining tables in queries google sheets

Basically I have two google sheets that look something like this:
a table where people can put in their email and select what kind of foo they are using
email
foo
example#email.com
This Foo
and then another table with information about the foo
foo name
foo type
foo boolean1
foo boolean2
This Foo
String
True
True
That Foo
Number
False
True
Other Foo
String
False
False
In a Separate Sheet I'd like to have a dashboard-like view of things wherein I would have counts of various things like number of people, how many of each type of Foo, etc
Where I'm having trouble is figuring out how to pull things like "Number of people who have selected String foos" and such
like, basically i want the google-query equivalent to (in sql)
SELECT COUNT(p.*) FROM people p JOIN info i on p.foo = i.foo_name GROUP BY i.foo_type WHERE i.foo_type = 'String'
What I would be looking for is a table that looks like this:
Data
Count
Active Roster
4
String
3
Number
1
I have also seen many solutions that have complicated formulas using VLOOKUP, INDEX, MATCH, etc.
I decided to write a user function to combine tables, or as I refer to it, de-normalize the database. I wrote the function DENORMALIZE() to support INNER, LEFT, RIGHT and FULL joins. By nesting function calls one can join unlimited tables in theory.
DENORMALIZE(range1, range2, primaryKey, foreignKey, [joinType])
Parameters:
range1, the main table as a named range, a1Notation or an array
range2, the related table as a named range, a1Notation or an array
primaryKey, the unique identifier for the main table, columns start with "1"
foreignKey, the key in the related table to join to the main table, columns start with "1"
joinType, type of join, "Inner", "Left", "Right", "Full", optional and defaults to "Inner", case insensitive
Returns: results as a two dimensional array
Result Set Example:
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio' AND Col8=2", FALSE)
EmpID
LastName
FirstName
OrderID
CustomerID
EmpID
OrderDate
ShipperID
1
Davolio
Nancy
10285
63
1
8/20/1996
2
1
Davolio
Nancy
10292
81
1
8/28/1996
2
1
Davolio
Nancy
10304
80
1
9/12/1996
2
Other Examples:
=denormalize("Employees","Orders",1,3)
=denormalize("Employees","Orders",1,3,"full")
=QUERY(denormalize("Employees","Orders",1,3,"left"), "SELECT * ", FALSE)
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio'", FALSE)
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio' AND Col8=2", FALSE)
=denormalize("Orders","OrderDetails",1,2)
// multiple joins
=denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3)
=QUERY(denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3), "SELECT *", FALSE)
=denormalize(denormalize("Employees","Orders",1,3),"OrderDetails",1,2)
=QUERY(denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3), "SELECT *", FALSE)
=QUERY(denormalize(denormalize("Employees","Orders",1,3),"OrderDetails",4,2), "SELECT *", FALSE)
function denormalize(range1, range2, primaryKey, foreignKey, joinType) {
var i = 0;
var j = 0;
var index = -1;
var lFound = false;
var aDenorm = [];
var hashtable = [];
var aRange1 = "";
var aRange2 = "";
joinType = DefaultTo(joinType, "INNER").toUpperCase();
// the 6 lines below are used for debugging
//range1 = "Employees";
//range1 = "Employees!A2:C12";
//range2 = "Orders";
//primaryKey = 1;
//foreignKey = 3;
//joinType = "LEFT";
// Sheets starts numbering columns starting with "1", arrays are zero-based
primaryKey -= 1;
foreignKey -= 1;
// check if range is not an array
if (typeof range1 !== 'object') {
// Determine if range is a1Notation and load data into an array
if (range1.indexOf(":") !== -1) {
aRange1 = ss.getRange(range1).getValues();
} else {
aRange1 = ss.getRangeByName(range1).getValues();
}
} else {
aRange1 = range1;
}
if (typeof range2 !== 'object') {
if (range2.indexOf(":") !== -1) {
aRange2 = ss.getRange(range2).getValues();
} else {
aRange2 = ss.getRangeByName(range2).getValues();
}
} else {
aRange2 = range2;
}
// make similar structured temp arrays with NULL elements
var tArray1 = MakeArray(aRange1[0].length);
var tArray2 = MakeArray(aRange2[0].length);
var lenRange1 = aRange1.length;
var lenRange2 = aRange2.length;
hashtable = getHT(aRange1, lenRange1, primaryKey);
for(i = 0; i < lenRange2; i++) {
index = hashtable.indexOf(aRange2[i][foreignKey]);
if (index !== -1) {
aDenorm.push(aRange1[index].concat(aRange2[i]));
}
}
// add left and full no matches
if (joinType == "LEFT" || joinType == "FULL") {
for(i = 0; i < lenRange1; i++) {
//index = aDenorm.indexOf(aRange1[i][primaryKey]);
index = aScan(aDenorm, aRange1[i][primaryKey], primaryKey)
if (index == -1) {
aDenorm.push(aRange1[i].concat(tArray2));
}
}
}
// add right and full no matches
if (joinType == "RIGHT" || joinType == "FULL") {
for(i = 0; i < lenRange2; i++) {
index = aScan(aDenorm, aRange2[i][foreignKey], primaryKey)
if (index == -1) {
aDenorm.push(tArray1.concat(aRange2[i]));
}
}
}
return aDenorm;
}
function getHT(aRange, lenRange, key){
var aHashtable = [];
var i = 0;
for (i=0; i < lenRange; i++ ) {
//aHashtable.push([aRange[i][key], i]);
aHashtable.push(aRange[i][key]);
}
return aHashtable;
}
function MakeArray(length) {
var i = 0;
var retArray = [];
for (i=0; i < length; i++) {
retArray.push("");
}
return retArray;
}
function DefaultTo(valueToCheck, valueToDefault) {
return typeof valueToCheck === "undefined" ? valueToDefault : valueToCheck;
}
// Search a multi-dimensional array for a value
function aScan(aValues, searchStr, searchCol) {
var retval = -1;
var i = 0;
var aLen = aValues.length;
for (i = 0; i < aLen; i++) {
if (aValues[i][searchCol] == searchStr) {
retval = i;
break;
}
}
return retval;
}
You can make a copy of the google sheet with data and examples here:
https://docs.google.com/spreadsheets/d/1vziuF8gQcsOxTLEtlcU2cgTAYL1eIaaMTAoIrAS7mnE/edit?usp=sharing

Can not add a list in document object using iTextSharp

public ActionResult PartTimeFacultyCourseLoadReport()
{
var teacherStatistics = (from t in db.Teachers
join c in db.Courses
on t.Id equals c.TeacherId into cGroup
where t.Status == "Part Time"
orderby t.Designation descending
select new
{
TeacherInfo = t,
CourseInfo = from cg in cGroup
orderby cg.Code ascending
select cg
}).ToList();
List<TeacherStatistics> teacherStatisticses = new List<TeacherStatistics>();
int count = 0;
foreach (var teacherStatistic in teacherStatistics)
{
TeacherStatistics aTeacherStatistics = new TeacherStatistics();
aTeacherStatistics.Name = teacherStatistic.TeacherInfo.Name;
aTeacherStatistics.Designation = teacherStatistic.TeacherInfo.Designation;
aTeacherStatistics.NumberOfCourse = teacherStatistic.TeacherInfo.NumberOfCourse;
count = 0;
foreach (var courseInfo in teacherStatistic.CourseInfo)
{
if (count != 0)
{
aTeacherStatistics.Courses += ", ";
}
aTeacherStatistics.Courses += courseInfo.Code;
aTeacherStatistics.Courses += "(";
aTeacherStatistics.Courses += courseInfo.Section;
aTeacherStatistics.Courses += ")";
count++;
}
teacherStatisticses.Add(aTeacherStatistics);
}
var document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
document.Open();
var data = teacherStatisticses.ToList();
document.Add(data);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=PartTimeFaculty.pdf");
Response.BinaryWrite(output.ToArray());
document.Close();
return View(teacherStatisticses);
}
I want to pass a list named 'teacherStatisticses' through document object for making a PDF. My code doesn't work. It showed me following Error -
Argument 1: cannot convert from 'System.Collections.Generic.List' to 'iTextSharp.text.IElement'
I assume that you are using some version of itextpdf for the PDF generation.
The error is in the line:
document.Add(data);
There is no way to add plain .NET objects into the PDF document. I can not predict the structure of PDF which you`d like to achieve, but the code mentioned above could be written as:
foreach(var teacher in teacherStatistics)
{
var paragraph = new Paragraph(teacher.ToString()); // instead of teacher.ToString() should be some code which translates teacherStatistics projection to the string representation
document.Add(paragraph);
}
//not tested
A lot of useful samples could be found at
http://developers.itextpdf.com/examples
Basic tutorial for the itextpdf:
http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/chapter-1-introducing-basic-building-blocks

How to copy one spreadsheet's cell to another spreadsheet

I tried coding like spreadsheet API batch copy https://developers.google.com/google-apps/spreadsheets/#updating_multiple_cells_with_a_batch_request, The sample is base on same spreadsheet, I added a target cell but always get same error
com.google.gdata.client.batch.BatchInterruptedException: Batch Interrupted (some operations might have succeeded) : a response has already been sent for batch operation update id='R1C1'
My code like this
SpreadsheetService spreadsheetService = getSpreadsheetService(currentEmail);
WorksheetFeed feed = spreadsheetService.getFeed(getWorksheetFeedURL(sourceId), WorksheetFeed.class);
SpreadsheetEntry targetFeed = spreadsheetService.getEntry(getSpreadsheetFeedURL(targetId), SpreadsheetEntry.class);
SpreadsheetEntry sourceFeed = spreadsheetService.getEntry(getSpreadsheetFeedURL(sourceId), SpreadsheetEntry.class);
for(WorksheetEntry entry:feed.getEntries()){
WorksheetEntry targetWorksheet = spreadsheetService.insert(targetFeed.getWorksheetFeedUrl(), entry);
FeedURLFactory urlFactory = FeedURLFactory.getDefault();
URL cellFeedUrl = urlFactory.getCellFeedUrl(sourceFeed.getKey(), "od6", "private", "full");
URL targetFeedUrl = urlFactory.getCellFeedUrl(targetFeed.getKey(), "od6", "private", "full");
CellFeed cellFeed = spreadsheetService.getFeed(targetFeedUrl, CellFeed.class);
List<CellAddress> cellAddrs = new ArrayList<CellAddress>();
for (int row = 1; row <= entry.getRowCount(); ++row) {
for (int col = 1; col <= entry.getColCount(); ++col) {
cellAddrs.add(new CellAddress(row, col));
}
}
Map<String, CellEntry> cellEntries = getCellEntryMap(spreadsheetService, cellFeedUrl, cellAddrs);
CellFeed batchRequest = new CellFeed();
for (CellAddress cellAddr : cellAddrs) {
URL entryUrl = new URL(targetFeedUrl.toString() + "/" + cellAddr.idString);
CellEntry batchEntry = new CellEntry(cellAddr.row, cellAddr.col, cellAddr.idString);
String inputValue = cellEntries.get(cellAddr.idString).getCell().getInputValue();
batchEntry.changeInputValueLocal(inputValue);
batchEntry.setId(String.format("%s/%s", targetFeedUrl.toString(), cellAddr.idString));
System.out.println(targetFeedUrl.toString()+": "+cellAddr.idString+" "+ inputValue);
BatchUtils.setBatchId(batchEntry, cellAddr.idString);
BatchUtils.setBatchOperationType(batchEntry, BatchOperationType.UPDATE);
batchRequest.getEntries().add(batchEntry);
}
spreadsheetService.setHeader("If-Match", "*");
// Submit the update
Link batchLink = cellFeed.getLink(ILink.Rel.FEED_BATCH, ILink.Type.ATOM);
CellFeed batchResponse = spreadsheetService.batch(new URL(batchLink.getHref()), batchRequest);
boolean isSuccess = true;
for (CellEntry entry1 : batchResponse.getEntries()) {
String batchId = BatchUtils.getBatchId(entry);
if (!BatchUtils.isSuccess(entry1)) {
isSuccess = false;
BatchStatus status = BatchUtils.getBatchStatus(entry);
}
}
spreadsheetService.setHeader("If-Match", null);
Batch copy:
What is the fastest way to update a google spreadsheet with a lot of data through the spreadsheet api?
There is a Bug with cell references such as $A5.
They will not write to the spreadsheet. While both A5 and $A$5 work, references with just one $ in cause a problem. I forget the fine detail.

how can I connect to database

I use this but I can't connect DataBase
conn1.Open();
using (OracleCommand crtCommand = new OracleCommand);
for connect to Oracle from application
string command = "Enter your command";
OracleConnection orclecon;
orclecon = new OracleConnection(connection);
orclecon.Open();
use this for select commands:
DataSet ds = new DataSet();
using (OracleDataAdapter Oda = new OracleDataAdapter(command, orclecon))
{
Oda.Fill(ds);
}
and use this for insert/update/delete commands:
//used for Oracle command (insert,update,delete) if number of rows that affected >0 return true else return false
using (OracleCommand orclcommand = new OracleCommand(command, orclecon))
{
int n = orclcommand.ExecuteNonQuery();
if (n > 0)
return true;
else
return false;
}
orclecon.Close();
To make it dynamic use this;
string sentence = "";
string formatprototype = "";//This will hold the string to be formatted.
string output="";
public void SearchString()
{
string pattern = #".*[ ]+?[\""]{1}(?<String>[a-zA-Z0-9_]*)[\""]{1}[ ]+?MINVALUE[ ]*(?<MinValue>[-?\d]*)[ ]*MAXVALUE[ ]*(?<MaxValue>[\d]*)[ ]+?[INCREMENT]*[ ]+?[BY]*[ ]+?(?<IncrementBy>[\d]*)[ ]+?[START]*[ ]+?[WITH]*[ ]+?(?<StartWith>[\d]*)[ ]+?[CACHE]*[ ]+?(?<Cache>[\d]*)\s+?";
Regex regex = new Regex(pattern);
Match match = regex.Match(sentence);
Group #string = match.Groups[1];
Group minvalue = match.Groups[2];
Group maxvalue = match.Groups[3];
Group incrementby = match.Groups[4];
Group startswith = match.Groups[5];
Group cache = match.Groups[6];
formatprototype = #"CREATE SEQUENCE ""{0}"" MINVALUE {1} MAXVALUE {2} INCREMENT BY {3} START WITH {4} CACHE {5} NOORDER NOCYCLE";
if (minvalue.Value.StartsWith("-"))
{
output = string.Format(formatprototype, #string, minvalue, maxvalue, incrementby, maxvalue, cache);
}
else if (!minvalue.Value.StartsWith("-"))
{
output = string.Format(formatprototype, #string, minvalue, maxvalue, incrementby, minvalue, cache);
}
MessageBox.Show(output);
}
Assume that SearchString() is the function in which you are doing this stuff.And make sure to assign each string that is extracted from database,to sentence.Try it and reply if it worked or not.

Make good LINQ query with string[]

I have some problems with LINQ and maby someone got answers
string[] roleNames = Roles.GetRolesForUser(currentUserName);
result = context.MenuRoles.Select(mr => new MenuGenerateViewModel
{
MenuID = mr.MenuID,
MenuNazwa = mr.Menu.MenuNazwa,
MenuKolejnosc = mr.Menu.MenuKolejnosc,
MenuStyl = mr.Menu.MenuStyl,
MenuParentID = mr.Menu.MenuParentID,
MenuActive = mr.Menu.MenuActive,
MenuActionName = mr.Menu.MenuAction.MenuActionName,
MenuControlName = mr.Menu.MenuControl.MenuControlName,
RoleName = mr.Role.RoleName,
RoleID = mr.RoleID,
MenuID = mr.MenuID
})
.Where(mr => mr.MenuActive == true)
.ToList();
How to take only compare string[] roleNames and return only if match. Problem alwais is when user is in the 2 or more roles.
Tx for answers
If I understand what you are asking for, add a second condition to your Where clause:
.Where(mr => mr.MenuActive && roleNames.Contains(mr.Role.RoleName))
You would be better off switching round your Where clause and Select for the simple reason that then you will not be retrieving from the database records which are not required.
result = context.MenuRoles.Where(mr => mr.MenuActive
&& roleNames.Contains(mr.Role.RoleName))
.Select(mr => ... )
.ToList();
This will generate a sql which only selects the necessary records, instead of selecting the whole lot and then filtering it. Try it and watch SQL profiler to see the difference (useful skill in any case when using EF)
With the help of brilliant people here, reached the target.
string[] roleNames = Roles.GetRolesForUser(currentUserName);
result = context.MenuRoles
.Where(mr => mr.Menu.MenuActive && roleNames.Contains(mr.Role.RoleName))
.Select(mr => new MenuGenerateViewModel
{
MenuID = mr.MenuID,
MenuNazwa = mr.Menu.MenuNazwa,
MenuKolejnosc = mr.Menu.MenuKolejnosc,
MenuStyl = mr.Menu.MenuStyl,
MenuParentID = mr.Menu.MenuParentID,
MenuActive = mr.Menu.MenuActive,
MenuActionName = mr.Menu.MenuAction.MenuActionName,
MenuControlName = mr.Menu.MenuControl.MenuControlName,
RoleName = mr.Role.RoleName
})
.ToList();
var userresult = context.MenuUsers
.Where(mr => mr.Menu.MenuActive && mr.User.Username == currentUserName)
.Select(mr => new MenuGenerateViewModel
{
MenuID = mr.MenuID,
MenuNazwa = mr.Menu.MenuNazwa,
MenuKolejnosc = mr.Menu.MenuKolejnosc,
MenuStyl = mr.Menu.MenuStyl,
MenuParentID = mr.Menu.MenuParentID,
MenuActive = mr.Menu.MenuActive,
MenuActionName = mr.Menu.MenuAction.MenuActionName,
MenuControlName = mr.Menu.MenuControl.MenuControlName,
Username = mr.User.Username
})
.ToList();
Here, gets all the menu to which you have the right, both through group membership and assigned directly to the menu itself.
// Kick all duplicates
var noduplicates = result.Concat(userresult)
.Distinct(new RoleMenuGenerateComparer());
Because usually we do not want duplicates in the menu so we remove them. For this to work properly we need to implement IEqualityComparer (U can read about this little bit up)
public class RoleMenuGenerateComparer : IEqualityComparer<MenuGenerateViewModel>
{
public bool Equals(MenuGenerateViewModel x, MenuGenerateViewModel y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.MenuNazwa == y.MenuNazwa && x.MenuID == y.MenuID;
}
public int GetHashCode(MenuGenerateViewModel menuGenerateViewModel)
{
if (Object.ReferenceEquals(menuGenerateViewModel, null)) return 0;
int hashMenuName = menuGenerateViewModel.MenuNazwa == null ? 0 : menuGenerateViewModel.MenuNazwa.GetHashCode();
int hashMenuID = menuGenerateViewModel.MenuID == null ? 0 : menuGenerateViewModel.MenuID.GetHashCode();
return hashMenuName ^ hashMenuID;
}
}
Of course I believe that you can optimize this code, but for the moment I have something like this.
Tx all for help.

Resources