Sometimes Image is not displaying for only one user - asp.net

I am having ASP.NET MVC application in which i am using HTTP handler ashx file to get the image on the page . This image is uploaded by user by scanning the document.
Now my problem is for every user its displaying except one , User is reporting he is not able to see the image even though it was loaded sucessfully , when i checked the logs it shown that server got image.
No exception was logged at the server while converting image too :(
One more thing this is happening frequently , 70% times user is not able to see the image in the page. 30% time he managed to see the image ...
Strange issue
Please advice what could be the issue ?
Below is my code
public class GetImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public GetImage()
{
}
public void ProcessRequest(HttpContext context)
{
if (context != null)
{
if (!string.IsNullOrEmpty(context.Request.Params["side"]))
{
bool isFront = false;
if (context.Request.Params["side"].Equals("Front"))
{
isFront = true;
}
else
{
isFront = false;
}
ICache Cache = CacheManager.SessionCache;
DepositState depState = (DepositState)Cache[Constants.DepositSession];
if (depState != null)
{
byte[] imageByteArray = null;
System.IO.MemoryStream imageMemoryStream = null;
try
{
if (isFront)
{
imageByteArray = System.Convert.FromBase64String(depState.FrontJpegBase64);
}
else
{
imageByteArray = System.Convert.FromBase64String(depState.BackJpegBase64);
}
imageMemoryStream = new System.IO.MemoryStream(imageByteArray);
using (System.Drawing.Image img = System.Drawing.Image.FromStream(imageMemoryStream))
{
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch(Exception ex)
{
Log.Error(Constants.DefaultErrorCode, "Exception occured while converting image to Base 64 in GetImage.ashx.cs" + ex);
}
imageMemoryStream.Close();
context.Response.Flush();
}
else
{
Log.Error(Constants.DefaultErrorCode, " Deposit State object is nullin GetImage.ashx ");
}
}
}
else
{
Log.Error(Constants.DefaultErrorCode, "Context is null in the Process Request ");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

I don't see where you are setting the context.Response.ContentType. I haven't tested this, but I wonder if the missing header would cause unpredictable browser behavior.

Related

How to resolve problem to Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript

[HttpGet("vulnerability")]
public IActionResult vulnerability(string input)
{
object content = 0;
try
{
content = new Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
}
catch (Exception)
{
content = "";
}
return View("Example", new { vuln = content });
}
I'm going to implement a "code injection" vulnerability in .net core.
The vulnerable configuration takes input to input and tries to execute it as an eval.
Yes)
Input: 1+1
Result screen: 2
by the way
Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
An error occurs in the portion. Occurrence Error - CS0712
EvaluateAsync()
Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
An error occurs in the portion. CS0712
EvaluateAsync() Occurrence Error - CS1501
How can I solve this?
I tried to solve the problem by referring to the official document.
Your code should like below:
[HttpGet("vulnerability")]
public async Task<IActionResult> vulnerability(string input)
{
object content = 0;
try
{
content = await CSharpScript.EvaluateAsync(input);
}
catch (Exception)
{
content = "";
}
return Ok(new { vuln = content });
}
And the test result:

Xamarin Forms: How to implement location share feature?

Whenever I am opening my app I need to check the location is on or off. If the location is off, I need to show an alert to the user to enable location share like the below screenshot:
I try this using the dependency service from this thread:
The interface on shared Project:
public interface ILocSettings
{
void OpenSettings();
}
Android implementation
[assembly: Dependency(typeof(LocationShare))]
namespace ProjectName.Droid
{
public class LocationShare : ILocSettings
{
public void OpenSettings()
{
//code1
Android.App.Application.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings));
//code2
//LocationManager LM = (LocationManager)Android.App.Application.Context.GetSystemService(Context.LocationService);
//if (LM.IsProviderEnabled(LocationManager.GpsProvider) == false)
//{
// Context ctx = Android.App.Application.Context;
// ctx.StartActivity(new Intent(Android.Provider.Settings.ActionLocationSourceSettings));
//}
}
}
}
Finally from the shared project called like below:
var myAction = await DisplayAlert("Location", "Please Turn On Location", "OK", "CANCEL");
if (myAction)
{
if (Device.RuntimePlatform == global::Xamarin.Forms.Device.Android)
{
DependencyService.Get<ILocSettings>().OpenSettings();
}
}
else
{
await DisplayAlert("Alert", "User Denied Permission", "OK");
}
I am getting below exception when running this. (Getting the same exception for code1 and code2)
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I need to show the alert only if the location is off. If the location is on, no need to do these things. How I can check the location is on or off?
Also, I need to implement the same feature for ios and windows platforms.
Update 1
Hi #Lucas Zhang - MSFT
I have tried your solution and got an alert like this. But after giving the location access, still the device's location is off. I need to on the device's location like this when the user taps the OK option in the alert (question screenshot). Either on the location directly or redirect to the location settings page.
Update 2
Tried GeolocatorPlugin and used the below code for checking the GPS is off or on. Always getting False value even if the GPS is on.
public bool IsLocationAvailable()
{
if (!CrossGeolocator.IsSupported)
return false;
return CrossGeolocator.Current.IsGeolocationAvailable;
}
Made below modification on the android service and now I am able to open the location settings.
public class LocationShare : ILocSettings
{
public void OpenSettings()
{
Intent intent = new Android.Content.Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
Before opening the location settings page, I need to verify the GPS is on or off (not the location permission).
Also I didn't understand the ios answer by Jack. So can you show me the ios dependency service like I did for android for opening ios location settings page?
In your case you could use the plugin PermissionsPlugin from Nuget.
Usage
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync<LocationPermission>();
if (status != PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
{
await DisplayAlert("Need location", "Gunna need that location", "OK");
}
status = await CrossPermissions.Current.RequestPermissionAsync<LocationPermission>();
}
if (status == PermissionStatus.Granted)
{
//Query permission
}
else if (status != PermissionStatus.Unknown)
{
//location denied
}
}
catch (Exception ex)
{
//Something went wrong
}
Update
It seems that you want to check if system location is open or not , right ? If so , you could try to achieve GPS info after you get the location permission . If the GPS info is still unavailable , that means the system setting is OFF .And you can invoke dependency service to open platform setting page.
public async void ShareLocation()
{
var status = await Permissions.RequestAsync<Permissions.LocationAlways>();
if (status == PermissionStatus.Granted)
{
bool gpsStatus = DependencyService.Get<ILocSettings>().isGpsAvailable();
if (!gpsStatus)
{
var myAction = await DisplayAlert("Location", "Please turn on GPS for the proper working of the application.", "TURN ON", "CANCEL");
if (myAction)
{
DependencyService.Get<ILocSettings>().OpenSettings();
}
}
}
}
//ILocSettings
public interface ILocSettings
{
void OpenSettings();
bool isGpsAvailable();
}
//Android Dependency Service
[assembly: Dependency(typeof(LocationShare))]
namespace Projectname.Droid.Services
{
public class LocationShare : ILocSettings
{
public bool isGpsAvailable()
{
bool value = false;
Android.Locations.LocationManager manager = (Android.Locations.LocationManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.LocationService);
if (!manager.IsProviderEnabled(Android.Locations.LocationManager.GpsProvider))
{
//gps disable
value = false;
}
else
{
//Gps enable
value = true;
}
return value;
}
public void OpenSettings()
{
Intent intent = new Android.Content.Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
}
For iOS
public void CheckAuthorization(CLLocationManager manager, CLAuthorizationStatus status)
{
switch (status)
{
case CLAuthorizationStatus.Authorized | CLAuthorizationStatus.AuthorizedAlways | CLAuthorizationStatus.AuthorizedWhenInUse:
Console.WriteLine("Access");
break;
case CLAuthorizationStatus.Denied | CLAuthorizationStatus.NotDetermined | CLAuthorizationStatus.Restricted:
Console.WriteLine("No Access");
break;
default:
Console.WriteLine("No Access");
break;
}
}
UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));

Browser caching images from ASP.NET Handler with complex URL not working

I'm trying to cache images, which are provided using a ASP.NET Handler same code as below:
Handler
public class ResourceHandler : IHttpHandler, IRouteHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.Private);
context.Response.Cache.SetMaxAge(new TimeSpan(1, 0, 0));
RouteData routeData = HttpContext.Current.Request.RequestContext.RouteData;
string name = routeData.Values["type"].ToString();
string imagePath = "path/{type}"
FileInfo fileInfo = new FileInfo(imagePath);
if (fileInfo == null)
{
// Resource not found
context.Response.StatusCode = 404;
return;
}
string rawIfModifiedSince = context.Request.Headers.Get("If-Modified-Since");
if (string.IsNullOrEmpty(rawIfModifiedSince))
{
// Set Last Modified time
context.Response.Cache.SetLastModified(fileInfo.LastWriteTimeUtc);
}
else
{
DateTime ifModifiedSince = DateTime.Parse(rawIfModifiedSince);
// HTTP does not provide milliseconds, so remove it from the comparison
if (fileInfo.LastWriteTimeUtc.AddMilliseconds(
-fileInfo.LastWriteTimeUtc.Millisecond) == ifModifiedSince)
{
// The requested file has not changed
context.Response.StatusCode = 304;
return;
}
}
using (Stream stream = fileInfo.OpenRead())
{
byte[] buffer = new byte[32];
while (stream.Read(buffer, 0, 32) > 0)
{
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(buffer);
}
}
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
public bool IsReusable
{
get { return true; }
}
}
}
Routes
I figure out that the route complexity was forcing the browser to always request from the server, never from the cache. (I've tried many, Chrome, Firefox, Edge)
If I register a simple route, everything works as intended:
routes.Add(new Route("image/{type}", new ResourceHandler()));
Example:
http://localhost/image/CompanyLogo/f8d8c2cc-271c-407e-9bbb-3deae1c577da_f8d8c2cc-271c-407e-9bbb-3deae1c577da_9bc61578-6c05-4532-8dce-ed2d6e28e8fc?size=normal&d=02102018061450
But Every browser refuses to get an image from cache if the url is like this:
routes.Add(new Route("image/{type}/{authenticatedUserId}/{userId}/{imageid}", new ResourceHandler()));
Example:
http://localhost/image/CompanyLogo/f8d8c2cc-271c-407e-9bbb-3deae1c577da/f8d8c2cc-271c-407e-9bbb-3deae1c577da/9bc61578-6c05-4532-8dce-ed2d6e28e8fc?size=normal&d=02102018061450
I've tried every possible header in combination, but why is the URL the issue? The simple one works, the dynamic one doesn't.
UPDATE
It works with the latest version of Firefox.

Will increasing my RAM reduce the size of my w3wp.exe in memory

I have a asp.net web site. I have an image being updated via a timer as many times as possible every second with an image the size of 720x576. I control when the image can be updated by initiating the next ashx page call to get my image after the img control has finished loading the previous image (I do this on the 'onload' event).
My w3wp.exe currently stands at 140,000k and it drops to 130,000. Frequently going up and down between these 2 values.
As i am testing with 1 User and as I am on a cheap VPS shared hosting environment my question is when I go Live will the w3wp.exe become uncontrollable or will the fact that by upgrading my server package (mainly increasing RAM) help to keep this all under control n a multi-user environment?
This is my Javascript:
var timer3;
var intervalLive = 50;
function play2() {
if (timer3) window.clearTimeout(timer3);
swapImages3();
}
function setImageSrc3(src) {
_imgLive.src = src;
timer3 = window.setTimeout(swapImages3, intervalLive);
}
function swapImages3() {
var imgCached = new Image();
imgCached.onload = function () {
setImageSrc3(imgCached.src);
};
imgCached.onerror = function () {
setImageSrc3("http://a URL/images/ERROR.jpg");
};
imgCached.onload = function () {
setImageSrc3(imgCached.src);
};
imgCached.src = null;
imgCached.src = 'http://A URL/Cloud/LiveXP.ashx?id=' + new Date().getTime() + '&Alias=' + alias;
}
And this is in my ashx page:
public class Live : IHttpHandler {
DAL dal = new DAL();
static byte[] StandardError = Shared.ERROR;
public void ProcessRequest(HttpContext context)
{
byte[] data = null;
context.Response.ContentType = "image/jpg";
try
{
if (context.Request.QueryString["Alias"] != null)
{
data = Shared.GetFrame(context.Request.QueryString["Alias"].ToString());
context.Response.BinaryWrite(data);
}
}
catch (Exception ex)
{
data = StandardError;
dal.AddError(ex.ToString());
}
finally
{
context.Response.BinaryWrite(data);
}
}
public bool IsReusable {
get {
return true;
}
}
}
thanks

HttpHandler [Image] cannot be displayed because it contains errors

Ok i have been working non stop on this and doing a lot of searching. I cannot get my images to display when pulling them from the database. If i try going to the handler link manually i get a message saying "The image [Image] cannot be displayed because it contains errors". I had some old images in the database from before and it first displayed those correctly. But now if i update images it will give me this error when trying to view them.
Upload code.
if (fileuploadImage.HasFile)
{
if (IsValidImage(fileuploadImage))
{
int length = fileuploadImage.PostedFile.ContentLength;
byte[] imgbyte = new byte[length];
HttpPostedFile img = fileuploadImage.PostedFile;
img.InputStream.Read(imgbyte, 0, length);
if (mainImage == null)
{
ProfileImage image = new ProfileImage();
image.ImageName = txtImageName.Text;
image.ImageData = imgbyte;
image.ImageType = img.ContentType;
image.MainImage = true;
image.PersonID = personID;
if (image.CreateImage() <= 0)
{
SetError("There was an error uploading this image.");
}
}
else
{
mainImage.ImageName = txtImageName.Text;
mainImage.ImageType = img.ContentType;
mainImage.ImageData = imgbyte;
mainImage.MainImage = true;
mainImage.PersonID = personID;
if (!mainImage.UpdateImage())
{
SetError("There was an error uploading this image.");
}
}
}
else
{
SetError("Not a valid image type.");
}
Here is my image handler:
public class ImageHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
int imageid = Parser.GetInt(context.Request.QueryString["ImID"]);
ProfileImage image = new ProfileImage(Parser.GetInt(imageid));
context.Response.ContentType = image.ImageType;
context.Response.Clear();
context.Response.BinaryWrite(image.ImageData);
context.Response.End();
}
And this is how i'm calling it "~/ImageHandler.ashx?ImID=" + Parser.GetString(image.ImageID)
I'm using the data type Image in sql server to store this.
Edit:
I also found out that if i put a try catch around context.Response.end() it is erroring out saying the "Unable to evaluate the code because the native frame..."
I found my problem. I was checking the header of the actual file to make sure it was valid. Somehow that was altering the data and making it bad.

Resources