Accessing SQL output in coding - asp.net

I have a SQL output like
TotalLeave Status
---------- ------
3 PaidLeave
5 MedicalLave
and I need to show this value in my label controls like,
lblMedicalLeave.text = 5
lblPaidLeave.text = 3
for this I just created objects for my dataset in my code like,
StaffAttendanceStatusTableAdapters.StaffTypesTableAdapter staffAttendanceStatus =
new StaffAttendanceStatusTableAdapters.StaffTypesTableAdapter();
StaffAttendanceStatus.StaffTypesDataTable StaffDataTable =
staffAttendanceStatus.GetDataStaffAttendanceStatus(staff.StaffId);
if (StaffDataTable[0] != null)
{
StaffAttendanceStatus.StaffTypesRow StaffRow = StaffDataTable[0];
lblTotalMedicalLeave.Text = StaffRow.TotalLeave.ToString();
lblTotalPaidLeave.Text = StaffRow.TotalLeave.ToString();
}
its showing the same value(3), is it possible to get the TotalLeave value for corresponding Status? can anyone help me here

You are accessing the same row both times. Use StaffDataTable[1] to access the second row. Anyway you should check if there is a result before access any values!
using StaffAttendanceStatusTableAdapters;
....
StaffTypesTableAdapter staffAttendanceStatus = new StaffTypesTableAdapter();
StaffAttendanceStatus.StaffTypesDataTable StaffDataTable =
staffAttendanceStatus.GetDataStaffAttendanceStatus(staff.StaffId);
if (StaffDataTable != null && StaffDataTable.Count > 1)
{
lblTotalMedicalLeave.Text = StaffDataTable[0].TotalLeave.ToString();
lblTotalPaidLeave.Text = StaffDataTable[1].TotalLeave.ToString();
}
hth

Since you need to get TotalLeave from two rows, you need to fetch data from two rows.
if (StaffDataTable != null && StaffDataTable.Rows.Count > 1)
{
StaffAttendanceStatus.StaffTypesRow StaffRow1 = StaffDataTable[0];
StaffAttendanceStatus.StaffTypesRow StaffRow2 = StaffDataTable[1];
lblTotalMedicalLeave.Text = StaffRow1.TotalLeave.ToString();
lblTotalPaidLeave.Text = StaffRow2.TotalLeave.ToString();
}
if there is no order of PaidLeave and MedicalLave status, just check row.Status and assign total value to corresponding label

Related

web2py SQLFORM.grid url

When I try to put form = SQLFORM.grid(db.mytable) in my controller the request changes to my/web/site/view?_signature=520af19b1095db04dda2f1b6cbea3a03c3551e13 which causes my if statement in controller to collapse. Can smbd please explain why this happens?
If I put user_signature=False then on view load the grid is shown (though the looks is awful, and I still need to find out how to change the view of my table), but on search,edit, etc. click, the same thing happens again. The url is changed and I get an error
Any suggestions?
thank you
EDIT
This is my edit function
#auth.requires_login()
def edit():
#Load workers
workers = db(db.worker.w_organisation == 10).select(db.worker.w_id_w, db.worker.w_organisation, db.worker.w_first_name, db.worker.w_last_name,db.worker.w_nick_name,db.worker.w_email,db.worker.w_status,db.worker.w_note).as_list()
#Define the query object. Here we are pulling all contacts having date of birth less than 18 Nov 1990
query = ((db.worker.w_organisation == 10) & (db.worker.w_status==db.status.s_id_s))
#Define the fields to show on grid. Note: (you need to specify id field in fields section in 1.99.2
fields = (db.worker.w_first_name, db.worker.w_last_name,db.worker.w_nick_name,db.worker.w_email,db.status.s_code,db.worker.w_note)
#Define headers as tuples/dictionaries
headers = { 'worker.w_first_name' : 'Ime',
'worker.w_last_name' : 'Priimek',
'worker.w_nick_name' : 'Vzdevek',
'worker.w_email' : 'E-posta',
'status.s_code': 'Status',
'worker.w_note' : 'Komentar' }
#Let's specify a default sort order on date_of_birth column in grid
default_sort_order=[db.worker.w_last_name]
#Creating the grid object
form = SQLFORM.grid(query=query, fields=fields, headers=headers,searchable=True, orderby=default_sort_order,create=True, \
deletable=True, editable=True, maxtextlength=64, paginate=25,user_signature=False
)
form = SQLFORM.grid(db.worker,user_signature=False)
workersDb = db((db.worker.w_organisation == 10) & (db.worker.w_status==db.status.s_id_s)).select(db.worker.w_id_w, \
db.worker.w_organisation, db.worker.w_first_name, \
db.worker.w_last_name,db.worker.w_nick_name,db.worker.w_email,\
db.status.s_code,db.worker.w_note).as_list()
workersList = []
for rec in workersDb:
status = rec['status']['s_code']
workers = rec['worker']
if not rec["worker"]["w_first_name"]:
polno_ime = rec["worker"]["w_last_name"]
elif not rec["worker"]["w_last_name"]:
polno_ime = rec["worker"]["w_first_name"]
else:
polno_ime = rec["worker"]["w_first_name"] + " " + rec["worker"]["w_last_name"]
rec["worker"]['w_full_name'] = polno_ime
rec["worker"]["w_status"] = status
data = rec["worker"]
#print rec
#print data
workersList.append(rec["worker"])
# If type of arg is int, we know that user wants to edit a script with an id of the argument
if(request.args[0].isdigit()):
script = db(getDbScript(request.args[0])).select(db.script.sc_lls, db.script.sc_name, db.script.id, db.script.sc_menu_data).first()
formData = str(script["sc_menu_data"])
#form = SQLFORM.grid(db.auth_user)
#print formData
# If we dont get any results that means that user is not giving proper request and we show him error
#print script
#Parsing script to be inserted into view
if not script:
return error(0)
return dict(newScript = False, script = script, formData = formData, workers = workersList, form = form)
# If the argument is new we prepare page for new script
elif request.args[0] == 'new':
scripts = db((auth.user.organization == db.script.sc_organization)).select(db.script.sc_name, db.script.id, workers = workersList, form = form)
return dict(newScript = True, scripts = scripts, workers = workersList, form = form)
# Else error
else:
return error(0)
also not to mention the sqlgrid looks awful, here is link to the picture https://plus.google.com/103827646559093653557/posts/Bci4PCG4BQQ

