Make AJAX request from MS CRM events - dynamics-crm

I need to make an AJAX request to some script from the onSave event of a form in MS CRM Dynamics 4.0.
The code I have now is
var http_request;
// Prepare the xmlHttpObject and send the request.
try{
http_request = new ActiveXObject("Msxm12.XMLHTTP");
}catch(e){
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("Something went wrong..");
}
}
var poststr = "foo=bar";
http_request.open("POST", "/folder/index.html", false);
http_request.setRequestHeader("Content-Type","text/xml; charset=utf-8");
http_request.send(escape(poststr));
// Capture the result.
var resultXml = http_request.responseText;
alert(resultXml);
The alert now gives me the content of a 404-type error. I'm sure the page is there, it's available through the browser.
If I change the
http_request.open("POST", "/folder/index.html", false);
to
http_request.open("POST", "localhost:5555/folder/index.html", false);
the open() fails, saying "Permission denied".
UPDATE (7 dec 2009);
I've created a virtual directory in the ISV folder of CRM and uploated an ASP.NET application. Now, if I go to crm.url.nl:5555/ISV/Default.aspx I get;
'Microsoft.Crm.WebServices.Crm2007.CookieAndSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' doesn't exist.
Parameter name: Microsoft.Crm.WebServices.Crm2007.CookieAndSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
With stacktrace;
[ArgumentException: 'Microsoft.Crm.WebServices.Crm2007.CookieAndSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' doesn't exist.
Parameter name: Microsoft.Crm.WebServices.Crm2007.CookieAndSoapHeaderAuthenticationProvider, Microsoft.Crm.WebServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]
Microsoft.Crm.Authentication.BaseAuthenticationSettings.CreateType(String typeName, Type requiredBaseType) +265
Microsoft.Crm.Authentication.BaseAuthenticationSettings.CreateProvider(String typeName, IDictionary`2 configuration) +28
Microsoft.Crm.Authentication.AuthenticationPipelineSettings.LoadPipeline() +262
Microsoft.Crm.Authentication.AuthenticationPipelineSettings.get_AuthenticationProvider() +16
Microsoft.Crm.Authentication.AuthenticationEngine.Execute(Object sender, EventArgs e) +524
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Does anyone have any idea? The .NET application only writes a single word to Response, so there's nothing special there...

Okay, I found out what the idea is.
If you want to do an AJAX call to a dynamic .NET application from CRM 4.0, here's what you do.
Put the assemblies of your .NET application in the CRMWeb/bin folder in the CRM folder. Put you aspx files in a folder in the ISV folder. I used the stunnware.com folder, because it was there, but you may want to create another folder for the sake of tidyness.
Then, in the onSave (or any on- event) put something like this;
var xmlHttp = null;
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
var getstr = "foo=bar&foo2=bar2";
var url = prependOrgName("/ISV/*YOURFOLDER*/Default.aspx?"+getstr);
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
Of course, if you want CRM to do anything with the response of the xml-request you can use the onreadystatechange for that.
Hope this may help other people. It may seem straightforward, but it took me quite a while before I figured out how to do it (although I knew how to use AJAX and .NET and stuff). I think it's a shame that the CRM developers are left out in the cold by Microsoft. They should really put some more time in documenting the SDK and how to do things like this.

Just thinking of things to try here:
The path to your file is within the CRMWeb directory? Do you have a virtual directory set up or anything?
Does the /folder/index.html work in an IFRAME on the same form?
Maybe try something you know will work just to make sure: http://stackoverflow.com or http://google.com.
Also note that MS recommends putting all customizations in the /ISV/ folder. It shouldn't cause 404 errors, but I'm not sure if they'll consider this unsupported.
Are you really calling a html extension? I believe you need to use prependOrgName (see SDK) for aspx and asmx extensions. I'm not sure if it would cause a 404 or just use your default organization off hand though.

Related

Not a valid resource name of assembly

I'm using Xamarin Studio and GTK#(.NET). I have the following problem:
I've made an app, and I need to(dinamically) download web images(favicons) and display them in a Gtk.Image widget. When I try to do this, I get the following error:
System.ArgumentException: 'myfile.ico' is not a valid resource name of assembly 'myApp, Version=1.0.6742.24722, Culture=neutral, PublicKeyToken=null'.
at at Gdk.PixbufLoader.InitFromAssemblyResource(Assembly assembly, String resource)
at at Gdk.PixbufLoader..ctor(Assembly assembly, String resource)
at at Gdk.Pixbuf..ctor(Assembly assembly, String resource)
at at Gdk.Pixbuf.LoadFromResource(String resource)
It works if i add the favicon, after download,in the resource folder, BUT I need to make this dinamically(if I add a new site, I want to see it's icon there..).
The code:
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri("https://google.com/favicon.ico",
Directory.GetCurrentDirectory() + "\..\..\Res\google.ico");
}
faviconImage.Pixbuf = Gdk.Pixbuf.LoadFromResource("myApp.Res.myfile.ico");
The image is in the folder(i can see it, it's everything ok) but i cannot use it if i don't include it(manually) in the resource folder....
Please help me :'(
Pixbuf.LoadFromResource only loads image data from an embedded assembly resource. You can not add resources to assemblies after they are created.
To create a Pixbuf from a file, use one the its .ator that supports either a file path to the image or one that uses a file stream.
Something like:
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "myDownloadIcon.ico");
var newPixBuf = new PixBuf(filePath):
faviconImage.Pixbuf = newPixBuf;

Rotativa component throws error Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.1 while generating the pdf in MVC project

I have used this component to generate a pdf document based out of a dynamic view content. On testing at DEV and Staging environment, it worked fine and on Production environment, it throws below shown error.
Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Rotativa Version: 1.0.0.0
System.Web.Mvc Version: 5.2.3.0
I have given the binding redirect in web.config as below.
bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0"
Code:
var pdfLetter = new Rotativa.ViewAsPdf(viewName, viewModel);
pdfLetter.FileName = fileName;
pdfLetter.PageSize = Rotativa.Options.Size.A4;
pdfLetter.PageOrientation = Rotativa.Options.Orientation.Portrait;
pdfLetter.PageMargins = new Rotativa.Options.Margins { Left = 4, Right = 1 };
var letterBytes = pdfLetter.BuildPdf(ControllerContext);
return letterBytes;
Web Application is not referencing the 3.0.0.1 version anywhere and still it throws the error. Tried to check the available Stack Overflow threads to fix.
Does anyone encountered this same problem and have any workaround to fix?
There was config value mismatch for MVC redirect between two environments and system was not able to recognize it. Fixed the issue by creating the web.config redirect section from the scratch.

MVC3 Application Inside Webforms Application Routing is throwing a HttpContext.SetSessionStateBehavior Error in IIS7.5

I'm running a mixed MVC Application inside a sub folder of a web forms application.
Everything worked great in VS 2010 debug (Cassini) but when I deployed to IIS7.5
I got the following error:
'HttpContext.SetSessionStateBehavior' can only be invoked before
'HttpApplication.AcquireRequestState' event is raised.
It errors on the last line (httpHandler.ProcessRequest(HttpContext.Current);) in the default.aspx file of the MVC application sub folder.
public void Page_Load(object sender, System.EventArgs e)
{
string pathToRewriteTo = Request.Path.ToLowerInvariant().Replace("default.aspx", "Home/Index");
HttpContext.Current.RewritePath(pathToRewriteTo, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
}
However if I manually navigate to Home/Index from the MVC root folder I can see my application fine from there.
I've looked up the error being thrown and I only find answers dealing with server transfers and not MVC routes.
I have also already checked my IIS7.5 configuration for the route handling module, Application pool running in integrated mode, etc.
Any help would be appreciated.
We faced a similar issue. There are changes to MVCHttpHandler in MVC2 and above.
You need to change it to use httpContext.Server.TransferRequest.
Try the below snippet:
var httpContext = HttpContext.Current;
httpContext.Server.TransferRequest(Url, true); // change to false to pass query string parameters if you have already processed them

mvc 3 Ajax.ActionLink with image not working

I am using vs2010 win7 x64 MVC 3 with regular asp.net development server. And the newest versions of firefox, IE9 and chrome.
I have a strongly typed view and i'm trying to get a ajax extention method working via a slightly modified version of this code asp-net-mvc-ajax-actionlink-with-image that Arjan Einbu provided for mvc 3.
Here is my extension method code located in a Helper.cs file in the App_Code folder of my mvc website.
public static class HelperExtensions
{
public static IHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string titleText, string actionName, object routeValues, AjaxOptions ajaxOptions)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("title", titleText);
var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions).ToHtmlString();
return new MvcHtmlString(link.Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing)));
}
}
In my view I have #model IEnumerable<Models.SpeciesType> at the top defining the model and I'm using ...
#Ajax.ImageActionLink(Url.Content("~/Content/ThumbUp.png"), "Valid/Appropriate", "VoteUp", new {id = item.ID}, new AjaxOptions { HttpMethod = "POST" } );
to insert the ajax action link with an image to allow the user to vote on the item. The above code does not work and no matter what I do it keep giving me error after endless error. The current error it is giving me is ...
Compiler Error Message: CS0121: The
call is ambiguous between the
following methods or properties:
'HelperExtensions.ImageActionLink(System.Web.Mvc.AjaxHelper,
string, string, string, object,
System.Web.Mvc.Ajax.AjaxOptions)' and
'HelperExtensions.ImageActionLink(System.Web.Mvc.AjaxHelper,
string, string, string, object,
System.Web.Mvc.Ajax.AjaxOptions)'
Which means I have two methods with the same name and signature in the same namespace that are conflicting, again impossible because I have only defined it once in one code file. So I thought there might me a caching issue so I did a ctrl+shift+delete in firefox and did a full clear of the cache, history and everything else. Refreshed the page and I get the same error. I also tested it in IE9 and chrome same issue.
I stopped and started the asp.net development server, quit visual studio and restarted still same issue.
Did disk clean up checked everything and ran it. Disk Cleanup did not delete all the files in "C:\Users\Dean\AppData\Local\Temp" So I manually deleted all remaining files in the folder that i could in including the "Temporary ASP.NET Files" folder. Then I ran vs2010 again and ran the website. Again still the same error "CS0121: The call is ambiguous between the following methods ... etc etc"
I can't get rid of this error no matter what I do. This was not the only error I was getting. Before this error started persisting I was also getting errors relating to mvc not being able to find a ImageActionLink method with the right signature namely
ImageActionLink(this AjaxHelper<IEnumerable<SpeciesType>> helper, etc etc
that error I assume was relating to the fact that I am using a strongly typed view.
So to try and get rid of the "call is ambiguous" error I commented out the entire ImageActionLink method and recompiled and ran the website again. I got this error
Compiler Error Message: CS1061:
'System.Web.Mvc.AjaxHelper>'
does not contain a definition for
'ImageActionLink' and no extension
method 'ImageActionLink' accepting a
first argument of type
'System.Web.Mvc.AjaxHelper>'
could be found (are you missing a
using directive or an assembly
reference?)
That error totally makes sense because the ImageActionLink no longer exists. So next thing I did was un-comment the ImageActionLink method recompile and run the website again. And sure enough the same "call is ambiguous" error.
I'm at a loss. I've done everything I can think of to clear various cache's to rule that out, comment and un-comment out pieces of code and test what part breaks. But I'm stuck not being able to get passed the "call is ambiguous" error.
Anyone have any ideas how to fix this "call is ambiguous" error so I can get on to asking why I can't seem to get a simple ajax extension method working ?
I got rid of the "call is ambiguous" error. What happened was I copied Arjan Einbu's mvc 3 version of the code found here asp-net-mvc-ajax-actionlink-with-image.
Then I created a new class in visual studio in the App_Code folder and did a ctrl+a ctrl+v and replaced all the pre generated class template code with just the HelperExtensions class. The problem was that I did not wrap the HelperExtensions with a namespace that matched the website namespace.
Something about how asp.net compiles code files without namespaces was screwing it up. I'm asuming it's probably because the code is compiled in the main website dll at build time and then when asp.net runs it compiles any code files it finds in the app_code folder thus two classes with the same name and same method name or some such.
Anyway now that I have solved that aggravation, I run my website and I get the fallowing error ...
Compiler Error Message: CS1061: 'System.Web.Mvc.AjaxHelper<IEnumerable<Models.SpeciesType>>' does not contain a definition for 'ImageActionLink' and no extension method 'ImageActionLink' accepting a first argument of type 'System.Web.Mvc.AjaxHelper<IEnumerable<Models.SpeciesType>>' could be found (are you missing a using directive or an assembly reference?)
The error reads as though it's finding the ImageActionLink method but the first parameter on the ImageActionLink method is not of the type AjaxHelper<IEnumerable<Models.SpeciesType>>
The error does not quite make sense. Yes the first parameter on the ImageActionLink method is of type AjaxHelper but not of the generic AjaxHelper type. So I tried to modify the ImageActionLink method declaration like so
public static IHtmlString ImageActionLink(this AjaxHelper<IEnumerable<SpeciesType>> helper, string imageUrl, string titleText, string actionName, object routeValues, AjaxOptions ajaxOptions)
But I still get the same error. The first parameter on ImageActionLink is of type AjaxHelper but it's defined "this AjaxHelper helper" meaning it's a extension method that is supposed to extend the AjaxHelper class.
I don't really need the #model IEnumerable<Models.SpeciesType> at the top of my index.cshtml file so I removed it and tried to run the app again with the same error only this time it's
Compiler Error Message: CS1061: 'System.Web.Mvc.AjaxHelper<dynamic>' does not contain a definition for 'ImageActionLink' and no extension method 'ImageActionLink' accepting a first argument of type 'System.Web.Mvc.AjaxHelper<dynamic>' could be found (are you missing a using directive or an assembly reference?)
Anyone know why I'm getting this error? And how to fix it?
Where in Web.config have you added namespace (you are using razor views) ? To pages or to
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="toolbox" />
<add namespace="aa.App_Code"/>
</namespaces>
</pages>
</system.web.webPages.razor>
try adding here, modify view (add some tag), and check if it works.

Problems rendering usercontrol with Charts to PDF

I am trying to render the context of an usercontrol to a PDF document. The usercontrol contains some charts (default asp.net charts):
// Getting the content from the usercontrol
myUsercontrol.Visible = true;
StringBuilder content = new StringBuilder();
StringWriter tw = new StringWriter(content);
HtmlTextWriter hw = new HtmlTextWriter(tw);
myUsercontrol.RenderControl(hw);
myUsercontrol.Visible = false;
// Generating the PDF
But sometimes I am getting an error with myUsercontrol.RenderControl(hw):
"error executing child request for chartimg.axd.".
I am not getting this error all the time. Sometimes it generates the PDF but then there is missing a chart (Missing image).
Anyone know what the problem could be and how to solve it?
Thanks very much in advance!
I found the problem, i have forgotten to add POST to the httphandler for the Chart in System.web in web.config. I had added it to the httphandler in Webserver but not in web and it was web I used for development :-)
<add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

Resources