Value cannot be null. Parameter name: String - c#

Please take a look at the following code. It's in handler.asxh.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
new RequestManagementFacade().PinRequest(Int32.Parse(context.Request.QueryString["requestId"]), (Boolean.Parse(context.Request.QueryString["isPinned"])));
}
This is showing the following error:
Value cannot be null. Parameter name: String
There is value being passed as I have checked the context request query string, however, the code breaks at this stage.
This handler will connect to the business logic layer.

There is value being passed as i have checke dthe context request query string
I strongly suspect your diagnostics are incorrect then. Values don't magically go missing - you need to question your assumptions. This is easy to debug through though. I would suggest changing your code to:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
string requestId = context.Request.QueryString["requestId"];
string isPinned = context.Request.QueryString["isPinned"];
var facade = new RequestManagementFacade();
facade.PinRequest(Int32.Parse(requestId), Boolean.Parse(isPinned));
}
It's then really simple to step through and find out what's going on.

It is likely that either context.Request.QueryString["requestId"] or context.Request.QueryString["isPinned"] is not returning a valid string value. Check that both values are passed in the query string with the proper IDs, those being of course requestId and isPinned.

Okay solved when passing the values to the handler i inserted it as
"PinRequest.ashx?="+requestId+isPinned"
Which gave me the result 2True
So i realised the hiccup was with not including the string names
"PinRequest.ashx?requestId=" + this._requestId + "&isPinned=" + this._isPinned
Thanks for you help guys
LeviBotelho Thank you made me check something i was missing out when checking as its javascript

experienced the error while using Int32.Parse(myString) to convert string to int and afterwards assign the value to an object's attribute. Using another method for converting(Convert.ToInt32(myString)) string to int worked for me.

Related

Twilio StatusCallback not working:

