When i re-publish my project to my host, and try to display my view i get this error about 50% of the times depending on how lucky i am
Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
my view gets called by
#if (Model.Items.Any())
{
var item = Model.Items.FirstOrDefault();
var table = item.GetValue("table");
// Render Action (controllerMethod, ControllerName, UmbracoModelData)
Html.RenderAction(table, "Monitor", new {data = item});
}
and this is my method in the controller that should return my view
public ActionResult Skader(LeBlenderValue data)
{
var jsonString = new WebClient { Encoding = System.Text.Encoding.UTF8 }.DownloadString("myStringHere");
var dbObj = JsonConvert.DeserializeObject<List<SkaderModel>>(jsonString);
var vm = new MonitorTableViewModel(){Skader = dbObj, gridData = data};
return PartialView("~/Views/Partials/Monitor/Skader.cshtml", vm);
}
Related
This exception is thrown when I need to call the Registry of my project and get all services displayed in client.It worked yesterday but dont know why its not working now.Can anyone help with me with this?
This is my method to get all services to client from the registry api
private void btnGetAll_Click(object sender, RoutedEventArgs e)
{
Services services;
User user = User.Instance;
//Api Call is made.
string url = "http://localhost:14470/api/AllServies/ " + Rtoken;
var clinet = new RestClient(url);
var request = new RestRequest();
var response = clinet.Post(request);
List<Services> data = new List<Services>();
data = JsonConvert.DeserializeObject<List<Services>>(response.Content.ToString());
List<Services> gridData = new List<Services>();
foreach (Services line in data)
{
//services = JsonConvert.DeserializeObject<List<Services>>(line);
/*if (services.Status.Equals("Denied"))
{
logout();
break;
}*/
gridData.Add(line);
}
// Services test = serviceInfo.SelectedItem as Services;
serviceInfo.ItemsSource = gridData;
}
This is the all service controller of my registry api
// POST: api/AllServices
[Route("api/AllServies/{token}")]
[HttpPost]
public IHttpActionResult Post([FromBody] int token)
{
//AuthInterface foob = auth.initServerConnection();
// Ilist return for returning list with multple types
//token validation
string validate = foob.Validate(token);
if (validate.Equals("Not Validated"))
{
//if valid token
// path to the text file
string path = "C:\\Users\\ravin\\Desktop\\assignment_1_DC\\Services.txt";
List<string> services = File.ReadAllLines(path).ToList();
List<Rdetails> regservice = new List<Rdetails>();
//checking for every line
foreach (var service in services)
{
//deserlizing text and assigning values to RegistryDetail type object
Rdetails rDetail = JsonConvert.DeserializeObject<Rdetails>(service);
// add details to the created Registry details type list
regservice.Add(rDetail);
}
return Ok(regservice);
}
else
{
// if token is unvalid
Rresponse reg = new Rresponse();
reg.RegStatus = "Denied";
reg.RegReason = "Authentication Error";
List<Rresponse> output = new List<Rresponse>();
output.Add(reg);
return Ok(output);
}
}
}
}
I have an async controller that returns results from a collection.
Sometimes, I will get an intermittent error if I click around the page to fast.
The errors are (in the browser console):
Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR
Or it will return this error from the front-end:
500 : Ajax request has failed
I have tried debugging locally in Visual Studio and stepping through the code, but locally, I don't get any errors and I can't figure out why it's doing it.
I have added a line that checks to make sure the returned collection is not null, so it's not that.
Here is the controller:
[HttpGet("factapi/Factory/{factoryId}/engines")]
public async Task<IActionResult> Get(Int32 factoryId)
{
using (var tran = Session.BeginTransaction())
{
var engineId = page.Assembly.Id.TrimToNull();
if (engineId == null) return NoContent();
var engines = await GetEngines(new Guid(engineId));
if (engines == null)
{
return BadRequest();
}
return Ok(engines);
}
}
This is the async method that gets the engines:
public async Task<IEnumerable<Engine>> GetEngines(Guid id)
{
var engines = new List<Engine>();
engines = await GetEngineList<Engine>(id);
return engines.Where(t => start.LiesBetween(t.BuildTime.AddMinutes( - 7), t.BuildTime.AddMinutes((t.TimeBreak / 60) + 7)));
}
And here is GetEngineList:
public async Task<List<T>> GetEngineList<T>(Guid id)
{
List<T> collectionVal = default(List<T>);
var factoryResponse = await GetList(id);
var fullList = factoryResponse.Results;
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var json = JsonConvert.SerializeObject(fullList);
var final = JsonConvert.DeserializeObject<List<T>>(json, settings);
collectionVal = final;
return collectionVal;
}
Another set of eyes would be welcome! :)
I had place call between two Android devices which is running successfully. Now I want to implement Callback Rest API because of some server side decision before place call. As given in this image, ICE event fire and developer backend respond SVAML response.
Now I want to simply Hangup Call, for this I had done following code :
[System.Web.Http.HttpPost]
public SvamletModel MakeCall(CallbackEventModel model)
{
var sinch = SinchFactory.CreateCallbackResponseFactory(Locale.EnUs);
var reader = sinch.CreateEventReader();
var evt = reader.ReadModel(model);
var builder = sinch.CreateIceSvamletBuilder();
SvamletModel svaml = builder.Hangup().Model;
return svaml;
}
but call still placed. I had also write action class under SvamletModel but same response.
[System.Web.Http.HttpPost]
public SvamletModel MakeCall(CallbackEventModel model)
{
var sinch = SinchFactory.CreateCallbackResponseFactory(Locale.EnUs);
var reader = sinch.CreateEventReader();
var evt = reader.ReadModel(model);
var builder = sinch.CreateIceSvamletBuilder();
SvamletModel svaml = builder.Build().Model;
SvamletActionModel actionModel = new SvamletActionModel();
actionModel.Name = "Hangup";
svaml.Action = actionModel;
return svaml;
}
Note I had followed all steps given in Callback API and https://developers.sinch.com/docs/further-securing-your-sinch-calling-functionality-app-with-rest-api with no success.
Hi your code looks correct, can you capture and send here the HTTP response your backend is sending as response of the ICE POST?
Also add the callID for call.
Sinch Voice & Video Team
Converting return type from SvamletModel to string is working.
So I have changed
[System.Web.Http.HttpPost]
public SvamletModel MakeCall(CallbackEventModel model)
{
var sinch = SinchFactory.CreateCallbackResponseFactory(Locale.EnUs);
var reader = sinch.CreateEventReader();
var evt = reader.ReadModel(model);
var builder = sinch.CreateIceSvamletBuilder();
SvamletModel svaml = builder.Hangup().Model;
return svaml;
}
to
[System.Web.Http.HttpPost]
public string MakeCall(CallbackEventModel model)
{
var sinch = SinchFactory.CreateCallbackResponseFactory(Locale.EnUs);
var reader = sinch.CreateEventReader();
var evt = reader.ReadModel(model);
var builder = sinch.CreateIceSvamletBuilder();
SvamletModel svaml = builder.Hangup().Model;
string json = JsonConvert.SerializeObject(svaml, Formatting.Indented);
return json;
}
I have a controller with the following actions:
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
[Route(
"/MyShop/OrderDetails/CancelOrder",
Name = UrlRouteDefinitions.MyShopOrderDetailsCancelOrder)]
[ValidateAntiForgeryToken]
public IActionResult CancelOrder(MyViewModel viewModel)
{
var isCancelSuccessful = _orderBusinessLogic.CancelOrderById(viewModel.Order.Id);
if (isCancelSuccessful)
{
//to show a success-message after the redirect
this.TempData["SuccessCancelOrder"] = true;
}
return RedirectToRoute(UrlRouteDefinitions.MyShopOrderDetailsIndex, new
{
orderId = viewModel.Order.Id
});
}
Then I also have the following piece of HTML in the View for the Controller mentioned above:
<div class="panel-body">
#if (TempData["SuccessCancelOrder"] != null)
{
//show the message
#TempData["SuccessCancelOrder"].ToString();
}
</div>
Now I'm writing an integration test (code-summary below) to check if the CancelOrder() method works as expected. There I'd like to access the value of the TempData dictionary to check its correctness.
[TestMethod]
public void MyTest()
{
try
{
//Arrange: create an Order with some Products
var orderId = CreateFakeOrder();
//Open the Order Details page for the arranged Order
var httpRequestMessage = base.PrepareRequest(
HttpMethod.Get,
"/MyShop/OrderDetails?orderId=" + orderId,
MediaTypeEnum.Html);
var httpResponse = base.Proxy.SendAsync(httpRequestMessage).Result;
var responseContent = httpResponse.Content.ReadAsStringAsync().Result;
var viewModel = base.GetModel<MyViewModel>(responseContent);
Assert.AreEqual(HttpStatusCode.OK, httpResponse.StatusCode);
//Try to execute a POST to cancel the Order
httpRequestMessage = base.PrepareRequest(
HttpMethod.Post,
"/MyShop/OrderDetails/CancelOrder",
MediaTypeEnum.Html,
httpResponse, content: viewModel);
httpResponse = base.Proxy.SendAsync(httpRequestMessage).Result;
var expectedRedirectLocation = $"{this.RelativeHomeUrl}/MyShop/OrderDetails?orderId=" + orderId;
var receivedRedirectLocation = WebUtility.UrlDecode(httpResponse.Headers.Location.ToString());
//we expect that the Order Details page will be reloaded
//with the ID of the already cancelled Order
Assert.AreEqual(HttpStatusCode.Redirect, httpResponse.StatusCode);
//-----------------------------------------------------------
//here I'm going to re-execute a GET-request
//on the Order Details page.
//
//Then I need to check the content of the message
//that's been written in the TempData
//-----------------------------------------------------------
}
finally
{
//delete the arranged data
}
}
In any case, I don't know how to access it from my integration test. Does anybody know how to do it and if there's a way at all?
Controller.TempData is public so you can easily access it and check if your key/value exists
[TestMethod]
public void TempData_Should_Contain_Message() {
// Arrange
var httpContext = new DefaultHttpContext();
var tempData = new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>());
var controller = new TestController();
controller.TempData = tempData;
// Act
var result = controller.DoSomething();
//Assert
controller.TempData["Message"]
.Should().NotBeNull()
.And.BeEquivalentTo("Hello World");
}
I need to extract the route data (Controller, Action etc) from an arbitrary request path (not related to the current request) such as / or /account/manage. In previous versions of Asp.Net Mvc this could be accomplished like this:
var request = new HttpRequest(null, "http://localhost:3333/Home/About", "testvalue=1");
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
var values = routeData.Values;
// The following should be true for initial version of mvc app.
values["controller"] == "Home"
values["action"] == "Index"
Source
This solution is not optimal since it requires a fully qualified Url instead of just a request path.
You can use TemplateMatcher to extract route values:
public class RouteMatcher
{
public static RouteValueDictionary Match(string routeTemplate, string requestPath)
{
var template = TemplateParser.Parse(routeTemplate);
var matcher = new TemplateMatcher(template, GetDefaults(template));
var values = new RouteValueDictionary();
var moduleMatch = matcher.TryMatch(requestPath, values);
return values;
}
// This method extracts the default argument values from the template.
private static RouteValueDictionary GetDefaults(RouteTemplate parsedTemplate)
{
var result = new RouteValueDictionary();
foreach (var parameter in parsedTemplate.Parameters)
{
if (parameter.DefaultValue != null)
{
result.Add(parameter.Name, parameter.DefaultValue);
}
}
return result;
}
}
And example usage:
var template = "{controller=Home}/{action=Index}/{id?}";
var routeValues = RouteMatcher.Match(template, "<your path>");
See this article: https://blog.markvincze.com/matching-route-templates-manually-in-asp-net-core/