Umbraco 7 if File Upload is empty - c#

I'm using Umbraco 7 with a File Upload. I would like to check IF there is or isn't a file uploaded.
If there isn't a file uploaded, I recieve the following error: Object reference not set to an instance of an object.
I have removed some code to make it easier to read through, but below is my surfacecontroller:
using System.Web.Mvc;
using Umbraco.Web.Mvc;
using Umbraco.Web;
namespace Sp34k.Controllers
{
public class GalleryItem
{
public string projectFile { get; set; }
}
public class PortfolioSurfaceController : SurfaceController
{
// GET: PortfolioSurface
public ActionResult GetCategoryDetails(int id)
{
GalleryItem gItem = new GalleryItem();
var node = Umbraco.TypedContent(id);
string file = node["uploadProjectFiles"].ToString();
if (string.IsNullOrWhiteSpace(file))
{
gItem.projectFile = node["uploadProjectFiles"].ToString();
}
return Json(gItem, JsonRequestBehavior.AllowGet);
}
}
}

I assume the problem is on this line:
string file = node["uploadProjectFiles"].ToString();
You may get a null as response to this from node with that key and you cannot call ToString() on it.
There is also another issue: if the string is null or whitespace you assign it to gItem.projectFile. I would assume you only want to assign it if it is not null or whitespace.
If the object in node is definitely a string or null, you can fix the code easily:
string file = node["uploadProjectFiles"] as string;
if (!string.IsNullOrWhiteSpace(file))
{
gItem.projectFile = file;
}
The as string means "if the object is a string assign it as such, or if it isn't return null." This way you either get a string (might still be empty/whitespace) or null with the type string and you can check it.

The node key which you are accessing is null probably, you need to check for null on it as well:
string file = node["uploadProjectFiles"] !=null ? node["uploadProjectFiles"].ToString() : String.Empty;
and then next use file variable:
if (string.IsNullOrWhiteSpace(file))
{
gItem.projectFile = file;
}

Related

C# Assigning default value to System.Uri property