So I'm building an app with twilio voice, and I've got all the phonecall stuff working. But I'm having a little trouble understanding which parameters my callback should have.
I've registered the URL as described in the docs:
options.From = formatPhoneNumber(callout.callback_number);
options.To = formatPhoneNumber(offer.employee_phone_number);
options.Url = TwilioCallBotController.TwilioCalloutScriptURL;
options.StatusCallback = TwilioCallBotController.StatusCallbackURL;
options.StatusCallbackEvents = new []{"initiated", "ringing", "answered", "completed" };
options.StatusCallbackMethod = "POST";
I've also made a callback method here, but I'm not having much luck finding out how the parameters are supposed to work with their API. I'm kindof at a loss as to what could be the reason behind this one not working:
[HttpPost]
public ActionResult TwilioStatusCallback()
{
var twiml = new Twilio.TwiML.TwilioResponse();
twiml.Say("This is a test");
string CallSid = Request.Form["CallSid"];
string CallStatus = Request.Form["CallStatus"];
Debug.WriteLine("Status Callback Delivered");
Shift_Offer shoffer = db.Shift_Offers.Where(s => s.twillio_sid == CallSid).ToList()[0];
shoffer.status = CallStatus.ToString();// + DateTime.Now.ToString();
return TwiML(twiml);
}
Edit:
So it turns out that the API is very sensitive about the method signature (the call was previously throwing a method not found exception in a number of microsoft DLLs, including System.Web and System.Web.Mvc.
So I've actually gotten the software to call the method by using an empty method signature (no parameters).
However I'm still having trouble getting the parameters from the HTTPPOST
Edit: So upon further investigation I've managed to inspect the Request. The values I'm after exist in Request.Form["foo"], but they don't seem to be getting put into the two strings I have declared. I've removed the ["HttpPost"] attribute to try to troubleshoot the issue, but I'm really at a loss as to why I can see the values in the debugger, but they're not translating into memory.
public ActionResult TwilioStatusCallback()
{
var twiml = new Twilio.TwiML.TwilioResponse();
string sid = Request.Form["CallSid"];
string status = Request.Form["CallStatus"];
Shift_Offer shoffer = db.Shift_Offers.Where(s => s.twillio_sid == sid).ToList()[0];
shoffer.status = status;// + DateTime.Now.ToString();
return TwiML(twiml);
}
Last issue was that the database wasn't being saved.
Just added a db.SaveChanges() and we're good.

ASP.NET Prevent exposure of sensitive data

I'm doing a asp.net/c# project. Currently I have one web page with a label control lblData to display content from a string variable. Please look at the code block below:
string strData = "Data";
lblData.Text = strData;
When I run Parasoft tool to scan the project, I get result as below:
Security issue: Prevent exposure of sensitive data
Leakage of ToString() result via web control.
I think my code violated some standard security practice but I'm not sure how to fix it.
Really appreciate for your time and help.
Is this full code, or you have simplified your example?
I am asking because I was not able to get any violation on your example.
After modifying your example to something like:
protected void Foo(object o)
{
string strData = "Data" + o.ToString() ;
lblData.Text = strData;
}
I am getting following violation:
Violation: Leakage of ToString() result ("strData") via web control
To fix that violation you will need to validate exposed data, it is done by defining in rule configuration validating method and passing your data to that method(by default all methods with prefix 'validate' are treated as validating)
so if you modify your code to something like:
protected void Foo(object o)
{
string strData = "Data" + o.ToString() ;
validateStrData(strData);
lblData.Text = strData;
}
private void validateStrData(string strData)
{
//some validating logic
}
then violation should not be reported
Try this,
lblData.Text = strData.ToString();

How can i use response.redirect from inside a function defined in Class file in c# 3.0

I have a simple function GetPageName(String PageFileName, String LangCode) defined inside a class file. I call this function from default.aspx.cs file, In this function I am not able to use Response.Redirect("Error.aspx") to show user that error has been generated.
Below is example of Code
public static string GetPageName(String PageFileName, String LangCode)
{
String sLangCode = Request("Language");
String pgName = null;
if ( sLangCode.Length > 6)
{
Reponse.Redirect("Error.aspx?msg=Invalid Input");
}
else
{
try
{
String strSql = "SELECT* FROM Table";
Dataset ds = Dataprovider.Connect_SQL(strSql);
}
catch( Exception ex)
{
response.redirect("Error.aspx?msg="+ex.Message);
}
}
return pgName;
}
I have may function defined in Business and Datalayer where i want to trap the error and redirect user to the Error page.
HttpContext.Current.Response.Redirect("error.aspx");
to use it your assembly should reference System.Web.
For a start, in one place you're trying to use:
response.redirect(...);
which wouldn't work anyway - C# is case-sensitive.
But the bigger problem is that normally Response.Redirect uses the Page.Response property to get at the relevant HttpResponse. That isn't available when you're not in a page, of course.
Options:
Use HttpContext.Current.Response to get at the response for the current response for the executing thread
Pass it into the method as a parameter:
// Note: parameter names changed to follow .NET conventions
public static string GetPageName(String pageFileName, String langCode,
HttpResponse response)
{
...
response.Redirect(...);
}
(EDIT: As noted in comments, you also have a SQL Injection vulnerability. Please use parameterized SQL. Likewise showing exception messages directly to users can be a security vulnerability in itself...)

How to pass a dynamic DataModel to an Action?

I dynamically build a ASP.NET MVC3 View with some inputfields, but cause of the dynamic creation of the UI, I do not know which inputfields will be available.
After clicking on a button (search) I want to pass the actual inputdata as an Model(ViewModel) to an Action. Here`s the Problem, I dont know which properties does the Model have and how to pass this dynamic Model/Object to the Action.
I tried to simply do it like so:
public ActionResult StartQuery(dynamic request)
{
var test = request;
//...
}
but don`t know how to handle this dynamic object. If this is the correct way, do I have to use reflection for this or does anybody can give me a tip how to correctly push dynamic data to an Action?
Thanks in advance,
Cordell
-EDIT
Even if I know the input IDs it doesn`t worked out. Keep getting DynamicBinderExceptions.
public ActionResult StartQuery(dynamic request)
{
string test = request.ArticleNo;
string test2 = request.ArtNoOfSuppl;
string test3 = request.ArticleGrp;
//...
These are the exact IDs for the test, I cannot build on the names, the could change.
Don't use dynamic, if you know the names you can fetch them directly from the request:
public ActionResult StartQuery()
{
string test = Request["ArticleNo"];
string test2 = Request["ArtNoOfSuppl"];
string test3 = Request["ArticleGrp"];
...
}
If you don't know them you could still loop through Request.Params collection and based on your rules find the parameters you need.

Check Validity for a QueryString using Entity Framework

I use C# Asp.Net and EF 4.
I have a scenario like MasterPage and DetailsPage.
So from my MasterPage I pass a variable as a QeryString to the DetailsPage, the DetailsPage will show up details for a specifc item in my DataBase.
I need to check the validity for my QueryString, in details I need:
Check if is Null, Empty or White Spaces.
Check if is NOT of type INT (just numbers not any letters).
Check if the Object NOT exists in my DB.
In case if Check result True, I will redirect the User.
At the moment I wrote this script. It is works but I would like to know if you know a better approch/code to solve this.
Also I would like to know if make sense to have this logic on every time the page Load, or would be enought us just on !Page.IsPostBack.
Thanks once again for your support guys!
protected void Page_Load(object sender, EventArgs e)
{
#region Logic Check Query String.
// Query String is Null or Empty.
if (string.IsNullOrWhiteSpace(ImageIdFromUrl))
RedirectToPage();
// Query String is not valid Type of INT.
int ImageId;
bool isInt = Int32.TryParse(ImageIdFromUrl, out ImageId);
if (isInt)
{
// Check if a valid Object request exist in Data Source.
using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
{
if (!context.CmsImagesContents.Any(x => x.ImageContentId == ImageId))
{
RedirectToPage();
}
}
}
else
RedirectToPage();
#endregion
}
You don't need to check it on every postback, only on a full page load. The query string is not sent to the server on postbacks.
I suggest you move all the query string validation logic to separate functions.

Categories

Resources