Nullreference exception was unhandled by user in asp.net [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
In the below code i have a string value it has a path.I want to place the String value inside the static method But i get Object reference not set to an instance of an object.if i write path in that code it works but not string value which has path .pls help me to solve the issue.
var projectname = name.ProjectName;
var batchname = name.BatchName;
var imagename = name.ImageName;
string concatenatedStr = "/"+ projectname + "/" + batchname + "/Input/" + imagename;
[WebMethod]
public static string buttonclickImage(string pageNo)
{
int iPageNo = 0;
if (pageNo != string.Empty && pageNo != "undefined")
iPageNo = Int32.Parse(pageNo);
FileTransfer.FileTransferClient fileTranz = new FileTransfer.FileTransferClient();
FileDto file = fileTranz.GetTifftoJPEG("concatenatedStr", iPageNo, "gmasdll");
var fileData = Convert.ToBase64String(file.Content);//throws error
return fileData;
}

it means that either file is null or file.Content is null. You can avoid the exception by
if(file!=null && file.Content!=null)
{
//your remaining code
}
ideally though you should first check the reason why it is null
Edit:
From your comments i infer that you want to pass your varible. Either make your string static, or make your method not static or pass the string to your method
[WebMethod]
public static string buttonclickImage(string pageNo)
{
int iPageNo = 0;
if (pageNo != string.Empty && pageNo != "undefined")
iPageNo = Int32.Parse(pageNo);
FileTransfer.FileTransferClient fileTranz = new FileTransfer.FileTransferClient();
//note the change here. no double quotes.
FileDto file = fileTranz.GetTifftoJPEG(concatenatedStr, iPageNo, "gmasdll");
var fileData = Convert.ToBase64String(file.Content);//throws error
return fileData;
}

You're not passing in the value stored in the concatenatedStr variable... you're passing in the literal string "concatenatedStr".
Change this:
FileDto file = fileTranz.GetTifftoJPEG("concatenatedStr", iPageNo, "gmasdll");
To this:
FileDto file = fileTranz.GetTifftoJPEG(concatenatedStr, iPageNo, "gmasdll");
You'll also need to make your variables static, since your method is static. Or leave the variables as they are, and make the method non-static, if that's an option.
I'm a little confused about where those variables are located though. They appear to be class-level in scope, but then you wouldn't be able to use var in that location.
I guess you could also modify your method to accept an additional parameter, and then pass in the value from wherever you're calling this.
public static string buttonclickImage(string pageNo, string concatenatedStr)
{
...

This works
[WebMethod]
public static string buttonclickImage(string pageNo)
{
var name = (name)HttpContext.Current.Session["Projectname"];
var projectname = name.ProjectName;
var batchname = name.BatchName;
var imagename = name.ImageName;
string concatenatedStr = "/" + projectname + "/" + batchname + "/Input/" + imagename;
int iPageNo = 0;
if (pageNo != string.Empty && pageNo != "undefined")
iPageNo = Int32.Parse(pageNo);
FileTransfer.FileTransferClient fileTranz = new FileTransfer.FileTransferClient();
FileDto file = fileTranz.GetTifftoJPEG(concatenatedStr, iPageNo, "gmasdll");
var fileData = Convert.ToBase64String(file.Content);
return fileData;
}

First of all construct value of "concatenatedStr" variable using String.Format.
For Eg:-
var projectname = name.ProjectName;
var batchname = name.BatchName;
var imagename = name.ImageName;
string concatenatedStr = string.Format("/{0}/{1}/Input/{2}", projectname, batchname, imagename);
Put debug point here and check what value "concatenatedStr" has.
If "concatenatedStr" is null then definitely you will get "Nullreference exception"....
So may be there is a problem with "concatenatedStr".....So deeply check concatenation variables too...
Hope this works......

Related

C# Set / create DateTaken parameter

I'm tying to set the DateTaken parameter with C#, because I've got a lot of photos without this date.
I only found this comment changing-datetaken-of-a-photo
In this toppic they are changing it and not creating it.
If use this function, but DataTakenProperty1 or DataTakenProperty2 is null and can not be set.
private static void SetDateTaken(string path, DateTime NEWdate)
{
Image theImage = new Bitmap(path);
PropertyItem[] propItems = theImage.PropertyItems;
Encoding _Encoding = Encoding.UTF8;
var DataTakenPropert = propItems.SetValue(NEWdate.ToString("yyyy:MM:dd HH:mm:ss"), ??How do i know the index??);
theImage.SetPropertyItem(DataTakenProperty);
string new_path = Path.GetDirectoryName(path) + "\\_" + Path.GetFileName(path);
theImage.Save(new_path);
theImage.Dispose();
}
Thanks for your help
You can acheive this using a little trick, since you can't initiate PropertyItem when its null.
It is difficult to set property items, because the PropertyItem class
has no public constructors. One way to work around this restriction is
to obtain a PropertyItem by retrieving the PropertyItems property
value or calling the GetPropertyItem method of an Image that already
has property items. Then you can set the fields of the PropertyItem
and pass it to SetPropertyItem.
private static void SetDateTaken(string path, string samplePath, DateTime NEWdate)
{
Encoding _Encoding = Encoding.UTF8;
Image theImage = new Bitmap(path);
PropertyItem[] propItems = theImage.PropertyItems;
var DataTakenProperty1 = propItems.FirstOrDefault(a => a.Id.ToString("x") == "9003");
var DataTakenProperty2 = propItems.FirstOrDefault(a => a.Id.ToString("x") == "9004");
//// this is where you do the hack
if (DataTakenProperty1 == null)
{
Image sampleImage = new Bitmap(samplePath);
PropertyItem fakePropertyItem1 = sampleImage.PropertyItems.FirstOrDefault(a => a.Id.ToString("x") == "9003");
fakePropertyItem1.Value = _Encoding.GetBytes(NEWdate.ToString("yyyy:MM:dd HH:mm:ss") + '\0');
fakePropertyItem1.Len = fakePropertyItem1.Value.Length;
theImage.SetPropertyItem(fakePropertyItem1);
PropertyItem fakePropertyItem2 = sampleImage.PropertyItems.FirstOrDefault(a => a.Id.ToString("x") == "9004");
fakePropertyItem2.Value = _Encoding.GetBytes(NEWdate.ToString("yyyy:MM:dd HH:mm:ss") + '\0');
fakePropertyItem2.Len = fakePropertyItem2.Value.Length;
theImage.SetPropertyItem(fakePropertyItem2);
}
else
{
DataTakenProperty1.Value = _Encoding.GetBytes(NEWdate.ToString("yyyy:MM:dd HH:mm:ss") + '\0');
DataTakenProperty2.Value = _Encoding.GetBytes(NEWdate.ToString("yyyy:MM:dd HH:mm:ss") + '\0');
theImage.SetPropertyItem(DataTakenProperty1);
theImage.SetPropertyItem(DataTakenProperty2);
}
theImage.Save(newPath);
theImage.Dispose();
}
List of PropertyIds

Check if string is null

I want to check if my variable(crphoto1) is null. If crphoto1 is null, crPhoto1Data should be null and when crphoto1 is not null crPhoto1Data should be like this byte[] crPhoto1Data = File.ReadAllBytes(crphoto1);. The code belows gives me error how can I fix it?
if (string.IsNullOrEmpty(crphoto1))
{
string crPhoto1Data = "";
}
else
{
byte[] crPhoto1Data = File.ReadAllBytes(crphoto1);
}
var ph1link = "http://" + ipaddress + Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=tWyd43";
string ph1contentType = "application/json";
JObject ph1json = new JObject
{
{ "ContactID", crcontactID },
{ "Photo1", crPhoto1Data }
};
The problem is that you're trying to use a variable that is declared inside a block with a narrower scope (you define crPhoto1Data inside the if block). Another problem is that you're trying to set it to more than one type.
One way solve this is to create the JObject in an if/else statement (or using the ternary operator as in my sample below):
JObject ph1json = string.IsNullOrEmpty(crphoto1)
? new JObject
{
{"ContactID", crcontactID},
{"Photo1", ""}
}
: new JObject
{
{"ContactID", crcontactID},
{"Photo1", File.ReadAllBytes(crphoto1)}
};

How to rename file in c# when uploading?

I am developing one application in web api and angularjs. I have file upload part. I am able to upload files and i am not storing files in webroot(i created folder called Uploads). My problem is i am not using any good naming convention to maintain uniqueness of files so there are chances of overriding files. I am new to angularjs so i refered below link. http://instinctcoder.com/angularjs-upload-multiple-files-to-asp-net-web-api/
This is my controller level code.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");
var multipartFormDataStreamProvider = new CustomUploadMultipartFormProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);
var fileName = "";
DateTime dt = DateTime.Now;
foreach (var key in multipartFormDataStreamProvider.Contents)
{
var a = key.Headers;
fileName = a.ContentDisposition.FileName;
break;
}
foreach (var key in multipartFormDataStreamProvider.FormData.AllKeys)
{
foreach (var val in multipartFormDataStreamProvider.FormData.GetValues(key))
{
Console.WriteLine(string.Format("{0}: {1}", key, val));
}
}
In the above code I am trying to add date part to beginning of file name as below
string filenameNew = "App1" + DateTime.Now.ToString("yyyyMMddHHmmss");
fileName = filenameNew + a.ContentDisposition.FileName;
public CustomUploadMultipartFormProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
string startwith = "Nor" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (headers != null && headers.ContentDisposition != null)
{
return headers
.ContentDisposition
.FileName.TrimEnd('"').TrimStart('"').StartsWith("startwith").ToString();
}
return base.GetLocalFileName(headers);
}
This i tried but whatever the original file name that only comes. May I get some idea where can i append datepart to file while saving? Any help would be appreciated. Thank you.
I'm not sure what you're trying to do inside of the GetLocalFileName, this is pretty messed up.
First off, StartsWith returns a boolean (true or false) that indicates if the string starts with whatever you put in the parenthesis.
string str = "SIMPLE";
bool t = str.StartsWith("SIM"); // true
bool f = str.StartsWith("ZIM"); // false
The fact you're turning this bool back into a string and also passing the string "startsWith" into the method, means it will always return the string "false" (a bool value converted into a string) unless the real filename starts with "startsWith".
I think this is what you're looking for:
public override string GetLocalFileName(HttpContentHeaders headers)
{
string prefix = "Nor" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (headers != null && headers.ContentDisposition != null)
{
var filename = headers.ContentDisposition.FileName.Trim('"');
return prefix + filename;
}
return base.GetLocalFileName(headers);
}
My suggestion for you is to learn the basics of C# and .Net a bit more, maybe read a C# book or something.