I have a project which is about RESTful API and I have as a property the basic URL, on which I need to add parts each time (that's in my methods). I need (a) to declare the default (unchanged) path, and then (b) some help on how do I add to the URL. Example:
public partial class APIParamaters
{
public System.Uri URL { get; set; } = (System.Uri) "http://192.100.106.657:8811/some/part/here/version1/api"; //throws error !!!
}
This is throwing an error and I don't know how to correct.
Also, how do I later add to the URL, for example, I am trying
class MyTest
{
public string SpecialPart = "Excellent";
public APIParamaters myParams = new APIParamaters
{
URL = URL + SpecialPart + "FirstCall", //trying to do: "http://192.100.106.657:8811/some/part/here/version1/api/Excellent/FirstCall"
SomethingElse = "Ok"
//etc..
};
}
The following code means (cast this string as System.Uri) but string can not be cast as System.Uri:
(System.Uri) "http://192.100.106.657:8811/some/part/here/version1/api";
You should instantiate System.Uri:
public System.Uri URL { get; set; } = new System.Uri("http://192.100.106.657:8811/some/part/here/version1/api");

C# How to get/set data from asmx Web Service

I'm using VisualStudio2013. Its important to note for readers that the code which this asmx is derived from works perfectly but I do not know how to use the asmx WebService. I downloaded the whole nine yards from here https://sourceforge.net/projects/shorturl-dotnet/
I cannot figure out how to get/set properties of the following CreateUrl() WebMethod. I want to learn how to use the entire WebService but started here.
In the example that follows I send a URL to the CreateURL() method which will shorten the URL and perform other tasks; I do not know how to get properties from the returned ShortUrl.Container Class: I have not been successful accessing the data after the class(es) are returned to my calling method.
// WebMethod
public class API : System.Web.Services.WebService {
[WebMethod]
public ShortUrl.Container CreateUrl(string real_url)
{
ShortUrl.Container oShortUrl = new ShortUrl.Container();
oShortUrl.RealUrl = real_url;
oShortUrl.ShortenedUrl = ShortUrl.Utils.UniqueShortUrl();
oShortUrl.CreateDate = DateTime.Now;
oShortUrl.CreatedBy = HttpContext.Current.Request.UserHostAddress;
ShortUrl.Utils.AddUrlToDatabase(oShortUrl);
oShortUrl.ShortenedUrl = ShortUrl.Utils.PublicShortUrl(oShortUrl.ShortenedUrl);
return oShortUrl;
}
}
// ShortUrl.Container class returned as oShortUrl
namespace ShortUrl
{
/// <summary>
/// Container for the ShortURL object
/// </summary>
public class Container
{
private string _real_url;
private string _short_url;
private DateTime _create_date;
private string _created_by;
public Container()
{
this.CreateDate = DateTime.Now;
this.CreatedBy = "tap";
this.RealUrl = null;
this.ShortenedUrl = "Unknown";
}
public string RealUrl
{
get { return _real_url; }
set { _real_url = value; }
}
public string ShortenedUrl
{
get { return _short_url; }
set { _short_url = value; }
}
public DateTime CreateDate
{
get { return _create_date; }
set { _create_date = value; }
}
public string CreatedBy
{
get { return _created_by; }
set { _created_by = value; }
}
}
}
In VS2013 I add the Service Reference to point to http://tap.tools.api.asmx as the service endpoint and name the VS2013 reference as ShortenUrl. VS2013 generates the APISoapClient and Container classes.
// get/set properties of the ShortUrl.Container class
// by means of APISoapClient
ShortenUrl.APISoapClient u = new ShortenUrl.APISoapClient();
u.CreateUrl("http://clintongallagher.com/tag-target-url.html");
// get/set properties of the ShortUrl.Container class
// by means of Container class
ShortenUrl.Container c = new ShortenUrl.Container();
string url = c.RealUrl;
I'm not getting anywhere with either and I think my problem is the instance of the oShortUrl object instantiated within the public ShortUrl.Container CreateUrl(string real_url) method. I do not know how to get any of the properties from that instance of oShortUrl the Container class returns to my methods.
// oShortUrl
ShortUrl.Container oShortUrl = new ShortUrl.Container();
Odd as it may sound as old and outdated the use of asmx happens to be I never worked with -any- WebServices yet which explains why I am weak and throw myself to the mercy of the court.
// EDIT: 2016-07-19 ~2:41pm
VS2013 generated several classes from the WSDL two of which appear to be useful as seen in Intellisense...
// class APISoapClient and class Container
When I use a local variable with APISoapClient a shortened URL is generated as I can see using SQL Management Studio and note all of the data is properly generated but I am not able to get/set on any other WebMethods or properties with to get/set data...
// Exposes two WebMethods: CreateUrl and GetUrl
ShortenUrl.APISoapClient u = new ShortenUrl.APISoapClient();
// Does generate the shortened URL
u.CreateUrl("http://clintongallagher.com/tag-target-url.html");
// Should return the URL that was shortened but doesn't
u.GetUrl("i2Z5H");
And...
// Exposes the properties in Intellisense but does not return data
ShortenUrl.Container c = new ShortenUrl.Container();
// returns 1/1/0001 12:00:00 AM
lblCreateDate.Text = "CreateDate: " + c.CreateDate.ToString();
// returns nothing
lblCreatedBy.Text = "CreatedBy: " + c.CreatedBy;
// returns nothing
lblRealUrl.Text = "RealUrl: " + c.RealUrl;
// returns ShortenUrl.Container
lblShortenedUrl.Text = "ShortenedUrl: " + u.GetUrl("i2Z5H");
If i understood what you're trying to get is the Container returned from the Web Method. If so then just create a variable type of Container and assign the method call to it. Like ShortUrl.Container c = u.CreateUrl(...) then from c you can get the values you're looking for.
Think about this #clintongallagher. When you do the following call,
ShortenUrl.APISoapClient u = new ShortenUrl.APISoapClient();
u.CreateUrl("http://clintongallagher.com/tag-target-url.html");
[WebMethod]
public ShortUrl.Container CreateUrl(string real_url)
{
ShortUrl.Container oShortUrl = new ShortUrl.Container();
oShortUrl.RealUrl = real_url;
//here you're assigning a value to this object, let's say 'A'
oShortUrl.ShortenedUrl = ShortUrl.Utils.UniqueShortUrl();
oShortUrl.CreateDate = DateTime.Now;
oShortUrl.CreatedBy = HttpContext.Current.Request.UserHostAddress;
//then here you're saving the object with the Shortened value 'A' you just got
ShortUrl.Utils.AddUrlToDatabase(oShortUrl);
/*
*finally you're replacing the Shortened value with another value,
*let's say 'B', which is the object you're going to return*/
oShortUrl.ShortenedUrl = ShortUrl.Utils.PublicShortUrl(oShortUrl.ShortenedUrl);
return oShortUrl;
}
I don't know how does GetUrl(shortened_value) is supposed to work but, assuming it will get from the DB the shortened_value passed in, of course the result would not be the same since the shortened value saved was 'A' and your asking for B.

AllowHtml not working

I'm building a Content Management System to allow people other than me to update stuff on the site.
I have a front-facing HTML form that sends data, via AJAX, to a controller:
// CONTROLLER
[ValidateInput(false)]
public void CarAJAX()
{
CarAdmin CA = new CarAdmin();
CA.UpdateCar(System.Web.HttpContext.Current.Request);
}
This data will have HTML, so I keep getting an error in my Model:
// MODEL
using System;
using System.Web;
using System.Web.Mvc;
namespace Site.Models
{
public class CarAdmin
{
public String id { get; set; }
[AllowHtml]
public String HTML_Stuff { get; set; }
public CarAdmin(){}
public void UpdateCar(HttpRequest Request)
{
HTML_Stuff = Request.Form["HTML_Stuff"]; // <-- ERROR HAPPENS HERE!!!!!!
// sanitation and validation
String Select = String.Format("UPDATE Car Set HTML_Stuff = {0} WHERE id = {1}", HTML_Stuff, id);
// Execute DB Command
}
}
}
As shown in the code, I'm getting an error when I try to set a member equal to a request variable that has HTML.
Edit: The error is 'A potentially dangerous Request.Form value was detected'
Here's what I've tried:
Change the validation mode in web.config, but I don't want to change the validation for my entire site, when only one variable will have HTML.
[AllowHtml] in the Model, however I'm still getting the same error - as if [AllowHtml] did nothing at all.
[ValidateInput(false)] in the Controller, similar to AllowHtml, it seems to have no affect whatsoever.
Am I missing something here?
I had the same problem. "requestValidationMode="2.0"" was set in web.config, [AllowHtml] was also set on proper property and I still got the error "A potentially dangerous Request.Form value detected...".
But I observed that the controller method actually was called (I was able to debug the method) so this had to meant that validation is in fact turned off. In Call Stack I noticed repeatedly occurring of classes around cache like "System.Web.Caching.OutputCacheModule" and this led me to an idea that this has something to do with cache I had turned off on the whole controller like this "[OutputCache(NoStore = true, Duration = 0)]".
Based on this I tried to also set Location of the cache to OutputCacheLocation.None and this did the trick. So I ended up with [OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)] working and finally not validating and not failing my requests.
Try with this:
// CONTROLLER
[HttpPost]
public ActionResult CarAJAX(CarAdmin model)
{
model.UpdateCar();
}
// MODEL
using System;
using System.Web;
using System.Web.Mvc;
namespace Site.Models
{
public class CarAdmin
{
private string html;
public String id { get; set; }
[AllowHtml]
public String HTML_Stuff {
get
{
return html;
}
set
{
// sanitation and validation on "value"
html = value;
}
}
public CarAdmin(){}
public void UpdateCar()
{
String Select = String.Format("UPDATE Car Set HTML_Stuff = {0} WHERE id = {1}", HTML_Stuff, id);
// Execute DB Command
}
}
}
I also noticed that you are validating inside a method. It would probably be better, if you do that when setting the property.
EDIT:
I researched quite a bit on the topic. You actually need to bind model to the controller using AJAX. Please look at this example. I'm not sure of extents of your code, but I think you also need ActionResult to return within controller. There are nice examples of what to return from ActionResult.
just put [ValidateInput(false)] on controller
You should do it as-
Create a separate class with entities those are required-
public class EntityDto {
public String id { get; set; }
[AllowHtml]
public String HTML_Stuff { get; set; }
}
And then use it in your controller method-
[ValidateInput(false)]
public void UpdateCar(EntityDto model)
{
var html_stuff = model.HTML_Stuff;
// sanitation and validation
String Select = String.Format("UPDATE Car Set HTML_Stuff = {0} WHERE id = {1}", html_stuff , id);
// Execute DB Command
}
Let me know if it helps.