How to select greater number and lower number using LINQ To SQL in C#

I have a TABLE in SQL Database there is a columns in
TABLE ID,Subject,Body,Status,TimeDate in the 400 row data and each i have take a Id as a P_Key and Identity Specification is Yes.
Here is Id = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 etc..
I want to select greater Id from table based on saved old id like i have saved ID 12 in im getting same id like this with Linq Query below:
public static int CheckId()
{
DataClassesDataContext con = new DataClassesDataContext(Globals.con);
var q = from v in con.TABLE
where v.Id== 12 & v.Status == Active
select v.Id;
foreach (var val in q)
{
return Convert.ToInt32(val);
}
return 0;
}
the i can return a greater id then 12. and there is also one issue. if there is greater ID is Missing from DB example Id 13 is missing then i will get Id 14 in that case. please let me know how can i get id like this i want from db using linq query.
Use Min
return con.<TABLE>
.Where(v=>v.ID > 12)
.Select(v=>v.ID)
.DefaultIfEmpty()
.Min();
I made a sample for you
List<Int32> test = new List<Int32>{1,2,3,4,5,6,7,8,9,10,11,12,14,13,15,16};
var min = test.Where(x=>x>12).Min();
Gives result 13 only, even when 14 is the first bigger
In Your case
//get a table object
Table table = new Table() //if you want whole row.
table = con.Table.Where(x=>x.id>12).MIN();
Based on the code you already have:
DataClassesDataContext con = new DataClassesDataContext(Globals.con);
var q = from v in con.TABLE
where v.Id > 12 & v.Status == Active
orderby v.Id
select v.Id;
return q.Take(1); // to return the whole row
// or
return q.Take(1).Id; // to return only the Id
This would return the first row meeting the criterias (id > 12, status = active). Add error handling code as needed.

