I created a simple API via ASP.NET MVC 4:
public class ActionController : ApiController
{
[WebMethod]
public string getCommunities()
{
try
{
MethodClass method = new MethodClass();
return method.getCommunities();
}
catch(Exception ex)
{
return ex.Message.ToString();
}
}
}
which is trying to call this method in the Method class:
public string getCommunities()
{
return "bbb";
}
but for whatever reason, I get this error:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">cannot parse xml! Check file path</string>
I tried Googling for the error, but came up with nothing, has anyone seen this error before? and how do I fix it?
As already pointed in comments, you are looking for your bug in the wrong place. method.getCommunities() is throwing an error with message "cannot parse xml! Check file path".
Googling your error it seems to me that you are throwing a custom exception: searching for that string in your code may point you to the right place.
As a quick proof of concept I changed the standard API generated by Visual Studio Web API template.
public string Get(int id)
{
try
{
var t = 0;
var i = 1 / t;
return "bbb";
}
catch { return "ABBA"; }
}
which exactly returns the custom error message as xml string
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">ABBA</string>
I attempted to replicate the case you mention by creating simple ActionController.cs in ASP.Net MVC 4 template as follow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Services;
namespace MvcApiApplicationTrial1.Controllers
{
public class ActionController : ApiController
{
[WebMethod]
public string getCommunities() {
try {
MethodClass method = new MethodClass();
return method.getCommunities();
} catch (Exception ex) {
return ex.Message.ToString();
}
}
}
public class MethodClass
{
public string getCommunities() {
return "bbb";
}
}
}
And call it in the web browser (Chrome) with the following url:
http://localhost:56491/api/Action/getCommunities
And get the following correct result:
If you declare, define, and call things right, your code should have no problem at all.
So, I suggest you to re-check your declaration, definition, as well as your calling to the related Controller/Method again. Your problem may lay somewhere else.
And since the error seems to be a custom error, judging from the code posted alone, likely that the problem lays somewhere in your getCommunities method. Check the method, try to find the "cannot parse xml!" text there. Alternatively, but less likely, the error is in the MethodClass constructor. Same thing, check your MethodClass, try to find the "cannot parse xml!" text.
As for the given case as what you have posted in your question, I found no issue at all.
But anything else in between try and "bbb" can also potentially be the source of the created error. Checking the error text would be my first step if there are more things in the try block and I am unsure where the error may actually be generated.
in Global.asax.cs should put code bellow:
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());
and in WebApiConfig code bellow:
config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
Related
I just deployed a new controller to my production environment. For some reason, the controller does not get called. All other controllers on the site work fine. This is the only one that is failing. What I keep getting is the error:
Error rendering controller BlogListing.GetIndex: Could not create
controller: 'BlogListing'. The controller for path '/' was not found
or does not implement IController
I've spent about 3 hours trying to troubleshoot this. I have:
Added debug code into the controller to see if it is in fact being called. My debug statements does not get hit.
Verified the name of the controller is correct
I am using the default MVC routing.
Thinking that it might be a missing dependent dll, I copied all of the dlls from my production environment (where it is not working) to my local environment and it came right up
Checked file system permissions thinking that somehow it couldn't be read.
I did look at other posts regarding similar issues but none of those solutions worked or were not applicable
namespace Portal.Features.Blog.Controllers
{
using Glass.Mapper.Sc;
using Glass.Mapper.Sc.Web.Mvc;
using Sitecore.Data.Items;
using System;
using System.Linq;
using System.Web.Mvc;
using Portal.Foundation.Blog;
using portal.ct.gov.Models;
using Portal.Features.Blog.Models;
using portal.ct.gov.Business;
public class BlogListingController : GlassController
{
public ActionResult GetIndex(string keyword = "", string page = "", string author = "")
{
Sitecore.Diagnostics.Log.Info("Blog Controller found", "portal.ct.gov");
try
{
SitecoreContext scContext = new SitecoreContext();
Item contextItem = scContext.GetCurrentItem<Item>();
Item blogHome = null;
//Get Blog Root
if (contextItem != null)
{
blogHome = contextItem.Axes.SelectSingleItem("ancestor-or-self::*[##templatename = 'Blog Section']");
}
var sKeyword = !string.IsNullOrEmpty(HttpContext.Request.QueryString[Constants.QueryStrings.SearchKeyword]) ? HttpContext.Request.QueryString[Constants.QueryStrings.SearchKeyword] : string.Empty;
var blogAuthor = !string.IsNullOrEmpty(HttpContext.Request.QueryString["author"]) ? HttpContext.Request.QueryString["author"] : string.Empty;
var blogCategory = !string.IsNullOrEmpty(HttpContext.Request.QueryString["category"]) ? HttpContext.Request.QueryString["category"] : string.Empty;
var blogPage = !string.IsNullOrEmpty(HttpContext.Request.QueryString["page"]) ? HttpContext.Request.QueryString["page"] : "1";
var model = GetBlogListing(blogHome, sKeyword, blogCategory, blogAuthor, Convert.ToInt32(blogPage));
return View("/views/blog/BlogResultsMain.cshtml", model);
}
catch(Exception ex)
{
Sitecore.Diagnostics.Log.Error("Error processing bloglisting-->getINdex " + ex.Message, ex, "portal.ct.gov");
return View("/views/blog/BlogResultsMain.cshtml");
}
}
}
Any help is appreciated. Please note that I am using Sitecore CMS.
It is worth checking the cached MVC-ControllerTypeCache.xml file in folder c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\NAMEOFYOURAPP\xxxxx\xxxxxxxx\UserCache\.
If you can't find your controller there, remove the cached xml file and restart your website. More details you can find here
I've been trying to evaluate XSockets but it appears I've hit my first stumbling block pretty early. I can connect to Generic controller just fine but custom controllers do not seem to work at all - I get a custom message: "The handler name was not found in loaded plugins". A Google search shows one other person having this problem in SE, but their solution did not work for me.
I've created a console project and installed the latest XSockets 3.03 from NuGet. My code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XSockets.Core.Common.Socket;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
using XSockets.Core.Common.Socket.Event.Interface;
namespace XSockets2
{
class Program
{
static void Main(string[] args)
{
using (var server = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>())
{
Console.WriteLine("running!");
server.StartServers();
Console.ReadLine();
server.StopServers();
}
}
}
public class TestCont: XSocketController
{
public override void OnMessage(ITextArgs textArgs)
{
this.SendToAll(textArgs);
}
}
}
And my Javascript
function connect2() {
var host = "ws://localhost:4502/testcont";
var conn;
conn = new XSockets.WebSocket(host);
conn.on(XSockets.Events.open, function (clientInfo) {
message(clientInfo.ClientGuid); //appends message to textarea
console.log('Open', clientInfo);
});
conn.on('OnMessage', function (d) {
message(d);
console.log('Message', d);
});
conn.on(XSockets.Events.onError, function (err) {
message(err.CustomMessage);
console.log('Error', err);
});
conn.on(XSockets.Events.close, function () {
message('Closed');
console.log('Closed');
});
First of all the latest version is 3.0.2 (not 3.0.3) but that is not important :)
There is a well known and documented bug in the plugin framework for the latest version. The bug only affect you if you run a console application (or any other *.exe) project since xsockets by default only looks in *.dll and not *.exe.
The issue and work around is described here
But your code will not work anyway since you have an error (from what I can see).
Your controller is named "TestCont" but you connect to "testcont". The connectionstring is case sensitive.
EDIT: I also think you are missunderstanding the method OnMessage since you have added a subscription to that exact name.
I'm trying to read the static securities definition file from the CME, located at:
ftp://ftp.cmegroup.com/fix/Production/secdef.dat.gz
Since they seem to be standard fix messages, I thought I could use QuickFix to help me read them into C# rather than parsing the file myself. I created a test app that basically does what I want, but I'm having 2 issues:
1) I'm getting a QuickFix exception "Invalid message: Header fields out of order" when forming the message from the string. If I set the "validate" boolean to false, this message disappears and the constructor succeeds, but may be an indicator for the next issue.
2) Upon calling p.Crack, I'm getting the QuickFix exception "QuickFix.UnsupportedMessageType", but there doesn't seem to be any indication of what the message type is that is supposedly unsupported.
Anyway, maybe QuickFix wasn't intended to be used in this way, but any ideas on how to get this to work?
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using QuickFix;
namespace TestQuickFix
{
class Program : QuickFix.MessageCracker
{
static void Main(string[] args)
{
int count = 0;
string line;
Program p = new Program();
StreamReader file = new StreamReader(#"C:\secdef.dat");
while (((line = file.ReadLine()) != null && count < 10))
{
// ISSUE #1 REQUIRES false 2ND ARG WHEN CREATING THE MESSAGE
Message m = new Message(line, false);
// ISSUE #2 Exception of type 'QuickFix.UnsupportedMessageType' was thrown.
p.Crack(m, new SessionID("beginString", "senderCompID", "targetCompID"));
}
file.Close();
}
public void OnMessage(QuickFix.FIX50.SecurityDefinition secDef, SessionID sessionID)
{
Console.WriteLine(secDef.ToString());
}
}
}
The messages seems to be in FIX50sp2 format, supported by QuickFIX. (Please take a look at the tag 1128=9).
http://www.onixs.biz/fix-dictionary/5.0.SP2/tagNum_1128.html
BUT every single message seems to be not-well formatted. In the header are missed tag 8 (should be the BeginString), and also the tag 56 (TargetCompID), that are mandatory.
Therefore in order to load a single line in a message you must put the "false" parameter to avoid validation.
I suppose the second error is related to the not-well formatted messages.
After emailing the QuickFix listserv with this question, I was able to get enough information to get this to work. Although each line still seems to be malformed for some reason, if I keep validation off, I can get the parser to do exactly what I need it to with the following simplified code:
using System;
using System.IO;
using QuickFix;
using QuickFix.DataDictionary;
namespace TestQuickFix
{
class Program
{
private const int MAX_LINES = 10;
static void Main(string[] args)
{
DataDictionary dd = new QuickFix.DataDictionary.DataDictionary("fix\\FIX50SP2.xml");
StreamReader file = new StreamReader(#"C:\secdef.dat");
int count = 0; string line;
while (((line = file.ReadLine()) != null && count++ < MAX_LINES))
{
QuickFix.FIX50.SecurityDefinition secDef = new QuickFix.FIX50.SecurityDefinition();
secDef.FromString(line, false, dd, dd);
Console.WriteLine(secDef.SecurityDesc);
}
file.Close();
}
}
}
In the following test program, the error output is correctly written to Error.txt.
using System;
using System.IO;
public class Test{
public static void Main(string[] args){
Console.SetOut(new StreamWriter("Output.txt", true));
Console.SetError(new StreamWriter("Error.txt", true));
int[] test = new int[1];
Console.Error.WriteLine(test[0]);
}
}
However, if we change the line
Console.Error.WriteLine(test[0]);
to
Console.Error.WriteLine(test[7]);
which will cause an exception, the error message for this exception gets printed to the console instead of to the file. How can I programmatically set it up so that the error message for system-thrown exceptions is also redirected to a file?
Simple console redirection (2> or >) is not an option because of the context in which this program is run.
I don't think the Console.SetError method actually changes the "DOS" error output of the application, just where Console.Error outputs. You should try PInvoking SetStdHandle. For example of this, see here: Redirect stdout+stderr on a C# Windows service
I believe, error output doesn't work the way you try using it. It is just a way to output information about some errors. Look at this http://msdn.microsoft.com/en-us/library/system.console.seterror.aspx
If you want to write something about an error, you need to do the next:
Console.Error.WriteLine("Error Log for Application {0}", appName);
so if you want to write info about exceptions to stderr, you need to catch your exceptions and direct its messages to stderr.
...
catch(Exception e) { Console.Error.WriteLine(e.Message); }
Are you looking for something like this?
FileStream errorFileStream = new FileStream("Error.txt", FileMode.OpenOrCreate);
StreamWriter errorStreamWriter = new StreamWriter(errorFileStream);
Console.SetError(errorStreamWriter);
string[] test = new string[2];
test[0] = "Hello";
test[1] = "World";
try
{
Console.WriteLine(test[2]);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
Console.Error.Close();
In Windows Forms I can create a class file called 'Authentication.cs' with the following code:
public class Authentication
{
public string Name;
internal bool Authenticate()
{
bool i = false;
if (Name == "Jason")
{
i = true;
}
return i;
}
}
In WebMatrix, I can insert a new Class file, called 'Authentication.cs', and insert the above code.
And in my default.cshtml file, I do this:
<body>
#{
Authentication auth = new Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp");</p>
}
}
</body>
But it won't work! It works for the WinForms desktop app, but not in WebMatrix. I don't know why it's not working. The error message is:
"The namespace Authenticate does not
exist. Are you sure you have
referenced assemblies etc?"
So, then at the top of my default.cshtml file I tried this:
#using Authentication.cs;
Which led to the exact same error!
There's no documentation that I can find anywhere that tells you how to "include" a class file into your WebMatrix pages.
Any help is appreciated,
Thank you!
You import a namespace, not a file. So; what namespace is Authentication in? For example:
#using My.Utils.Authentication.cs;
Also - you want to drop the ; in the razor call:
<p>#auth.Authenticated("jasonp")</p>
You can also provide the fully qualified name in the code:
#{
var auth = new My.Utils.Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp")</p>
}
}
(aside: are you intentionally calling the same method twice with the same values?)
Just drop the cs file in you App_Code directory
then do something like this
#{
Authentication auth = new Authentication();
if(auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp");</p>
}
}
No need to add a using.
Additionally if you wanted to use a .dll then you would need the using
#using NameSpace.Authenication
#{
Authenticated auth = new Authenicated();
}
#if(#auth.Authenticated("jasonp"))
{
<p>#auth.Authenticated("jasonp")</p>
}
Create a file named linkRef.cs
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class linkRef
{
public linkRef() {
//
// TODO: Add constructor logic here
//
}
}
Put it in a folder App_code then by dot net 2012 publish to bin then upload bin folder