How to Clear/Remove an ActiveDirectory property with ExtensionSet

I'm using the Principal Extensions for a User in AD to access properties not normally retrieved by the UserPrincipal. My custom properties are defined like such:
[DirectoryProperty("facsimileTelephoneNumber")]
public string FaxNumber
{
get
{
if (ExtensionGet("facsimileTelephoneNumber").Length != 1)
return null;
return (string)ExtensionGet("facsimileTelephoneNumber")[0];
}
set
{
ExtensionSet("facsimileTelephoneNumber", value);
}
}
How do you clear the property with ExtensionSet? If I input null or empty string, I will almost always get this error message: "The attribute syntax specified to the directory service is invalid.". It sounds like you should clear the property but I'm unsure how this works with ExtensionSet.
The problem was I was not sending back an array, I was only sending back the value, not an array:
[DirectoryProperty("facsimileTelephoneNumber")]
public string FaxNumber
{
get
{
if (ExtensionGet("facsimileTelephoneNumber").Length != 1)
return null;
return (string)ExtensionGet("facsimileTelephoneNumber")[0];
}
set
{
ExtensionSet("facsimileTelephoneNumber", string.IsNullOrEmpty(value) ? new string[1] {null} : new string[1] {value});
}
}

how to force WebAPI in MVC4 to render null strings as empty in json result

