Ashx handler cannot be used through an <asp:Image> control - asp.net

In an ASP.NET 3.5 application, I have created an ashx handler as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Services;
namespace TestWebConfig
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpg";
BinaryReader br = new BinaryReader(File.Open( #"d:\Temp\images\AutumnLeaves.jpg", FileMode.Open ));
int bufferLength = 1000;
do
{
byte[] buffer = br.ReadBytes(bufferLength);
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
if (buffer.Length < bufferLength)
{
break;
}
} while (true);
br.Close();
}
public bool IsReusable
{
get
{
return true;
}
}
}
}
In an aspx page, if I specify:
<img alt="alt2" src="Handler1.ashx" style="border-width:0px"/>
then the web page is loaded into the browser together with the image. On the other hand, if I use:
<asp:Image ID="Image2" runat="server" />
and in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
Image2.ImageUrl = "Handler1.asxh";
}
then the Image2 control does not load the picture, although the associated html code looks alike. Only the alt text is shown. What's wrong?
Thanks

For one thing in your Page_Load it looks like you've given it the wrong extension, but I don't think that's the problem.

Related

Unable to access a file to be deleted in a qr code programme

I have a qr code asp.net web form and I am getting an error
System.IO.IOException: 'The process cannot access the file 'C:\Users\Asus.DESKTOP-BTB81TA\Desktop\bikestop\bikestop\images\qr code stuff\fileName.png' because it is being used by another process.'
in one of my lines :
File.Delete(filePath2);
Here is the full code :
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.IO; //For MemoryStream
using System.Web.Services; //For WebMethod attribute
using Bytescout.BarCode;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Text;
using System.IO;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using ZXing;
using ZXing.Aztec;
namespace bikestop
{
public partial class bookRide : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
// int i = 0;
protected void Scan_Click(object sender, EventArgs e)
{
Rectangle rect = new Rectangle(0, 0, 2000, 1000);
string filePath = AppDomain.CurrentDomain.BaseDirectory;
string filePath2;
filePath2 = #"" + filePath + "\\images\\qr code stuff\\fileName.png";
//do stuff
using (Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);
}
if (System.IO.Directory.Exists(filePath2) == true)
{
bmp.Save(filePath2, ImageFormat.Png);
bmp.Dispose();
}
else
{
File.Delete(filePath2);
bmp.Save(filePath2, ImageFormat.Png);
bmp.Dispose();
}
try
{
IBarcodeReader barcodeReader = new BarcodeReader();
var barcodeBitmap = (Bitmap)Bitmap.FromFile(filePath2);
var barcodeResult = barcodeReader.Decode(barcodeBitmap);
Output.Text = barcodeResult.Text;
Output.NavigateUrl = barcodeResult.Text;
}
catch
{
Output.Text = "No barcode found";
}
}
}
}
}

Consuming pipl api in asp.net

i am having trouble configuring this API
https://pipl.com/dev/
i have this code in page load event, but the problem is that it keep on loading the page once i click on "veiw page in browser".
protected void Page_Load(object sender, EventArgs e)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
SearchAPIRequest req = new SearchAPIRequest(email: "clark.kent#example.com");
SearchAPIResponse resp = await req.SendAsync();
Console.Out.WriteLine(resp.Image.GetThumbnailUrl(200, 100, true, true));
Console.Out.WriteLine(resp.Name);
Console.Out.WriteLine(resp.Education);
Console.Out.WriteLine(resp.Username);
Console.Out.WriteLine(resp.Address);
var jobs = resp.Person.Jobs.Select(j => j.ToString());
Console.Out.WriteLine(String.Join(", ", jobs));
Console.Out.WriteLine();
var relationships = resp.Person.Relationships.Select(r => r.Names[0]);
Console.Out.WriteLine(String.Join(", ", relationships));
Console.Out.WriteLine();
}
Am i missing some code ? or any thing else.. please guide.
PS: I have already installed their package with "PM> Install-Package piplclient"
The ASPX page needs to have "Async=true" in order to use an async method. The following is an example backend C# file:
using Pipl.APIs.Search;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : Page
{
protected async void Page_Load(object sender, EventArgs e)
{
SearchAPIRequest request = new SearchAPIRequest(email: "clark.kent#example.com");
try
{
var response = await request.SendAsync();
Response.Write(response.Name.ToString());
}
catch (SearchAPIError ex)
{
Console.Out.WriteLine(e.ToString());
}
catch (IOException ex)
{
Console.Out.WriteLine(e.ToString());
}
}
}
}

asp.net - object reference not set to an instance of an object for master page cs file

