I'm trying to work on a generic webpage for SQL Server metrics, these can be from queries/stored procedures etc. These might be in different databases and tables, and I want them in a nice format.
Say I have a URL that looks like this:
localhost:0000/Metric/framework?database=db1&table=t1&records=100
OR localhost:0000/Metric/framework?database=db1&table=t2&records=100
OR localhost:0000/Metric/framework?database=db2&table=t9&records=10
(DONE) Open Web page - code gets database/table/recordCount from the URL (Dynamic)
(DONE) Creates a connection to SQL
(DONE) Runs a query or stored procedure
(DONE) Casts ALL of the returned field types in to TYPE STRING, so that way I don't have to worry about faffing about matching my model to the SQL Server table.
(DONE) Then displays the results for the query/stored procedure
(DONE) I don't even have to mess around with the HTML side of things either, that's why I have the NAME as well as the VALUE in my model, that way I make the table heading from the Model.
I'm trying to do it as simple as possible, as it's just a few scripts that I want to be able to query through a web page, that way I can click on a URL and have metrics in front of me in seconds, without having to log in to SQL run a script, change database etc.
The way I have it working is: I just look at the number of fields I want to use, then add those new lines to the model _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 etc, but then the tricky bit comes in with the conversion of Type X to String. And for the 10 fields I would have to have 10 of those sections.
Example Webpage 1
1. int ID Casts to String
1. string Description Casts to String
1. date "2022-12-01" Casts to String
This would be a _0 _1 _2 field model
Example Webpage 2
1. int ID Casts to String
1. currency Price Casts to String
1. currency Qty Casts to String
1. date "2022-12-01" Casts to String
1. bool Yes Casts to String
This would be a _0 _1 _2 _3 _4 field model
Everything works and I can make a model of the returned fields, and I can change all of the types in to Strings get them in to the Model and display them on a separate page, so it's a win.
But it's not elegant in the slightest.
The tricky part, how can I make it so it has the minimal coding for the conversion?
I thought to iterate through them, but have been unable to do so.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.VisualBasic.FileIO;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
namespace Metric_Tracker.Pages.Metric
{
public class FrameworkModel : PageModel
{
public List<frameworkInfo> frameworks = new List<frameworkInfo>();
public void OnGet()
{
try
{
string database = HttpContext.Request.Query["database"].ToString();
if (database == null || database == String.Empty)
{
database = "database";
}
string table = HttpContext.Request.Query["table"].ToString();
if (table == null || table == String.Empty)
{
table = "table";
}
tablename = table;
string records = HttpContext.Request.Query["records"].ToString();
if (records == null || records == String.Empty)
{
records = "10";
}
string connectionString = "Data Source=.;Initial Catalog=" + database + ";integrated security=True;TrustServerCertificate=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "SELECT TOP (" + records + ") * FROM " + table ;
string fieldtype = "";
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
frameworkInfo framework = new frameworkInfo();
framework.fieldname_0 = (reader.GetName(0).ToString());
fieldtype = (reader.GetFieldType(0).ToString());
// Arrrggggghhhhh
if (fieldtype == "System.Int64") { framework.field_0 = (reader.GetInt64(0).ToString()); }
else if (fieldtype == "System.Int32") { framework.field_0 = (reader.GetInt32(0).ToString()); }
else if (fieldtype == "System.Int16") { framework.field_0 = (reader.GetInt16(0).ToString()); }
else if (fieldtype == "System.String") { framework.field_0 = (reader.GetString(0).ToString()); }
else if (fieldtype == "System.DateTime") { framework.field_0 = (reader.GetDateTime(0).ToString()); }
else if (fieldtype == "System.Char") { framework.field_0 = (reader.GetChar(0).ToString()); }
else if (fieldtype == "System.Decimal") { framework.field_0 = (reader.GetDecimal(0).ToString()); }
else if (fieldtype == "System.Double") { framework.field_0 = (reader.GetDouble(0).ToString()); }
else if (fieldtype == "System.Boolean") { framework.field_0 = (reader.GetString(0).ToString()); }
else if (fieldtype == "System.Byte") { framework.field_0 = (reader.GetByte(0).ToString()); }
else if (fieldtype == "System.UInt16") { framework.field_0 = (reader.GetInt16(0).ToString()); }
framework.fieldname_1 = (reader.GetName(1).ToString());
fieldtype = (reader.GetFieldType(1).ToString());
if (fieldtype == "System.Int64") { framework.field_1 = (reader.GetInt64(1).ToString()); }
else if (fieldtype == "System.Int32") { framework.field_1 = (reader.GetInt32(1).ToString()); }
else if (fieldtype == "System.Int16") { framework.field_1 = (reader.GetInt16(1).ToString()); }
else if (fieldtype == "System.String") { framework.field_1 = (reader.GetString(1).ToString()); }
else if (fieldtype == "System.DateTime") { framework.field_1 = (reader.GetDateTime(1).ToString()); }
else if (fieldtype == "System.Char") { framework.field_1 = (reader.GetChar(1).ToString()); }
else if (fieldtype == "System.Decimal") { framework.field_1 = (reader.GetDecimal(1).ToString()); }
else if (fieldtype == "System.Double") { framework.field_1 = (reader.GetDouble(1).ToString()); }
else if (fieldtype == "System.Boolean") { framework.field_1 = (reader.GetString(1).ToString()); }
else if (fieldtype == "System.Byte") { framework.field_1 = (reader.GetByte(1).ToString()); }
else if (fieldtype == "System.UInt16") { framework.field_1 = (reader.GetInt16(1).ToString()); }
ETC...
frameworks.Add(framework);
}
}
}
}
}
catch (Exception ex)
{
//some exception
}
}
}
public class frameworkInfo
{
public string? fieldname_0;
public string? field_0 = "";
public string? fieldname_1;
public string? field_1 = "";
Etc...
}
}
This is how I'm outputting the table. As you will see I have the fields from my model, this might make it easier to understand what I'm trying to do.
<table class="table">
<thead>
<tr>
foreach (var item in Model.framework)
{
<tr>
<td> item.fieldname_0 </td>
<td> item.fieldname_1 </td>
<td> item.fieldname_2 </td>
<td> item.fieldname_3 </td>
<td> item.fieldname_4 </td>
</tr>
break;
}
</tr>
</thead>
<tbody>
foreach (var item in Model.framework)
{
<tr>
<td> item.field_0 </td>
<td> item.field_1 </td>
<td> item.field_2 </td>
<td> item.field_3 </td>
<td> item.field_4 </td>
</tr>
}
</tbody>
</table>
This part is working for me thank you so much for your assistance. This will save me lots of cutting and pasting: 2 lines of code for each field and almost no overhead in the code, I can now knock out as many of these pages as needed for my project in about 2 minutes.
frameworkInfo framework= new frameworkInfo();
framework.field_0 = Convert.ToString(reader.GetValue(0));
framework.fieldname_0 = (reader.GetName(0).ToString());
framework.field_1 = Convert.ToString(reader.GetValue(1));
framework.fieldname_1 = (reader.GetName(1).ToString());
framework.field_2 = Convert.ToString(reader.GetValue(2));
framework.fieldname_2 = (reader.GetName(2).ToString());
framework.field_3 = Convert.ToString(reader.GetValue(3));
framework.fieldname_3 = (reader.GetName(3).ToString());
framework.field_4 = Convert.ToString(reader.GetValue(4));
framework.fieldname_4 = (reader.GetName(4).ToString());
frameworks.Add(framework)
You can simply use Convert.ToString, just check if the value is not null before it:
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
if (reader.GetValue(i) != DBNull.Value){
framework.field_1 = Convert.ToString(reader.GetValue(i)));
}
}
}
}
Related
I'm trying to update information in the SQL table with this code using c# language, the first section is to count all data. the second section is to run my update Query/function
the event is : private void mlnk_ADD_Click(object sender, EventArgs e)
string SARL;
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [employe] WHERE CODE = #CODE OR FULLNAME =
#FULLNAME OR BIRTHDATE = #BIRTHDATE OR BIRTHPLACE = #BIRTHPLACE OR ADDRESS = #ADDRESS
OR NCCP = #NCCP OR PHONE = #PHONE OR JOB = #JOB OR SARL =#SARL", napster.myConn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#CODE", mtb_CODE.Text);
cmd.Parameters.AddWithValue("#FULLNAME", mtb_FULLNAME.Text);
cmd.Parameters.AddWithValue("#BIRTHDATE", mdtp_BIRTHDATE.Text);
cmd.Parameters.AddWithValue("#BIRTHPLACE", mtb_BIRTHPLACE.Text);
cmd.Parameters.AddWithValue("#ADDRESS", mtb_ADDRESS.Text);
cmd.Parameters.AddWithValue("#NCCP", mtb_NCCP.Text);
cmd.Parameters.AddWithValue("#PHONE", mtb_PHONE.Text);
cmd.Parameters.AddWithValue("#JOB", mtb_JOB.Text);
if (mrb_LOCATERR.Checked == true)
{ SARL = "LOCA-TERR"; }
if (mrb_LUDAR.Checked == true)
{ SARL = "LUDAR"; }
if (mrb_ECORA.Checked == true)
{ SARL = "ECORA"; }
cmd.Parameters.AddWithValue("#SARL", SARL);
int UserExist = (int)cmd.ExecuteScalar();
here I am trying to insert the data into my table after checking that all data not exist to avoid the duplicate
if (UserExist > 0)
{
this.Alert("the information already exists.", frmAlert.alertTypeEnum.Error);
}
else
{
if (mrb_LOCATERR.Checked == true)
{ SARL = "LOCA-TERR"; }
if (mrb_LUDAR.Checked == true)
{ SARL = "LUDAR"; }
if (mrb_ECORA.Checked == true)
{ SARL = "ECORA"; }
if (mtb_CODE.Text != "" && mtb_FULLNAME.Text != "" && mdtp_BIRTHDATE.Text != "" && mtb_BIRTHPLACE.Text != "" && mtb_JOB.Text != "" && mtb_PHONE.Text != "")
{
// (update_employee) is public void for insert data into [employe] table
napster.update_employee(mlnk_ID.Text, mtb_CODE.Text, mtb_FULLNAME.Text, mdtp_BIRTHDATE.Text, mtb_BIRTHPLACE.Text, mtb_ADDRESS.Text, mtb_JOB.Text, mtb_PHONE.Text, SARL, mtb_NCCP.Text);
mlnk_ID.Text = "";
mtb_CODE.Text = "";
mtb_FULLNAME.Text = "";
mdtp_BIRTHDATE.Text = "";
mtb_BIRTHPLACE.Text = "";
mtb_ADDRESS.Text = "";
mtb_JOB.Text = "";
mtb_PHONE.Text = "";
mtb_NCCP.Text = "";
mrb_LOCATERR.Checked = true;
this.Alert("information updated.", frmAlert.alertTypeEnum.Info);
}
else
{
this.Alert("information not updated.", frmAlert.alertTypeEnum.Error);
}
}
Use stored procedure its more cleanner and you can define the output and the input parameteres ( exemple :select cout(*) into output_parameter where ....).
and use switch statement, There is a lot of IF in your code.
Project_Detail pro = new Project_Detail();
string title=Ttitle.Text;
string year1=Tyear.Text;
string key = Tkeywrds.Text;
string area = Ddl_area.Text;
string categ = Ddl_catgry.Text;
string tech = Ddl_tech.Text;
string type =Ddl_type.Text;
var q = from obj in da.Project_Details
where obj.Project_Title.Contains(title)
|| obj.Submission_Date.Contains(year1)
|| obj.Keywords.Contains(key)
|| obj.Project_Area.Contains(area)
|| obj.Project_Category.Contains(categ)
|| obj.Project_Technology.Contains(tech)
|| obj.Project_Type.Contains(type)
select obj;
if (q != null)
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}
this code give last record of table and also not give else condition result.
I want result of all condition and want to use LIke satatement.
q is never null. It might be empty, though. So you should change your code to
if (q.Any()) // <<-----
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}
You can also use count method .Count()
if (q.count()>0)
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}
I want to create List(T) from sql db table
let's say i have one table
ID Name
1 xyz
2 efd
3 abc
4 pqr
i want to some code in C# who will read this db table data and write
following lines in my c# class or / notepad or whatever...
List<ItemViewModel> Items= new List<ItemViewModel>();
Items.Add(new ItemViewModel() { id= 1, name= "xyz"}
Items.Add(new ItemViewModel() { id= 2, name= "efd"}
Items.Add(new ItemViewModel() { id= 3, name= "abc"}
Items.Add(new ItemViewModel() { id= 4, name= "pqr"}
thanks in advance
Add "dapper" to your project (available on NuGet), then:
var list = connection.Query<YourType>("select * from TableName").ToList();
Or for a parameterless query:
var region = "South";
var list = connection.Query<YourType>(
"select * from TableName where Region=#region", new { region });
Here one of best code that you can got, the following method can deal with any data classes and system defined types :
public List<T> ExecuteQuery<T>(string s, SqlConnection condb, params SqlParameter[] Params)
{
List<T> res = new List<T>();
string er = "";
SqlDataReader r = null;
try {
if (condb == null)
throw new Exception("Connection is NULL");
if (string.IsNullOrEmpty(s))
throw new Exception("The query string is empty");
using (SqlCommand cm = new SqlCommand(s, condb)) {
if (Params.Length > 0) {
cm.Parameters.AddRange(Params);
}
if (cm.Connection.State != ConnectionState.Open)
cm.Connection.Open();
r = cm.ExecuteReader;
object prps = typeof(T).GetProperties;
object prpNames = prps.Select((System.Object f) => f.Name).ToList;
if (r.HasRows) {
while (r.Read) {
if (typeof(T).FullName.Contains("System.")) {
res.Add(r(0));
// Classes
} else {
object c = Activator.CreateInstance(typeof(T));
for (j = 0; j <= r.FieldCount - 1; j++) {
object jj = j;
//er = dt.Rows(jj)("ColumnName").ToLower
object fname = r.GetName(j).ToString;
er = fname;
object fType = r.GetProviderSpecificFieldType(j).ToString.ToLower;
object p = prps.Where((System.Object f) => f.Name.Trim.ToLower == fname.ToLower).ToList;
if (p.Count > 0) {
//Date or DateTime
if (fType.Contains("date")) {
if (!p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value))) {
p(0).SetValue(c, Now, null);
} else {
if (!(p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value)))) {
p(0).SetValue(c, r(fname), null);
}
}
//String
} else if (fType.Contains("string")) {
if (r(fname) == null || r(fname).Equals(System.DBNull.Value)) {
p(0).SetValue(c, "", null);
} else {
p(0).SetValue(c, r(fname), null);
}
} else {
if (!(p(0).PropertyType.FullName.ToLower.Contains("system.nullable") && (r(fname) == null || r(fname).Equals(System.DBNull.Value)))) {
p(0).SetValue(c, r(fname), null);
}
}
}
}
res.Add(c);
}
}
}
r.Close();
}
//If cm IsNot Nothing Then
// 'cm.Connection.Close()
// cm.Dispose()
//End If
} catch (Exception ex) {
if (r != null && r.IsClosed == false)
r.Close();
throw ex;
}
return res;
}
Usage :
var data = ExecuteQuery<ItemViewModel>("SELECT [ID], [Name] FROM [ItemViewTable]",
new SqlConnection("SomeConnectionString"));
If you just want a list populated with whatever data is currently in the database table, you can just do a simple query. You don't have to involve code generation.
Using linq-to-sql to read the contents of the table and create an ItemViewModel for each entry:
using(var context = new MyLinqDbContext())
{
var items = (from i in context.MyTable
select new ItemViewModel { id = ID, name = Name })
.ToList();
}
If you want C# code generated which is being created from database values and compiled into your solution, you want to use Microsofts text templating engine (T4). To get a hold of this technique, you can read up on it in detail in this blog entry.
If you understand the basics of T4, you can read up this blog, there's an example of how to dynamically create Enum classes for static lookup tables which are stored in a database. Starting from this code, you can write your own code generation template which creates the classes you need.
I got an ActionResult TabNotes which returns a View for a tab which shows notes from a database in a grid. On the tab is a button for ActionResult CreateNote, which returns a PartialView and after saving the note I redirect back to the ActionResult TabNotes with
return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
However, when it goes to the action result TabNotes using this redirect it does not show the grid. The javascript gives the following error
Uncaught ReferenceError: $ is not defined (anonymous function)
Uncaught ReferenceError: ko is not defined (anonymous function)
This does not happen the first time it goes to ActionResult. Using breakpoints the following part of the ActionResult TabNotes:
[...]
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
gives the same input values in Model for the first time and the second time. Where can this error come from?
Edit: Firebug shows the following errors:
prompt aborted by user
throw Components.Exception...by user", Cr.NS_ERROR_NOT_AVAILABLE); nsPrompter.js (regel 462 <Systeem>
$ is not defined
$(document).ready(function(){$('#tblTN...tes/44?cmd=refresh" id="TNPhrase44"> 44?mod...=Phrase (regel 2)
ko is not defined
var viewModel=ko.mapping.fromJ...],"buttons":[],"PostAction":null}}); 44?mod...=Phrase (regel 12)
Below is the javascript and code
#model test.Web.Framework.Areas.Administration.Models.TabNotesModel
#using (UI.DocumentReadyScript())
{
if (Model.meta.id.HasValue)
{
UI.jQuery("#tbl" + Model.meta.modelname).flexigrid(Model.Grid);
}
}
<form method="post" action="#Url.Action("TabNotes", new { cmd = "refresh" })" id="#Model.meta.modelname">
<div class="ui-state-highlight ui-corner-all highlight" data-bind="visible: meta.message">
<span class="ui-icon ui-icon-info"></span><strong data-bind="text: meta.message">
</strong>
</div>
#using (UI.BeginBlock("Administation.TabNotes", UI.Label("Notes", "Notes").ToString(), test.Web.Framework.Core.enumIcons.pencil, false, false))
{
<table id="#("tbl" + Model.meta.modelname)">
</table>
}
</form>
<script type="text/javascript">
(function() {
var viewModel=ko.mapping.fromJS(#Html.Raw(UI.JavascriptEncode(Model)));
viewModel.getData=function() { return ko.mapping.toJSON( this ); };
viewModel.setData=function(data){
$('#tbl'+this.meta.modelname()).flexigrid( data.Grid);
ko.mapping.updateFromJS(this,data);
};
$('##Model.meta.modelname').koform({viewmodel: viewModel , validate : {errorElement:'p' } } );
$('##Model.meta.modelname').koform('applyBindings');
$('#load-partial').click(function() {
$('#partial').load('#Url.Action("CreateNote", "Entity", new {itemId = #Model.meta.id, modelEntity = "Phrase"})');
});
})();
</script>
<div id="partial"></div>
<button type="button" id="load-partial">Create Note</button>
'
public ActionResult CreateNote(
[ModelBinder(typeof(Models.JsonModelBinder))]
NoteModel Model, string cmd, long? itemId, string modelEntity)
{
if (cmd == "Save")
{
Model.meta.message = "Note saved";
test.Database.User User = UserRepository.GetUser(1);
Entity entity = NotesRepository.GetEntity("Phrase");
NotesRepository.StoreNote(Model.subject, Model.text, User, entity, itemId);
return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
}
Model.meta.modelname = "CreateNote";
Model.meta.JsViewModelType = "EditNoteModel";
Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId});
return PartialView("CreateNotePartial",Model);
}
'
public ActionResult TabNotes([ModelBinder(typeof(Models.JsonModelBinder))]
TabNotesModel Model, string cmd, string modelEntity, long? id)
{
if (modelEntity != null)
{
Model.meta.entity = modelEntity;
}
Entity entity = NotesRepository.GetEntity(Model.meta.entity);
if (id.HasValue)
{
Model.meta.id = id;
}
if (Model.meta.id.HasValue)
{
Model.meta.modelname = "TN" + Model.meta.entity + Model.meta.id.Value.ToString();
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId", Model.meta.id.Value);
Entity noteEntity = NotesRepository.GetEntity("Note");
var grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
grid.buttons.Clear();
//grid.buttons.Add(new Button { onpress = "CreateNote", action = Url.Action("CreateNote"), name = "CreateNote", postdata = new { meta = Model.meta }});
grid.title = "";
Model.Grid = grid;
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
'
public GridResult TabNoteData(string id, long itemId, FlexigridRequest request, string cmd)
{
GridResult returnValue = null;
var entity = NotesRepository.GetEntity(id);
Entity noteEntity = NotesRepository.GetEntity("Note");
//var Acess = UIRepository.GetEntityAccess(id);
FlexigridConfiguration grid;
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId",itemId);
grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
IQueryable q = NotesRepository.GetNotes(entity.EntityId, itemId);
var sortField = entity.EntityFields.SingleOrDefault(c => c.Name == request.sortname);
if (sortField == null)
{
request.sortname = grid.sortname;
}
IQueryable qdata = null;
if (!string.IsNullOrEmpty(request.sortname) && request.sortname != "undefined")
{
switch (request.sortorder)
{
case enumFlexigridRequestSortOrder.asc:
qdata = q.OrderBy(request.sortname + " ascending");
break;
case enumFlexigridRequestSortOrder.desc:
qdata = q.OrderBy(request.sortname + " descending");
break;
}
}
if (!string.IsNullOrEmpty(request.query) && !string.IsNullOrEmpty(request.qtype))
{
qdata = qdata.Where(request.qtype.SanitizeFieldExpression() + ".Contains(#0)", request.query);
}
if (request.q != null && request.q.Length > 0)
{
for (int i = 0; i < request.q.Length; i++)
{
var type = UIRepository.GetType(id);
var property = type.GetProperty(request.q[i]);
System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(property.PropertyType);
string sv = request.v[i];
if (sv == null || sv == "null")
{
qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=#0", (object)null);
}
else
{
object v = tc.ConvertFromString(sv);
qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=#0", v);
}
}
}
string settingName = "Grid." + id + ".Rp";
var setting = UIRepository.GetQuery<test.Database.UserSetting>().SingleOrDefault(uc => uc.CreatedById == CurrentUser.UserId && uc.Name == settingName);
if (setting == null)
{
setting = UIRepository.Create<test.Database.UserSetting>();
setting.Name = settingName;
setting.Value = request.rp.ToString();
UIRepository.Add(setting);
}
else
{
if (request.rp.ToString() != setting.Value)
{
setting.Value = request.rp.ToString();
UIRepository.Update(setting);
}
}
int rowId = 0;
var datarows = new List<object>();
foreach (var record in qdata.Skip((request.page - 1) * request.rp).Take(request.rp).GetData())
{
var cellValues = new List<object>();
foreach (var gc in grid.colModel.OrderBy(c => c.di))
{
cellValues.Add(gc.ToString(UI, record));
}
var row = new { id = rowId, cell = cellValues.ToArray() };
datarows.Add(row);
rowId++;
}
returnValue = Grid(request.page, qdata.Count(), datarows.ToList());
return returnValue;
}
That error can only be caused be one of three things:
Your JavaScript file is not being properly loaded into your page
You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.
You should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.
Make sure all javascript code is being run inside a code block such as:
$(document).ready(function () {
//your code here
});
This will ensure that your code is being loaded after jQuery has been initialized.
One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.
So to avoid that you can use a "bodyguard" function like the following:
( function($) {
//We can now use $ as I implemented the bodyguard!
$(document).ready(function() {
//your code...
});
} ) ( jQuery );
public enum FrameStatus
{
NotReport = 0,
NormalStatus = 1,
NotNormalstatus = 2
}
but alway FrameStatus.NormalStatus how?
public FrameStatus FrameReportStatus(int Framid, string Timebet)
{
foreach (FrameCam fc in al)
{
if (fc.Timebet == Timebet && fc.IdFrame == Framid)
{
if ((int)fc.status == 1) fc.status = FrameStatus.NormalStatus;
else if ((int)fc.status == 2) fc.status = FrameStatus.NotNormalstatus;
else fc.status = FrameStatus.NotReport;
return fc.status;
}
}
return FrameStatus.NotReport;
}
my complete classs
class FrameCam
{
private ArrayList al = new ArrayList();
public string strConnect;
public FrameStatus status = FrameStatus.NormalStatus;
public string Timebet;
public int IdFrame;
public FrameCam()
{
}
public FrameCam(string st, string bt)
{
strConnect = st;
Timebet = bt;
LoadtoList();
}
public FrameStatus GetFramStatus(int Framid, string timebet)
{
foreach (FrameCam fc in al)
{
if (Framid == fc.IdFrame && timebet == fc.Timebet)
{
return fc.status;
}
}
return FrameStatus.NotReport;
}
private void LoadtoList()
{
SqlConnection conn = null;
SqlDataReader sr = null;
try
{
string query =
"SELECT * FROM FrameReport WHERE convert(varchar, GETDATE(), 101) = convert(varchar, DateTimeSign, 101) AND TimeSignBeetWeen='" +this.Timebet+"'";
conn = new SqlConnection(this.strConnect);
conn.Open();
SqlCommand sc = new SqlCommand();
sc.CommandText = query;
sc.Connection = conn;
sr = sc.ExecuteReader();
while (sr.Read())
{
FrameCam fc = new FrameCam();
fc.Timebet = sr["TimeSignBeetWeen"].ToString();
fc.IdFrame = (int)sr["IdFrame"];
if ((int)sr["Status"] == (int)FrameStatus.NormalStatus)
{
status = FrameStatus.NormalStatus;
}
if ((int)sr["Status"] == (int)FrameStatus.NotNormalstatus)
{
status = FrameStatus.NotNormalstatus;
}
else status = FrameStatus.NotReport;
al.Add(fc);
}
}
catch (Exception)
{
}
finally
{
if (sr != null) sr.Close();
if (conn != null) conn.Close();
}
}
public FrameStatus FrameReportStatus(int Framid, string Timebet)
{
foreach (FrameCam fc in al)
{
if (fc.Timebet == Timebet && fc.IdFrame == Framid)
{
if ((int)fc.status == 1) fc.status = FrameStatus.NormalStatus;
else if ((int)fc.status == 2) fc.status = FrameStatus.NotNormalstatus;
else fc.status = FrameStatus.NotReport;
return fc.status;
}
}
return FrameStatus.NotReport;
}
}
You're not assigning anything to fc.Status within LoadToList and the initialize for FrameCam's 'status' field is "FrameStatus.NormalStatus". If you update the code in LoadToList to assign to fc.status (instead of this.status, as is shown here) then it should work as you expect.
As a side note, LoadToList should be a static method, which would have mitigated this problem.
Use a debugger. Step through the code.
The code is not taking the path you think it is taking.
If you do not know how to step through code in a debugger, you MUST learn.
This is not an optional skill for a computer programmer.