linq sum and group [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamic Anonymous type in Razor causes RuntimeBinderException
I have this Linq Agregate Query
var GruposQ = from lcGrupos in db.Merlin_ConceptosFacturacion_Kit_Componentes
where lcGrupos.NumIdConcepto == Item.NumIdConcepto & lcGrupos.BitComponenteVariable == true
select lcGrupos;
var GruposList = from comps in GruposQ
group comps by
new
{
NumIdGrupoProducto = comps.NumIdGrupoProducto,
} into g
select new
{
NumIdTransaccion = NumIdTransaccion,
NumIdGrupoProducto = g.Key.NumIdGrupoProducto,
NumCantidad = g.Sum(x=>x.NumCantidad),
Grupo = GruposQ.Where(x => x.NumIdGrupoProducto == g.Key.NumIdGrupoProducto)
};
ViewBag.CompsKit = GruposList.ToList();
My problem is when I try to get elements from ViewBag.CompsKit:
#foreach (var myTrans in ViewBag.CompsKit)
{
// Here it throws an error
// 'object' does not contain a definition for 'NumIdtransaccion'
<span>myTrans.NumIdtransaccion</span>
}
But if i look into this object it allready has the property.
myTrans { NumIdTransaccion = 15460
, NumIdGrupoProducto = 163
, NumCantidad = 100,000
, Grupo = System.Data.Common.Internal.Materialization.CompensatingCollection`1[ParadigmaNet.Areas.Items.Models.Merlin_ConceptosFacturacion_Kit_Componentes] } dynamic {<>f__AnonymousType7<decimal,decimal?,decimal,System.Linq.IQueryable<ParadigmaNet.Areas.Items.Models.Merlin_ConceptosFacturacion_Kit_Componentes>>}
How can I do to access the properties ? in this agregate ?
You can't use "dynamic" type in a Razor View.
You must use a typed object as Model.
You can do grouping and filtering in single query:
var numIdConcepto = Item.NumIdConcepto;
var query = from comps in db.Merlin_ConceptosFacturacion_Kit_Componentes
where comps.NumIdConcepto == numIdConcepto &&
comps.BitComponenteVariable
group comps by comps.NumIdGrupoProducto into g
select new
{
NumIdGrupoProducto = g.Key,
NumCantidad = g.Sum(x => x.NumCantidad),
Grupo = g.ToList()
};
ViewBag.CompsKit = query.ToList();
ViewBag.NumIdTransaccion = NumIdTransaccion;
Also
you don't need create anonymous object for grouping by single property
you don't need to compare boolean values with true/false
you can simply use g.Key when use single property for grouping
items in group already will have NumIdGrupoProducto equal to grouping key
Instead of assigning same NumIdTransaccion to each group in the query result, pass that value to view separately: ViewBag.NumIdTransaccion = NumIdTransaccion
View:
<span>ViewBag.NumIdTransaccion</span>
#foreach(var item in ViewBag.CompsKit)
{
<span>#item.NumIdGrupoProducto</span>
<span>#item.NumCantidad</span>
}
Consider also creating ViewModel for this view - thus you will be safe about typos and all such errors will be eliminated at compile time.

Field type returning numbers [Axapta]

I want to get the field types. My code is as follows:
tID = dict.tableName2Id(tableName);
counter = 0;
dt = new DictTable(tID);
if (dt)
{
counter = dt.fieldNext(counter);
while (counter)
{
df = dt.fieldObject(counter);
if (df)
{
fields = conIns(fields,1,df.baseType());
}
counter = dt.fieldNext(counter);
}
}
On return to .NET Business connector, the types are shown as numbers instead of strings.
Kindly help.
EDIT : DataField.baseType() returns "Types" can this be converted to string and then added to the container?
EDIT 2: Ok now, im getting a Types Enumeration. Is there any way to map this enumeration in AX and add to container as string?
Got it!! Here's the code :
tID = dict.tableName2Id(tableName);
counter = 0;
dt = new DictTable(tID);
if (dt)
{
counter = dt.fieldNext(counter);
while (counter)
{
df = dt.fieldObject(counter);
if (df)
{
t = df.baseType();
fields = conIns(fields,1,enum2str(t));
}
counter = dt.fieldNext(counter);
}
}

Flex AS3 Arraycollection sorting based on Array of values

I have been working on sorting Arraycollection like ascending , descending the numeric list. Total length of my collection will go up to 100. Now I want to preform sort to nested data like this
Data Structure
Name : String
Categories : Array ["A","x or y or z","C"]
Categories array will have maximum 3 items , out of that three items the second item can have 3 different values either X or Y or Z. My result data looks like here
{"Mike" , ["A","x","C"]}
{"Tim" , ["A","y","C"]}
{"Bob" , ["A","x","C"]}
{"Mark" , ["A","z","C"]}
{"Peter" , ["A","z","C"]}
{"Sam" , ["A","y","C"]}
anyone please explain how to sort this type of data in a way showing all "x" first , "y" next and "z" at the last and vice a versa. Any help is really appreciated. Thanks Anandh. .
You can specify a compare function in your SortField like this:
var sortfield:SortField = new SortField("Categories");
sortfield.compareFunction = myCompare;
var sort:Sort = new Sort();
sort.fields = [sortfield];
yourCollection.sort = sort;
and your compare function:
function myCompare(a:Object, b:Object):int {
/*
return -1, if a before b
return 1, if b before a
return 0, otherwise
*/
}
or something like that.. and it's untested code :)
I have created a new property to the data structure called categoryOrder In the setter I did the following and Am using the categoryOrder for sorting - sortBy = categoryOrder;. I understand little hard coding is needed but still I believe this will reduce the number of comparisons when I use compareFunction. Anyone please valid this idea. Thanks!
public function set categories(data:ArrayCollection) :void
{
if(data != null)
{
_categories = data;
for each(var categorie:Object in data)
{
switch(categorie.categoryName)
{
case "x":{categoryOrder = 1;break;}
case "y":{categoryOrder = 2;break;}
case "z":{categoryOrder = 3;break;}
}
}
}
}
Data Structure
Name : String
Categories : Array ["A","x or y or z","C"]
categoryOrder : Number

Resources