Hi Have This Code, I Want This Function To Return A List Of CLS_EL_ARCHIVE Objects But I Get This Error :
'CLS_EL_ARCHIVE' does not contain a constructor that takes 0 argument
public override IEnumerable<CLS_EL_ARCHIVE> GetAll()
{
DataTable DT = DAC.SelectData("SP_GET_ALL", new SqlParameter[] { new SqlParameter("#Table", "ARCHIVE") });
List<CLS_EL_ARCHIVE> ArchiveList = new List<CLS_EL_ARCHIVE>();
ArchiveList = DT.AsEnumerable().Select(Row => new CLS_EL_ARCHIVE
{
ArchiveId = Row.Field<int>("ArchiveId"),
Label = Row.Field<string>("Label"),
Date = Row.Field<DateTime>("Date"),
Note = Row.Field<string>("Note")
});
return ArchiveList;
}
This is working for me :) waiting for more answers
DataTable DT = DAC.SelectData("SP_GET_ALL", new SqlParameter[] { new SqlParameter("#Table", "ARCHIVE") });
List<CLS_EL_ARCHIVE> ArchiveList = new List<CLS_EL_ARCHIVE>();
ArchiveList = DT.AsEnumerable().Select(Row => new CLS_EL_ARCHIVE(Row.Field<int>("ArchiveId"), Row.Field<string>("Label"),
Row.Field<DateTime>("Date"), Row.Field<string>("Note"))).ToList();
Related
I am facing a problem in rendering events from a SQL Server database. All events are getting fetched using this code but not getting displayed in my calendar, so can anyone please help me?
.cshtml code:
events: function(start, end, callback) {
debugger;
var startdate=start.format('DD-MM-YYYY HH:mm'),
enddate=end.format('DD-MM-YYYY HH:mm'),
params={'start_time':startdate,'end_time':enddate};
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllEvents","Base")',
success: function (data) {
alert("hello");
}
});
}
,
my controller code:
public static List<Task_has_UsersModel> LoadAllTasks(double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
var sql = "SELECT * from task_has_users";
var data = Database.Open("DefaultConnection").Query(sql);
List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
foreach (var item in data)
{
Task_has_UsersModel model = new Task_has_UsersModel();
model.Task_Id = Convert.ToInt32(item.Task_Id);
model.Project_Id = Convert.ToInt32(item.Project_Id);
model.start_time = item.start_time;
model.end_time = item.end_time;
result.Add(model);
}
return result;
}
[HttpPost]
public JsonResult GetAllEvents(double start, double end)
{
var ApptListForDate = LoadAllTasks(start,end);
var eventList = from e in ApptListForDate
select new
{
id=e.Task_Id,
name=e.Project_Id,
start=e.start_time.ToString(),
end=e.end_time.ToString(),
allDay=false,
color = "#008000",
//allDay=false,
className= "label-important" ,
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
private static DateTime ConvertFromUnixTimestamp(double timestamp)
{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(timestamp);
}
}
I have tried with (double start,double end ) still my events are not getting displayed in calendar
Finally after 3 days of hard work , i have done this.... No need to write anything in events , just call a function , it will automatically appends the date range and all you are done................... thanks
.cshtml code:
events:'GetAllEvents',
eventLimit: 50,
editable: true,
droppable: true,
// timeFormat: 'hh:mm-h:mma ',
timeFormat: 'hh:mma ',
displayEventEnd : true,
my controller code:
public static List<Task_has_UsersModel> LoadAllTasks(string start, string end,string uname)
{
UsersContext db = new UsersContext();
var uid = (from i in db.UserProfiles
where i.UserName == uname
select i.UserId).FirstOrDefault();
int userId = Convert.ToInt32(uid);
// var culture = System.Globalization.CultureInfo.CurrentCulture;
var sql = "SELECT * from task_has_users where UserId = " + userId;
var data = Database.Open("DefaultConnection").Query(sql);
List<Task_has_UsersModel> result = new List<Task_has_UsersModel>();
foreach (var item in data)
{
Task_has_UsersModel model = new Task_has_UsersModel();
model.Task_Id = Convert.ToInt32(item.Task_Id);
model.Project_Id = Convert.ToInt32(item.ProjectId);
// model.start_time = Convert.ToDateTime(item.start_time);
model.start_time = (item.start_time).ToString("yyyy-MM-dd HH-mm-ss");
model.end_time = (item.end_time).ToString("yyyy-MM-dd HH-mm-ss");
model.title = item.title;
result.Add(model);
}
return result;
}
[HttpGet]
public JsonResult GetAllEvents(string start, string end)
{
string uname = (Session["UserName"]).ToString();
var ApptListForDate = LoadAllTasks(start,end,uname);
var eventList = from e in ApptListForDate
select new
{
id=e.Task_Id,
title=e.title,
start=e.start_time,
end=e.end_time,
allDay=false,
color = "#008000",
//allDay=false,
className= "label-important" ,
};
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
finally done
Now i am using Kendo for Autocomplete text. Database is Northwind. But it always return undefined. I don't know to have any wrong thing?
View
#(Html.Kendo().AutoComplete()
.Name("cbRegion")
.Filter("contains")
.DataTextField("RegionDescription"))
.DataSource(s => { s.Read(r => r.Action("GetSupplier", "AutoComplete")).ServerFiltering(true); })
Controler
public JsonResult GetSupplier() {
var md = db.Regions.ToList();
List<RegionInfo> ls = new List<RegionInfo>();
foreach (var item in md) {
ls.Add(new RegionInfo{ RegionDescription = item.RegionDescription , RegionID = item.RegionID});
}
JavaScriptSerializer ser = new JavaScriptSerializer();
var json = ser.Serialize(ls);
return Json(JArray.Parse(json), JsonRequestBehavior.AllowGet);
}
Image error
Please give me advise. Thanks
I'm working on cascading the multi-select based on the values of the data-attributes on another.
I have this method which is called inside the onChanged event of the parent. By parent I mean what to filter the child by i.e
Parent = Department Multiselect
Child = Staff Multiselect.
The child element has a data attribute of data-departmentid.
function cascadeMultiselect(control, targetControl, key) {
this.control = control;
this.targetControl = targetControl;
this.key = key;
this.toHide = [];
this.toShow =[];
//Get controls selectedIds
this.selectedIds = function() {
var selected = [];
_.each($(this.control + " option:selected"), function(c) {
selected.push($(c).val());
});
return selected;
};
//Now filter
this.filter = function() {
//Get target control attribute values
_.each($(targetControl + " option"), function(tc) {
//Use the val as an identifier
var val = $(tc).val();
var data = $(tc).attr("data-" + key);
data = data.split(",");
var isMatch = anyMatchInArray(data, this.selectedIds());
if(!isMatch){
$(tc).hide();
}
});
}
this.filter();
$(targetControl).multiselect('rebuild');
}
It's being called like so:
onChange: function() {
cascadeMultiselect('#departmentlist', '#stafflist', "DepartmentID");
}
The problem is I can't hide the elements. The filter works just fine, I've tried:
$(tc).hide(); // tc = targetControl option
I've also tried to refresh instead of rebuild.
Since it seems the only way to do this was to store the values of the multiselect, and then remove / add the relevant values.
I decided to use a rudimentary Cache class:
var Cache = (function () {
this.all = [];
function Cache(control) {
this.control = control;
}
Cache.prototype.getAll = function () {
return this.all;
};
Cache.prototype.setAll = function (all) {
this.all = all;
};
return Cache;
})();
Function now looks like:
function cascadeMultiselect(control, targetControl, key, cache) {
this.control = control;
this.targetControl = targetControl;
this.key = key;
this.toHide = [];
this.toShow =[];
//To reset the multiselect
this.reset = function(){
$(targetControl).html('');
$(targetControl).multiselect('dataprovider', cache.all)
}
//Get controls selectedIds
this.selectedIds = function() {
var selected = [];
_.each($(this.control + " option:selected"), function(c) {
selected.push($(c).val());
});
return selected;
};
//Now filter
this.filter = function() {
//Get target control attribute values
_.each($(targetControl + " option"), function(tc) {
//Use the val as an identifier
var val = $(tc).val();
var data = $(tc).attr("data-" + key);
data = data.split(",");
var isMatch = anyMatchInArray(data, this.selectedIds());
console.log($(tc));
if(!isMatch){
$(tc).remove();
}
});
}
//If nothing selected then reset the multiselect
if(this.selectedIds().length == 0){
this.reset();
return;
}else{
this.filter();
}
$(targetControl).multiselect('rebuild');
}
When I first populate the multiselect with the dataprovider I add the data to the cache:
if(cache != null){
cache.setAll(this.dataToAdd);
}
I Have the following test:
[Test]
public void Add_New_Group_Should_Return_StatusCode_Created_And_A_Header_Location_To_The_New_Group()
{
var newGroup = new GroupData { ID = 1, UserID = 1, Name = "Group 1", Description = "Description 1" };
var fakeGroupDAL = A.Fake<IGroupDAL>();
var contactGroupsController = new ContactGroupsController(fakeGroupDAL);
SetupControllerForTests(contactGroupsController, HttpMethod.Post);
var response = contactGroupsController.AddGroup(new ContactGroupApiRequest(), newGroup);
Assert.IsTrue(response.StatusCode == HttpStatusCode.Created, "Should have returned HttpStatusCode.Created");
}
Which calls the following configuration method:
private static void SetupControllerForTests(ApiController controller, HttpMethod httpMethod)
{
var config = new HttpConfiguration();
var request = new HttpRequestMessage(httpMethod, "http://localhost/contactgroups");
var route = config.Routes.MapHttpRoute("ContactGroupsApi", "{controller}/{action}/{request}", new { request = RouteParameter.Optional });
var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "contactgroups" } });
controller.ControllerContext = new HttpControllerContext(config, routeData, request);
controller.Request = request;
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
}
I'm trying to test the following action method:
[HttpPost]
public HttpResponseMessage AddGroup([FromUri]ApiRequest req, [FromBody] GroupData contactGroup)
{
if(ModelState.IsValid && contactGroup !=null)
{
_groupDal.AddGroup(contactGroup);
contactGroup.Name = HttpUtility.HtmlEncode(String.Format("{0} - {1}", contactGroup.Name, contactGroup.Description));
var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(contactGroup.Name) };
var uriString = Url.Link("ContactGroupsApi", new { controller = "contactgroups", action = "Group", UserId = contactGroup.UserID, GroupId = contactGroup.ID});
response.Headers.Location = new Uri(uriString);
return response;
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
The action method works perfectly well when called normally, but fails under test because the call to Url.Link returns null.
var uriString = Url.Link("ContactGroupsApi", new { controller = "contactgroups", action = "Group", UserId = contactGroup.UserID, GroupId = contactGroup.ID});
All this code is based very closely on the following article: Unit test ASP.NET Web Api
I suspect that when running under test there is insufficient route table info. Any idea what I'm doing wrong?
I fixed my tests by adding the HttpRouteData to the HttpRouteDataKey property of the controller's HttpRequestMessage. Like this:
controller.Request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
Retrieve code from json.
C#code:-
var collection = getsortcat.Select(x => new
{
idterm = x.IDTerm,
mvo = x.MVO,
pic = x.Pic,
said = x.SAid,
termactive = x.TermActive,
vid = x.Vid,
fvo = x.FVO,
eterm = x.ETerm,
edef = x.EDef,
buse = x.BUse,
bterm = x.BTerm,
idcat = x.TermCat,
items = x.TermCategory1.IDCat,
catname = x.TermCategory1.TermCategory1
});
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(collection);
return Json(output, JsonRequestBehavior.AllowGet);
Javascript Code:-
success: function (e) {
var txt = "'{ data :" + e + "}'";
var obj = eval("(" + txt + ")");
$('#pdata').append(obj.data[0]);
},
Not getting output. Please give me solution how to retrieve data from c# linq object to json to html?
First fix your controller action to get rid of any JavaScriptSerializers and manual plumbing code. Directly return the collection to the Json result:
var collection = getsortcat.Select(x => new
{
idterm = x.IDTerm,
mvo = x.MVO,
pic = x.Pic,
said = x.SAid,
termactive = x.TermActive,
vid = x.Vid,
fvo = x.FVO,
eterm = x.ETerm,
edef = x.EDef,
buse = x.BUse,
bterm = x.BTerm,
idcat = x.TermCat,
items = x.TermCategory1.IDCat,
catname = x.TermCategory1.TermCategory1
});
return Json(collection, JsonRequestBehavior.AllowGet);
Now inside the success callback the e parameter already represents an array of objects that were parsed. You don't need to call any eval. Directly access the elements (by index) and then the properties:
success: function (e) {
var txt = e[0].mvo;
},
you could also loop through the elements:
success: function (e) {
for (var i = 0; i < e.length; i++) {
var element = e[i];
alert(element.idterm);
}
},