DotNet.Highcharts Package Issues - asp.net-mvc-4

I am following a tutorial how-to-use-highcharts-js-with-asp-net-mvc-4
and when I build the application I receive the error
The Type or namespace name 'DotNet' could not be found (are you missing a using directive or and assembly reference?)
I have in my controller
using HighChart.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Highcharts;
using DotNet.Highcharts.Helpers;
using DotNet.Highcharts.Options;
using DotNet.Highcharts.Enums;
In this the DotNet has a blue squiggly under it.
and the reference "DotNet.Highcharts" in the my references folder.
I am using VS 2012 Professional (if that matters)
Do I need to add something in my webconfig that I am missing or do I need to set a reference path? I have used nuget packages before and not ran across this problem so not sure what I need to do.
What I have done.
Restarted VS
Closed / Reopen project
Start from scratch project (mvc 4 empty) and added in DotNet.Highcharts and Jquery packages from nuget and followed the tutorial I listed above.
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HighChart.Models
{
public class TransactionCount
{
public string MonthName { get; set; }
public int Count { get; set; }
}
}
Controller
using HighChart.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Highcharts;
using DotNet.Highcharts.Helpers;
using DotNet.Highcharts.Options;
using DotNet.Highcharts.Enums;
namespace HighChart.Controllers
{
public class ChartSampleController : Controller
{
//
// GET: /ChartSample/
public ActionResult Index()
{
var transactionCounts = new List<TransactionCount> {
new TransactionCount() { MonthName="January", Count=30},
new TransactionCount() { MonthName="February", Count=40},
new TransactionCount() { MonthName="March", Count=4},
new TransactionCount() { MonthName="April", Count=35}
};
var xDataMonths = transactionCounts.Select(i => i.MonthName).ToArray();
var yDataCounts = transactionCounts.Select(i => new object[] { i.Count }).ToArray();
//instanciate an object o the highcharts type
var chart = new Highcharts("chart")
//define the type of chart
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })
//overall title of the chart
.SetTitle(new Title { Text = "Incoming Transactions per hour" })
//small lable below the main title
.SetSubtitle(new Subtitle { Text = "Accounting" })
//load the X values
.SetXAxis(new XAxis { Categories = xDataMonths })
//set the Y Title
.SetYAxis(new YAxis { Title = new YAxisTitle { Text = "Number of Transactions" } })
.SetTooltip(new Tooltip
{
Enabled = true,
Formatter = #"function () { return '<b>' + this.series.name + '</b><br/>'+ this.x +': '+ this.y; }"
})
.SetPlotOptions(new PlotOptions
{
Line = new PlotOptionsLine
{
DataLabels = new PlotOptionsLineDataLabels
{
Enabled = true
},
EnableMouseTracking = false
}
})
//load the Y values
.SetSeries(new[]
{
new Series {Name = "Hour", Data = new Data(yDataCounts)},
//you can add more y data to create a second line
// new series { Name = "Other Name", Data = new Data(OtherData)}
});
return View(chart);
//return View();
}
}
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
</head>
<body>
<div>
#model DotNet.Highcharts.Highcharts
<p>My Chart</p>
#(Model)
</div>
</body>
</html>
Any help will be greatly appreciated! Thanks in advance

Did you add the dll to the references? You will need to do this manually by browsing to the dll location.

In my case, I had to specifically download the "Net 4.0" DLL.
https://dotnethighcharts.codeplex.com/releases/view/121251
I honestly thought the nuget package would take care of this

Related

Async in ASP.NET Core MVC

