Crystal Reports Images not loading in ASP.NET MVC - asp.net

I'm using Crystal Reports in a Webform inside of an MVC application. Images in the reports are not being displayed, however, on both the ASP.NET Development Server and IIS 7 (on Win7x64).
I know from a number of other questions similar to this that the CrystalImageHandler HTTP Handler is responsible for rendering the image, but I've tried all of the usual solutions to no avail.
So far, I have
Added the following to my appSettings (via http://www.mail-archive.com/bdotnet#groups.msn.com/msg26882.html)
<add key="CrystalImageCleaner-AutoStart" value="true" />
<add key="CrystalImageCleaner-Sleep" value="60000" />
<add key="CrystalImageCleaner-Age" value="120000" />
Added the following httpHandler to system.web/httpHandlers (via https://stackoverflow.com/questions/2253682/crystal-report-viewer-control-isnt-loading-the-images-inside-the-report)
<add verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=12.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
Added the following to my Global.asax.cs (via Crystal Reports Images and ASP.Net MVC)
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
and
routes.IgnoreRoute("CrystalImageHandler.aspx");
Any ideas as to why the images still 404?

I had similar problem. This helped me.
routes.IgnoreRoute("{*allaspx}", new { allaspx = #".*(CrystalImageHandler).*" });

I've tried the multitude of ways this can supposedly be made to work. None did. So I eventually settled on cheating:
public class CrystalImageHandlerController : Controller
{
//
// GET: /Reports/CrystalImageHandler.aspx
public ActionResult Index()
{
return Content("");
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
var handler = new CrystalDecisions.Web.CrystalImageHandler();
var app = (HttpApplication)filterContext.RequestContext.HttpContext.GetService(typeof(HttpApplication));
if (app == null) return;
handler.ProcessRequest(app.Context);
}
}
I added a route to this controller matching what Crystal expects (./CrystalImageHandler.aspx) and used this controller to invoke the handler when the action is executed. Not pretty, but functional.

Have you tried adding it to system.webServer/handlers? That should fix it on IIS7 but it is strange it doesn't work on the development server w/o that.

Add this in RouteConfig.cs file
routes.IgnoreRoute("Reports/{resource}.aspx/{*pathInfo}");
Note
"Reports" is the folder name which contains the aspx file of report viewer
change this folder name as per your application

Related

How to use Url route url with parameters

i have a page with ~/x.aspx with urlmappings :
<add url="Home" mappedUrl="~/x.aspx" />
what i want is when calling ~/x.aspx?type=y then url still display Home
is there any way to do that
<add url="Home" mappedUrl="~/x.aspx" />
<add url="Home" mappedUrl="~/x.aspx?type=y" />
If you're using Web Forms, you can use the following tutorial. Basically the "type" could be a list of optional check boxes and the complete URL with parameters could be constructed in your code-behind.
Walkthrough: Using ASP.NET Routing in a Web Forms Application
For MVC, see the following question:
Routing with Multiple Parameters using ASP.NET MVC
I haven't work with mappings in the web.config but apparently is not possibly to use wildcards/regex
But you can do that by overwriting in your Global.asax the method Application_Start
protected void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
// routing segment variable: {}
routes.MapPageRoute(null, "home", "~/Pages/x.aspx");
routes.MapPageRoute(null, "home/{type}", "~/Pages/x.aspx");

Get value from web.config applicationSettings into ASP.NET markup

I might be completely off track by now, so I will just ask this here so someone can help me.
What I want to do, is to insert a value from my web.config, stored in an applicationSettings area, into my aspx markup. Specifically I want to reade a URL from config. This is the configSection setup I use
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=123456">
<section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=12345" requirePermission="false" />
</configSections>
Later in that file are the actual settings like so:
<applicationSettings>
<MyApp.Properties.Settings>
<setting name="ImagesUrl" serializeAs="String">
<value>http://resources/images/</value>
</setting>
Now I want to reference the above value in markup like this:
<asp:Image ID="Image1" runat="server" ImageUrl="<%$AppSettings:ImagesUrl%>/Image1.jpg
I know there's an expression available <%$ AppSettings: ImagesUrl %>, but I'm not using the appsettings part of web.config, rather the configSection.
EDIT:
I believe I can only do it with ExpressionBuilder, because I have to concatenate the string with the individual image name. I changed the example above to reflect that.
I like Bert Smith Code Solution below for accessing the config section, only I need to put it in an expression builder.
I'm stuck at overriding the GetCodeExpression method from where I would call the Configuration Manager, but I don't understand how to build an expression the parameters.
public class SettingsExpressionBuilder: ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
return ??
}
EDIT
The result looks like this, and works for all kinds of files, not just images:
<asp:ScriptReference Path='<%$Code:GetAppSetting("ResourcesUrl","JS/jquery/jquery.jqplot.js")%>'
and I simply used the example from Microsoft to return any kind of code from the expression builder:
return new CodeSnippetExpression(entry.Expression);
And GetAppSetting is a method in my custom Page class.
Typically you would create a custom settings class to read these values out as this artical describes. Personally, I would just use the appSettings as suggested above as this is existing functionality and for what your doing would on the surface seem adequate.
However, not knowing your circumstances, what your attempting to do could be solved without the custom settings like so:
In the code behind I created a protected function to retrieve the setting
protected string GetCustomSetting(string Section, string Setting)
{
var config = ConfigurationManager.GetSection(Section);
if (config != null)
return ((ClientSettingsSection)config).Settings.Get(Setting).Value.ValueXml.InnerText;
return string.Empty;
}
Then in the aspx markup I call this function
<div>
<label runat="server" id="label"><%=GetCustomSetting("applicationSettings/MyApp.Properties.Settings", "ImagesUrl") %></label>
</div>
Hope this helps.
Follow Up:
The CodeExpression will look something like this:
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
{
var config = ConfigurationManager.GetSection("applicationSettings/MyApp.Properties.Settings");
return new CodePrimitiveExpression(((ClientSettingsSection)config).Settings.Get(entry.Expression).Value.ValueXml.InnerText);
}
In my Test, I created a class called CustomSettingsExpressionBuilder and added it to the App_Code folder. Added the configuration for the custom express to the web.config and called it from aspx like so:
<asp:Label ID="Label1" runat="server" Text="<%$CustomSettings:ImagesUrl %>"></asp:Label>
Does it has to be in markup? Why don't you set it in code-behind.
Image1.ImageUrl= //fetch your settings here.
One another way would be defining a property or static method in your code-behind and then using that in the markup.
I'm not sure about the ASP.NET bit of it, but if this was normal code you'd do MyApp.Properties.Settings.Default.ImagesUrl, so try
<asp:Image ID="Image1" runat="server"
ImageUrl="<%$MyApp.Properties.Settings.Default.ImagesUrl%>
It would definitely be easier to store this in <appSettings> though.

How to create facebook application via Facebook Developer Toolkit

I'm trying to create a basic application, i created facebook application before but everything has been changed :(
I looked every where to create a basic application, but now i'm getting mad because there isn't any working sample. Because of the changed links, facebook api changes, facebook wiki changes i couldn't find a working copy.
I wonder if anyone can help me to write a basic app that gets permission to write user name to screen in facebook developer toolkit asp.net. I looked computerbeacon.net, codeplex, and some other pages but i couldn't succeed, so please don't give me the links :)
Edit: I' m adding some screenshots and some codes, it will may be help you to find my problem.
Here some screenshots from fb;
This is the core settings,
This is the Facebook integration settings,
Web.config file
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="FaceBookAPIKey" value="MyapiKey"/>
<add key="FaceBookSecretKey" value="MyapiSecret"/>
</appSettings>
<system.web>
<compilation debug="false" targetFramework="4.0" />
</system.web>
</configuration>
My Default.aspx file;
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Assembly="Facebook.Web" Namespace="Facebook.Web" TagPrefix="cc1" %>
<cc1:CanvasFBMLLoginControl ID="CanvasFBMLLoginControl1" runat="server" RequireLogin="true" />
Result;
Thanks
I faced the same problems.
please make sure that
please fill canvas url with your webapp correct URL when you create facebook application
I paste here the following running example that update my status in facebook profile
the following code in markeup
<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
<form method="post">
<input type="submit" value="Submit Comment" />
<%--<fb:login-button></fb:login-button>
<fb:prompt-permission perms="status_update"> Grant permission for status updates </fb:prompt-permission>
</form>
and the following in form page to send status
/// <summary>
/// To send status to your facebook account
/// </summary>
/// <param name="statusMessage">status message</param>
public bool publishToFaceBook(string statusMessage)
{
//please Change call back url in FB app accoroding to your web site application
Facebook.Rest.Api Api;
Facebook.Session.ConnectSession _connectSession;
_connectSession = new Facebook.Session.ConnectSession(ConfigurationManager.AppSettings["FaceBookAPIKey"], ConfigurationManager.AppSettings["FaceBookSecretKey"]);
bool sucess=false;
if (_connectSession.IsConnected())
{
try
{
Api = new Facebook.Rest.Api(_connectSession);
Facebook.Schema.user u = Api.Users.GetInfo();
Facebook.Schema.user_status _status = new Facebook.Schema.user_status();
Api.Users.SetStatus(statusMessage);
sucess = true;
}
catch (Exception ex)
{
sucess = false;
}
}
return sucess;
}
I hope that help you
Best Regards,
Mohammed Thabet Zaky

Turn off input validation for a single field

I've got an ASP.NET 4 site on which I want to allow people to put '<' in their password. However, .NET gets in the way by blocking (what it sees as) an attempt to put HTML in a form field. I know I can turn off input validation entirely, but I only want to turn it off for this one field. Does anyone know an easy way to do that?
This is now possible with .NET 4.5.
Update your Web.config:
<httpRuntime targetFramework="4.5" requestValidationMode="4.5" />
Then set ValidateRequestMode="Disabled" on your password controls:
<asp:YourControl id="YourControl" runat="server" ValidateRequestMode="Disabled"/>
Note - after updating web.config, you might run into the error WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. See ASP.Net 2012 Unobtrusive Validation with jQuery for more info on that.
More info on RequestValidationMode 4.5: requestValidationMode 4.5 vs 2.0
You can only turn off input validation for the entire page. The only solution I can think of is to turn off the input validation, and then scrub all the other (non-password) input fields using something like Anti-XSS.
You can turn input validation off for the single MVC action using the ValidateInputAttribute. Since you're only accepting username/password (I would assume) you should be able to scrub input yourself of any invalid characters. Use the Microsoft Web Protection Library to do that.
Note in ASP.NET 4 and higher to get ValidateRequest in the #Page directive to work you need to add <httpRuntime requestValidationMode="2.0" /> to web.config. See this page for details:
http://www.asp.net/whitepapers/aspnet4/breaking-changes
But this is my preferred approach:
namespace Controls
{
public class HtmlTextBox : TextBox
{
protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
{
bool res = base.LoadPostData(postDataKey, postCollection);
Text = Text.Replace("<", "<").Replace(">", ">").Replace("&", "&");
return res;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "htmlTextBox" + UniqueID, "try { var item = document.getElementsByName('" + UniqueID + "')[0]; item.value = item.value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); } catch (err) {}");
}
}
}
And then register the control in web.config:
<system.web>
<pages>
<controls>
<add tagPrefix="uc1" namespace="Controls" />
</controls>
</pages>
</system.web>
This way you can just use <uc1:HtmlTextBox runat="server" /> if you want to allow the textbox to post html, but other controls on the page will still be blocked from posting html unlike the approach of turning ValidateRequest off.
This is possible. Just add [AllowHtml] on the property that should not be validated.
see ValidateInputAttribute does not contain a definition for Exclude

ASP.Net - How can I allow imported script files be viewed by unauthenticated users when using Forms Authentication?

I'm using ASP.Net and forms authentication. When a user is directed to the Login Page I get a JavaScript error:
Message: Syntax error Line: 3 Char: 1
Code: 0 URI:
http://localhost:49791/login.aspx?ReturnUrl=%2fWebImageButton.js
This is because I am using a Custom Image Button in a separate Web Control Project control that adds a ScriptReference to the page:
public class WebImageButton : LinkButton, IScriptControl, IButtonControl
{
protected override void OnPreRender(EventArgs e)
{
// Link the script up with the script manager
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
scriptManager.RegisterScriptControl(this);
scriptManager.Scripts.Add(new ScriptReference("<snip>.WebImageButton.js", "<snip>"));
}
base.OnPreRender(e);
}
}
If I add the following rule into my Web.Config, then the file is successfully imported:
<location path="WebImageButton.js">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
This isn't very good as I have a number of custom controls that do the same thing, and I don't particularly fancy authenticating each of their js files individually.
Is there no way that I can declare that all imported script references should be allowed? I tried authorising the WebResource.axd file in-case that allows it, but the page itself (when rendered) physically references the WebImageButton.js file.
The ideal scenario would be something like the following:
<location path="My.WebControlLibraryProject.Controls">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Is there any way to achieve this without listing each file?
EDIT: Just to be clear, these script files are in another project and are not in my actual web project. I know how to declare the location paths of directory paths to include a large number of files in one wack, but I can't figure out how to authenticate automatic script references, which are from embedded resources.
Is the WebImageButton.js an embedded resource? As I've seen, you had implemented IScriptControl. Thus, you must return all of script references on the IScriptControl.GetScriptReferences. I think an embedded resource never be authorized. I use some of custom controls in different situation and don't have any problem. I'm wondering that script manager references to WebImageButton.js directly, and not in form of .axd file. So, I think the problem is arising from your resource file.
public class WebImageButton : LinkButton, IScriptControl, IButtonControl
{
protected ScriptManager ScriptManager
{
get
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager == null)
{
throw new System.Web.HttpException("<snip>");
}
return scriptManager;
}
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
this.ScriptManager.RegisterScriptControl<WebImageButton>(this);
}
#region IScriptControl Members
public System.Collections.Generic.IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
yield break;
}
public System.Collections.Generic.IEnumerable<ScriptReference> GetScriptReferences()
{
yield return new ScriptReference("<snip>.WebImageButton.js", "Assembly Name");
}
#endregion
}
This is just a guess - have you tried putting in a wildcard in the location path? Perhaps something like < location path="*.js">?
You can specify a generic location and put all your scripts there so that all the scripts that don't require authorization will pass. You just need to change the path to whatever folder you want it to be and put the scripts there.
That will work for not only scripts, but other resources as well, such as images, style sheets, etc.

Categories

Resources