How to render null string properties as empty strings in ASP.NET MVC4 Web API v.1 in json result?
WebAPI renders them as
"myproperty": null
how to render this as
"myproperty": ""
controller is
public class Customer {
public string myproperty { get; set; }
}
public class CustomersController : ApiController
{
public HttpResponseMessage Get()
{
var cust = new Customer();
return Request.CreateResponse(HttpStatusCode.OK,
new { customers = cust.ToArray() });
}
}
object are nested and contain lot of string properties. Setting them all to empty strings in constructor seems ugly. API caller needs empty strings or 0 for decimals, it does not like null constant in any value.
you can decorate your properties like this :
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
[DefaultValue("")]
public string myproperty{ get; set; }
Note that you can set the default value handling to populate in a global config like this:
GlobalConfiguration
.Configuration
.Formatters
.JsonFormatter
.SerializerSettings
.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Populate;
So, you don't need to decorate it to every property. You will only need to use the DefaultValue.
public class Customer {
private string _myproperty = String.Empty;
public string myproperty
{
get { return _myproperty; };
set { _myproperty = value ?? String.Empty; }
}
}
i give little overhead but solve my problem
DataTable dt = (new tst()).Gettable();
string s = string.Empty;
s = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
s= s.Replace("null", "\"\"");
Object obj = Newtonsoft.Json.JsonConvert.DeserializeObject(s);
return Ok(obj);
As default web api works like this...
you don't need to change

Categories