I am new to async programming. FirstOrDefaultAsync is throwing an error
List does not contain a definition for FirstOrDefaultAsync()
Can someone explain me what I am doing wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace PatientManagement.Models
{
public class PatientService : IPatientService
{
private List<Patient> patients;
public PatientService()
{
patients = new List<Patient>()
{
new Patient(){ ID = 1, Name = "Akash", Email = "aakash1027#gmail.com" },
new Patient(){ ID = 2, Name = "John", Email = "John#gmail.com" },
new Patient(){ ID = 3, Name = "Mike", Email = "Mike#gmail.com" },
};
}
public async Task<Patient> GetPatient(int id)
{
return await patients.FirstOrDefaultAsync(x => x.ID == id);
}
}
}
The problem is there really is no FirstOrDefaultAsync method on a List!
Async code is appropriate for cases where you, for instance, cross a boundary and have to wait for a database or some other process to do work. Your case is different: your process actually has to do the work of finding this record in the list. So you should just use the normal synchronous FirstOrDefault:
public Patient GetPatient(int id)
{
return patients.FirstOrDefault(x => x.ID == id);
}

Swagger 2.0 with API 2.o and Odata 3.0

I been trying to implement swagger, through [Swashbuckle][1] on my application, but i get no endpoints at all on my swagger ui, and my doc just returns this
{
"swagger": "2.0",
"info": {
"version": "v1",
"title": "NB.EAM.WebAPI.V4"
},
"host": "localhost:24320",
"schemes": [
"http"
],
"paths": {},
"definitions": {}
}
In my webApiConfig i set the following configuration from following the dummys
var swagConfig = new HttpSelfHostConfiguration("http://localhost:24320");
SwaggerConfig.Register();
WebApiConfig.Register(swagConfig);
using (var server = new HttpSelfHostServer(swagConfig))
{
server.OpenAsync().Wait();
}
My swagger configuration is the standart one created by Swashbuckle:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "NB.EAM.WebAPI.Odata");
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML";
var commentsFile = Path.Combine(baseDirectory, "bin", commentsFileName);
c.IncludeXmlComments(commentsFile);
c.DocumentFilter<ApplyResourceDocumentation>();
c.CustomProvider(defaultProvider => new ODataSwaggerProvider(defaultProvider, c, GlobalConfiguration.Configuration).Configure(odataConfig =>
{
odataConfig.IncludeNavigationProperties();
}));
})
.EnableSwaggerUi(c =>
{
});
Any idea what i might be missing?
Edit:
here is more information about my setting
full code of my WebApiConfig:
public static void Register(HttpConfiguration config)
GlobalConfiguration.Configuration.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor()));
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
var conventions = ODataRoutingConventions.CreateDefault();
conventions.Insert(0, new CompositeKeyRoutingConvention());
conventions.Insert(1, new CompositeKeyNavigationRoutingConvention());
conventions.Insert(2, new CountODataRoutingConvention());
ODataBatchHandler batchHandler = new UnitOfWorkBatchHandler(GlobalConfiguration.DefaultServer);
config.Routes.MapODataServiceRoute("odata", "odata", GenerateEdmModel(), new CountODataPathHandler(), conventions, batchHandler);
config.Filters.Add(new SqlExceptionFilterAttribute());
config.Filters.Add(new FilterInterceptor());
InitContentRepository();
log4net.Config.XmlConfigurator.Configure();
var swagConfig = new HttpSelfHostConfiguration("http://localhost:24320");
SwaggerConfig.Register();
WebApiConfig.Register(swagConfig);
using (var server = new HttpSelfHostServer(swagConfig))
{
server.OpenAsync().Wait();
}
}
public static Microsoft.Data.Edm.IEdmModel GenerateEdmModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.ContainerName = "NBContext";
builder.EntitySet<as_portfolio>("as_portfolio");
builder.EntitySet<cf_usersportfolio>("cf_usersportfolio");
builder.EntitySet<as_locatportfolio>("as_locatportfolio");
builder.EntitySet<ac_bdgaset>("ac_bdgaset");
builder.EntitySet<ac_bdgcc>("ac_bdgcc");
builder.EntitySet<ac_bdgdtl>("ac_bdgdtl");
builder.EntitySet<ac_bdgloca>("ac_bdgloca");
builder.EntitySet<ac_bdgress>("ac_bdgress");
builder.EntitySet<ac_bdgsect>("ac_bdgsect");
builder.EntitySet<ac_bdgwoa>("ac_bdgwoa");
builder.EntitySet<ac_bdgwob>("ac_bdgwob");
builder.EntitySet<ac_bdgwolb>("ac_bdgwolb");
builder.EntitySet<ac_bdgwost>("ac_bdgwost");
builder.EntitySet<ac_bgdcc>("ac_bgdcc");
builder.EntitySet<ac_custome>("ac_custome");
----Very long list of enetitySets
return builder.GetEdmModel();
}
An example of my API
using NB.EAM.DataV2;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http.OData;
namespace NB.EAM.WebAPI.Controllers
{
public class wo_hrtypeController : BaseODataController
{
// GET: odata/wo_hrtype
[Queryable]
public IQueryable<wo_hrtype> Getwo_hrtype()
{
return this.GetWo_HrtypeBll.GetAll();
}
// GET: odata/wo_hrtype(5)
[Queryable]
public SingleResult<wo_hrtype> Getwo_hrtype([FromODataUri] string key)
{
return SingleResult.Create(this.GetWo_HrtypeBll.Find(wo_hrtype =>
wo_hrtype.lb_tyhr == key));
}
}
There is no much information to work there.
We don't know what kind of filters are being aplied on ApplyResourceDocumentation (actually, this class is on the swashbuckle.odata sample proyect and may not fit your necesities:
https://github.com/rbeauchamp/Swashbuckle.OData/blob/master/Swashbuckle.OData.Sample/DocumentFilters/ApplyResourceDocumentation.cs).
We can't also check your entities and function definitions. Check this as an example: https://github.com/rbeauchamp/Swashbuckle.OData/blob/master/Swashbuckle.OData.Sample/App_Start/ODataConfig.cs
And we can't also check if your controllers are defined in a proper way (Methods as verbs. I think custom named methods are only taken into account if they are defined as functions)
I think I just had a similar issue. Try replacing the following line
GlobalConfiguration.Configuration.EnableSwagger(...
with this one:
swagConfig.EnableSwagger(...
The thing is that you should use here the same configuration instance that you pass to the HttpSelfHostServer constructor.
SwaggerConfig.Register(swagConfig); // pass the swagConfig instance to the auto-generated method
WebApiConfig.Register(swagConfig);
using (var server = new HttpSelfHostServer(swagConfig))
{
server.OpenAsync().Wait();
}

Asp.Net MVC Assembly Reference Error

I add the reference system.web.routing dll and I add namespace in all page and also add in web.config page, but here the error in add query string parameter line. Can someone findthe error and tell the answer?
var isDescending = string.CompareOrdinal(Model.SortBy, ViewData["ColumnName"].ToString()) == 0 && Model.SortAscending;
var routeData = new RouteValueDictionary { { "sortBy", ViewData["ColumnName"].ToString() }, { "ascending", !isDescending } };
// Add in the querystring parameters *except* for the paging ones (as sorting should send us back to the first page of data)
routeData.AddQueryStringParameters().ExceptFor("page", "pageSize");
var htmlAttributes = new Dictionary<string, object>();
if (string.CompareOrdinal(Model.SortBy, ViewData["ColumnName"].ToString()) == 0)
{
if (Model.SortAscending)
{
htmlAttributes.Add("class", "sortAsc");
}
else
{
htmlAttributes.Add("class", "sortDesc");
}
}
}
you have added system.web.routing dll and you have added namespace in all page and also add in web.config page you said that fine
so you have to remove this line and run the program surely u will get output
routeData.AddQueryStringParameters().ExceptFor("page", "pageSize");

Filter Column Doesn't Display

I'm trying to set up a basic Mvc.Jquery.Datatables runthrough. I'm getting an extra row at the top which isn't the expected filter row.
There is a script error in the background 'Uncaught TypeError: {object Object} has no method 'columnFilter' as shown below
My Index View is
#using DataTables.Controllers
#using Mvc.JQuery.Datatables
#using Mvc.JQuery.Datatables.Serialization
<script src="~/Content/DataTables/media/js/jquery.js"></script>
<script src="~/Content/DataTables/media/js/jquery.dataTables.js"></script>
<link href="~/Content/DataTables/media/css/demo_table.css" rel="stylesheet" />
<h2>Datatables Demo</h2>
#{
var vm = Html.DataTableVm("table", (HomeController h) => h.GetDataObject(null), null);
vm.ColumnFilter = true;
vm.StateSave = true;
}
#Html.Partial("DataTable", vm)
My controller code is
public class HomeController : Controller
{
public ActionResult Index()
{
var data = DataRepository.GetData();
return View(data);
}
public DataTablesResult<MyDataObject> GetDataObject(DataTablesParam dataTablesParam)
{
var data = DataRepository.GetData().Select(o => o).AsQueryable();
return DataTablesResult.Create(data, dataTablesParam);
}
}
How to get the sort row to show? Thanks.
** Solution **
As suggested, I was missing the script
<script src="~/Content/jquery.dataTables.columnFilter.js"></script>
I think you have a missing script tag for the column filter extension. compare the references against the example page.
also make sure you are using EmbeddedResourceVirtualPathProvider or have the templates project installed

RavenDB Spatial index for LineString

How do I create a RavenDB Spatial Index for LineString geo data ?
I am trying to create a spatial index for LINESTRING of geo data, But search query does not return any data.
Please use following testcase as reference, since I am new to RavenDb I am not sure my search query is correct or bug on RavenDB
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Raven.Abstractions.Indexing;
using Raven.Client;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
namespace GeoDataLoading.Test
{
[TestFixture]
public class SpatialTest
{
public class GeoDocument
{
public string WKT { get; set; }
}
public class GeoIndex : AbstractIndexCreationTask<GeoDocument>
{
public GeoIndex()
{
Map = docs => from doc in docs
select new {_ = SpatialGenerate("WKT", doc.WKT, SpatialSearchStrategy.GeohashPrefixTree)};
}
}
[Test]
public void LineStringsShouldNearest()
{
using (var store = new EmbeddableDocumentStore {RunInMemory = true})
{
store.Initialize();
store.ExecuteIndex(new GeoIndex());
using (IDocumentSession session = store.OpenSession())
{
session.Store(new GeoDocument
{
WKT =
"LINESTRING (-0.20854 51.80315, -0.20811 51.80395, -0.20811 51.80402, -0.20814 51.80407, -0.20823 51.80419, -0.20888 51.80435, -0.20978 51.80455, -0.21033 51.80463, -0.21088 51.80467, -0.2116 51.80463, -0.21199 51.80457, -0.21246 51.80453, -0.2131 51.80448, -0.21351 51.80442, -0.2143 51.80433, -0.21436 51.80372, -0.21454 51.80321, -0.21468 51.80295)"
});
session.SaveChanges();
}
using (IDocumentSession session = store.OpenSession())
{
List<GeoDocument> result = session.Advanced.LuceneQuery<GeoDocument>("GeoIndex")
.WaitForNonStaleResults()
.WithinRadiusOf(1.2, -0.20854f, 51.80315f)
.SortByDistance()
.ToList();
Assert.IsTrue(result.Count > 0);
}
}
}
}
}
public class YourDocumentType_SpatialIndex : AbstractIndexCreationTask<YourDocumentType>
{
public SpatialIndex()
{
Map = documents => from document in documents
select new
{
document.LinkId,
_ = SpatialGenerate(fieldName: "Geometry", shapeWKT: document.Geometry, strategy: SpatialSearchStrategy.GeohashPrefixTree, maxTreeLevel: 12)
};
}
}
Fair warning that I have not tested this.