This is the code to my Master Page cs file. For some reason when I run my default page, I get an error that says "object reference not set to an instance of an object."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Theming.MasterPages
{
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string selectedTheme = Page.Theme;
HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
if (preferredTheme != null)
{
selectedTheme = preferredTheme.Value;
}
if (!string.IsNullOrEmpty(selectedTheme))
{
ListItem item = ThemeList.Items.FindByValue(selectedTheme);
if (item != null)
{
item.Selected = true;
}
}
}
switch (Page.Theme.ToLower())
{
case "darkgrey":
Menu1.Visible = false;
TreeView1.Visible = true;
break;
default:
Menu1.Visible = true;
TreeView1.Visible = false;
break;
}
}
protected void ThemeList_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie preferredTheme = new HttpCookie("PreferredTheme");
preferredTheme.Expires = DateTime.Now.AddMonths(3);
preferredTheme.Value = ThemeList.SelectedValue;
Response.Cookies.Add(preferredTheme);
Response.Redirect(Request.Url.ToString());
}
}
}
The error appears to be at the switch statement but I can't figure out why. I've read on other posts that the value is assigning to the variable as null but I don't know why; I've got dark grey as an app theme. If anyone could please help me it would be very much appreciated.
I don't see Menu1 or TreeView1 defined anywhere in your markup. If those are in a content page, you can't access those in the MasterPage code-behind (there may be a way, but you can't directly access them the way you're trying to).

AjaxPro for .NET

I am new to Ajax .I have used AjaxPro In ASPX page for executing method .I have used below code for .NET 2.0
In ASPX:
$(function() {
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function(event, ui) {
var order = $('#sortable').sortable('serialize');
var retStr = SortTest.Save(order);
}
});
$( "#sortable" ).disableSelection();
});
</script>
In CS file:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using Ajaxpro;
public partial class SortTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(SortTest));
}
[AjaxPro.AjaxMethod]
public string Save(string corder)
{
return "Test";
}
}
Its working fine,but when i using in .NET 1.1 (AjaxPro.JSON.dll),its not working and even though i didn't get how to register.Plz do help me ajaxpro for .NET1.1 .
as i see in your there is no namespace. try to use namespace first. then Call your Ajax method by using Namespace.ClassName. some thing like this.
[AjaxNamespace("SortNameSpace")]
public partial class SortTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(SortTest));
}
[AjaxPro.AjaxMethod]
public string Save(string corder)
{
return "Test";
}
}
while calling from javascript try like this
var retStr = SortNameSpace.SortTest.Save(order).value; //do something with returned value

Add additional content into a known content placeholder from a user control

I have a UserControl that has some javascript I'd like to inject into a known ContentPlaceHolder.
I was hoping to do something like the following except when I append to add the control to found control I get an exception which says I cannot modify the control collection in the Init, Load or PreRender events:
"UserControl.ascx"
<%# Control Language="C#" %>
<asp:Checkbox runat="server" id="checkBox"/>
<app:JavascriptInjector runat="server" InjectInto="ScriptPlaceHolder">
$(function(){ $('#<%= checkBox.ClientID %>').click(function() { ... });
</script></app:JavascriptInjector>
"JavascriptInjector.cs"
using System;
using System.Diagnostics;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
public class JavascriptInjector : PlaceHolder
{
public string InjectInto
{
get { return this.ViewState["InjectInto"] as string; }
set { this.ViewState["InjectInto"] = value; }
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreRender += this.__PreRender;
}
private void __PreRender(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.InjectInto))
{
goto performRegularlly;
}
var injectInto = this.FindControlRecursively(this.Page);
if (injectInto == null)
{
goto performRegularlly;
}
injectInto.Controls.Add(this);
return;
performRegularlly:
Debug.WriteLine("performing regularlly");
}
private Control FindControlRecursively(Control current)
{
var found = current.FindControl(this.InjectInto);
if (found != null)
{
return found;
}
foreach (var child in current.Controls.Cast<Control>())
{
return this.FindControlRecursively(child);
}
return null;
}
}
I figured it out. The following JavascriptInjector class will work, although I don't know what the implications are of calling the render method in the PreRender. Also think I may need to do something to figure out which type of HtmlTextWriter that the base application is using.
"JavaScriptInjector.cs"
using System;
using System.IO;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
public class JavascriptInjector : PlaceHolder
{
private bool performRegularlly;
public string InjectInto
{
get { return this.ViewState["InjectInto"] as string; }
set { this.ViewState["InjectInto"] = value; }
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreRender += this.__PreRender;
}
protected override void Render(HtmlTextWriter writer)
{
if (this.performRegularlly)
{
base.Render(writer);
}
}
private void __PreRender(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.InjectInto))
{
goto performRegularlly;
}
var injectInto = this.FindControlRecursively(this.Page);
if (injectInto == null)
{
goto performRegularlly;
}
performRegularlly = false;
using (var stringWriter = new StringWriter())
using (var writer = new HtmlTextWriter(stringWriter))
{
base.Render(writer);
writer.Flush();
injectInto.Controls.Add(new LiteralControl(stringWriter.GetStringBuilder().ToString()));
}
this.Controls.Clear();
return;
performRegularlly: this.performRegularlly = true;
}
private Control FindControlRecursively(Control current)
{
var found = current.FindControl(this.InjectInto);
if (found != null)
{
return found;
}
foreach (var child in current.Controls.Cast<Control>())
{
return this.FindControlRecursively(child);
}
return null;
}
}

Resources