How to resolve problem to Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript - asp.net

[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:

Related

Xamarin.Forms failing to use EvoHtmlToPdfclient in order to convert html string to a pdf file

I'm using Xamarin.Forms and I am trying to convert an html string to a pdf file using EvoPdfConverter, but the problem is that when I try to do so, on the line htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString()); in the code snippet below, the app just freezes and does nothing, seems like it wants to connect to the given IP, but it can't, however I don't get any errors or exceptions! not even catch!! does anybody know what I should do to resolve this issue? and here is my code for this:
public void ConvertHtmlToPfd(string htmlData)
{
ServerSocket s = new ServerSocket(0);
HtmlToPdfConverter htmlToPdfConverter = new
HtmlToPdfConverter(GetLocalIPAddress(),(uint)s.LocalPort);
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;
htmlToPdfConverter.PdfDocumentOptions.CompressCrossReference = true;
htmlToPdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best;
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
try
{
// create the HTML to PDF converter object
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
Java.IO.File myDir = new Java.IO.File(root + "/Reports");
try
{
myDir.Mkdir();
}
catch (Exception e)
{
string message = e.Message;
}
Java.IO.File file = new Java.IO.File(myDir, filename);
if (file.Exists()) file.Delete();
htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString());
}
catch (Exception ex)
{
string message = ex.Message;
}
}
Could you try to set a base URL to ConvertHtmlToFile call as the second parameter? You passed an empty string. That helps to resolve the relative URLs found in HTML to full URLs. The converter might have delays when trying to retrieve content from invalid resources URLs.

session modify from webmethod

is it possible to modify a session from a webmethod, well the complete description is,
I have a button that client side triggered to add data from textboxes into one new row inside a session
The session declared as
public List<Some_Business_Object_Here> A_Session
{
get
{
return (List<Some_Business_Object_Here>)Session["Session_Name_Here"];
}
set
{
Session["Session_Name_Here"] = value;
}
}
and The WebMethod
[WebMethod]
public static string InsertItemDt(List<string> dataIns)
{
BOResponse objRes = new BOResponse();
SomeFormHere form = new SomeFormHere();
Some_Business_Object_Here objDet = new Some_Business_Object_Here();
objDet.Data1 = dataIns[0];
objDet.Data2 = Convert.ToInt32(dataIns[1]);
objDet.Data3 = Convert.ToDecimal(dataIns[2]);
objRes = form.A_Processing_Method(objDet, ListItemDetail);
return new JavaScriptSerializer().Serialize(objRes);
}
and if the method processing to add a new row after some validation
is it possible to do it with this kind of method?
Edit: BOResponse is object for validation, containing only error code and catch error message
so the method be like
Private BOResponse A_Processing_Method (Some_Business_Object_Here obj)
{
try
{
(Some Validation Here...)
if (!validation)
{
MsgCode = 10;
MsgDesc = "Some Custom Error Text Here"
}
else
{
A_Session.Add(obj);
}
}
catch (Exception err)
{
MsgCode = 20;
MsgDesc = err.Message;
}
}
nevermind, seems it's working this way

Using geolocalisation with windows phone, await error

I'm trying to get the current location of an user, but the code show me an error...
// try get user location
Geolocator geo = new Windows.Devices.Geolocation.Geolocator();
geo.DesiredAccuracyInMeters = 10;
try {
Geoposition position = await geo.GetGeopositionAsync();
} catch (Exception e) { }
My problem is that the compiler show me an error at await geo.GetGeopositionAsync();
The 'await' operator can only be used when its containing method or lambda expression is marked with the 'async' modifier.
But from what I have seen, this is the same code as shown by Microsoft
I already restart VS12 and the pc (which is a VM but still) and the error is still here...
What's going wrong ?
I also try this and still get the same error:
Geoposition position = await geo.GetGeopositionAsync().asTask<Geoposition>();
You need to mark your method with async:
void **async** themethod()
{
// try get user location
Geolocator geo = new Windows.Devices.Geolocation.Geolocator();
geo.DesiredAccuracyInMeters = 10;
try {
Geoposition position = await geo.GetGeopositionAsync();
} catch (Exception e) { }
}

interesting service behaviour in silverlight

I have a Silverlight project which takes some encrypted string thru its Service Reference: DataService (service which is done in an ASP.NET project).
The method from TransactionServices.cs to get the encrypted string is:
public void GetEncryptedString(string original)
{
DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
dataSvc.GetEncryptedStringCompleted += new EventHandler<SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs>(dataSvc_GetEncryptedStringCompleted);
dataSvc.GetEncryptedStringAsync(original);
}
On completing, put the result in encodedString var (which is initialized with an empty value):
void dataSvc_GetEncryptedStringCompleted(object sender, SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
if (e.Result == null) return;
this.encodedString = e.Result;
}
catch (Exception ex)
{
Logger.Error("TransactionService.cs: dataSvc_GetEncryptedStringCompleted: {0} - {1}",
ex.Message, ex.StackTrace);
MessageBox.Show(ex.ToString());
}
}
}
Now I want to get the encoded string from my MainPage.xaml like:
TransactionService ts = new TransactionService();
ts.GetEncryptedString(url);
Console.WriteLine(ts.encodedString);
I do not uderstand why ts.encodedString is empty. When I do the debug I see that it actually prints out empty and AFTER that it goes to the void dataSvc_GetEncryptedStringCompleted to take the result and fill it.
Can you point me what I've done wrong? Is there a way to wait for the encodedString to be fetched and only after that to continue?
Thanks a lot.
When you call the ts.GetEncryptedString(url); you just started async operation. And therefor the value you are accessing is will be set only in the callback method.
But you access it before the value is modified by the callback.
The solution which I am using will looks similar to folowing:
Redefine the GetEncryptedString method signature.
public void GetEncryptedString(string original, Action callback)
{
DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
dataSvc.GetEncryptedStringCompleted += (o,e) =>
{
dataSvc_GetEncryptedStringCompleted(o,e);
callback();
}
dataSvc.GetEncryptedStringAsync(original);
}
Call it like this:
ts.GetEncryptedString(url, OtherLogicDependantOnResult);
where
OtherLogicDependantOnResult is
void OtherLogicDependantOnResult()
{
//... Code
}

Sometimes Image is not displaying for only one user

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.

Resources