Xamarin c# for Android : creating a json string?

Having problems with this code ..
GlodalVariables.SoftID = "55";
WebClient client = new WebClient ();
Uri uri = new Uri ("http://www.example.com/CreateEntry.php");
string folder = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
Android.Content.Context myContext = Android.App.Application.Context;
try{
string smsUri = System.IO.Path.Combine (folder, "SL.db");
string myjson = "";
SQLiteDatabase Mydb = SQLiteDatabase.OpenDatabase(smsUri , null, DatabaseOpenFlags.OpenReadwrite );
ICursor SMScursor = Mydb.Query ("MySMSLog", null,null, null,null, null ,"TheDate ASC");
MySMSLog test = new MySMSLog() ;
if (SMScursor.MoveToFirst ()) {
while (!SMScursor.IsAfterLast){
string number = SMScursor.GetString(SMScursor.GetColumnIndex("TheNumber"));
string name = SMScursor.GetString(SMScursor.GetColumnIndex("TheName"));
string date = SMScursor.GetString(SMScursor.GetColumnIndex("TheDate"));
string direction = SMScursor.GetString(SMScursor.GetColumnIndex("TheDirection"));
string text = SMScursor.GetString(SMScursor.GetColumnIndex("TheText"));
string id = SMScursor.GetString(SMScursor.GetColumnIndex("Id"));
test.Id = int.Parse(id);
test.TheDate = date;
test.TheDirection = direction ;
test.TheName = name;
test.TheNumber = number;
test.TheText = text;
string output = Newtonsoft.Json.JsonConvert.SerializeObject (test);
myjson = myjson + output + " ";
SMScursor.MoveToNext ();
}
}
System.Console.WriteLine (myjson );
System.Console.WriteLine();
SMScursor.Close ();
When i Copy the complete json string into a json test site (http://jsonlint.com/)
It tells me the sting is invalid ...
I'm getting all the record rows and putting them into a single json string before pushing them over to the server..
Shouldn't you get the result in an array form? So the final json should look like :
[{json1},{json2}..]
Probably if you have just {json1} {json2} this is not a valid object.
Could an alternative solution be to build a collection of "MySMSLog" objects, then serialise the collection throught JSonConvert? That way you don't need to worry about getting the structure correct through your own string manipulation.
This would most likely also future proof your code on the ridiculously outlandish chance that JSON standards change, as the NewtonSoft library would be updated as well.

Dynamically loading a resource and reading the correct value for the CurrentUICulture

I'm creating a method to convert an enum to a friendly string. The friendly names are stored in a resource file and are subject to globalization. So I created two resource file: Enums.resx and Enums.pt-BR.resx whose keys are the name of the enum followed by it's value (i.e DeliveryStatus_WaitingForPayment).
This is the code I'm using to load the resource and get the corresponding friendly name for the enum:
public static string EnumToString<T>(object obj)
{
string key = String.Empty;
Type type = typeof(T);
key += type.Name + "_" + obj.ToString();
Assembly assembly = Assembly.Load("EnumResources");
string[] resourceNames = assembly.GetManifestResourceNames();
ResourceManager = null;
for(int i = 0; i < resourceNames.Length; i++)
{
if(resourceNames[i].Contains("Enums.resources"))
{
rm = new ResourceManager(resourceNames[i], Assembly.GetExecutingAssembly());
Stream resStream = assembly.GetManifestResourceStream(resourceNames[i]);
ResourceReader reader = new ResourceReader(resStream);
IDictionaryEnumerator dict = reader.GetEnumerator();
while (dict.MoveNext())
{
string keyToCompare = dict.Key.ToString();
if (keyToCompare == key)
return dict.Value.ToString();
}
}
return obj.ToString();
}
}
This method works almost perfectly except that it ignores the CurrentUICulture and always returns the values from the default resource, that is, even when I'm using pt-BR as my CurrentUICulture it will load the value from Enum.resx and not Enum.pt-BR.resx.
What am I doing wrong?
As it turns out I was taking the wrong approach to read the resource file. Not only I didn't need to work my way through a stream it was preventing me from getting the result based on the CurrentUICulture.
The solution is much easier than that of my first attempt:
public static string EnumToString<T>(object obj)
{
string key = String.Empty;
Type type = typeof(T);
key += type.Name + "_" + obj.ToString();
Assembly assembly = Assembly.Load("EnumResources");
string[] resourceNames = assembly.GetManifestResourceNames();
ResourceManager = null;
for(int i = 0; i < resourceNames.Length; i++)
{
if(resourceNames[i].Contains("Enums.resources"))
{
//The substring is necessary cause the ResourceManager is already expecting the '.resurces'
rm = new ResourceManager(resourceNames[i].Substring(0, resourceNames[i].Length - 10), assembly);
return rm.GetString(key);
}
return obj.ToString();
}
}
I hope this helps anyone trying something similar in the future!

Categories

Resources