In my asp.web api 2.0 project I have a Json file, where all the error codes are mapped. I want to read the json file in order to return response to the caller.
I am unable to read the same, however if I use console application following code works, any suggestion will be helpful.
Code that works in console application:
var assembly = Assembly.GetExecutingAssembly();
using (var stream = new StreamReader(assembly.GetManifestResourceStream("ConsoleApp24.Utilities.StatusCodes.json") ?? throw new InvalidOperationException()))
{
var status = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
Using above code provides assembly as null in web api project, hence I changed it to following:
var assembly = GetWebEntryAssembly();
using (var stream = new StreamReader(assembly.GetManifestResourceStream("PaymentAccount.Api.Resources.StatusCodes.json") ?? throw new InvalidOperationException()))
{
var status = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
private Assembly GetWebEntryAssembly()
{
if (System.Web.HttpContext.Current == null ||
System.Web.HttpContext.Current.ApplicationInstance == null)
{
return null;
}
var type = System.Web.HttpContext.Current.ApplicationInstance.GetType();
while (type != null && type.Namespace == "ASP")
{
type = type.BaseType;
}
return type == null ? null : type.Assembly;
}
The exception I get is:
Operation is not valid due to the current state of the object.
With Server.MapPath it is easy for ASP.NET to find your files but the file still have to be inside of the application root folder, here is some official documentation on this function.
Just place file inside your root folder, and then use Server.MapPath this will allow your ASP.NET application to find your file in the Server file system.
string json = File.ReadAllText(Server.MapPath("~/files/myfile.json"));
You can try this :
public object Get()
{
string allText = System.IO.File.ReadAllText(#"c:\data.json");
object jsonObject = JsonConvert.DeserializeObject(allText);
return jsonObject;
}
this code returns json text
Related
I'm coding an app using Visual Studio and Xamarin in C#, and I'd like the user to be able to take a photo and save it in his phone to later be retrieved within the app. To do this, I need to start by saving the photo in the phone. My photos are of type FileResult and I put all the photos in a list and save the list thanks to this block of code:
public static List<FileResult> SavedListPhoto
{
get
{
var savedList = Deserialize<List<FileResult>>(Preferences.Get(nameof(SavedListPhoto), null));
Console.WriteLine(savedList);
return savedList ?? new List<FileResult>();
}
set
{
var serializedList = Serialize(value);
Preferences.Set(nameof(SavedListPhoto), serializedList);
Console.WriteLine(nameof(SavedListPhoto));
}
}
static T Deserialize<T>(string serializedObject) => JsonConvert.DeserializeObject<T>(serializedObject);
static string Serialize<T>(T objectToSerialize) => JsonConvert.SerializeObject(objectToSerialize);
Now that the list is saved in the phone, I'd like to be able to access the list and the elements inside it, as well as modify it. I'm using this block of code to accomplish it:
private List<FileResult> GetList(object instance, string path)
{
var pp = path.Split('/');
Type t = instance.GetType();
foreach( var prop in pp)
{
Console.WriteLine(prop);
PropertyInfo propInfo = t.GetProperty(prop);
Console.WriteLine(propInfo);
if (propInfo != null)
{
instance = propInfo.GetValue(instance, null);
t = instance.GetType();
}
else throw new ArgumentException("Properties path is not correct");
}
return (List<FileResult>)instance;
}
However, whatever I do, the ArgumentException gets thrown. Obviously, it's because propInfo is always null, but I don't understand why. The instance I'm giving is the list itself, and the path I'm giving is the following:
/data/user/0/com.companyname.app1/cache/2203693cc04e0be7f4f024d5f9499e13/9fe8dae02ada45a5bb9eba67d39f7d06/8907af5726ff404fadb415261a7dc71e.jpg, which is the path that I get from the following block of code (after being modified so I get only the path above):
Preferences.Get("SavedListPhoto", "false")
I've looked but I found no problems which related exactly to what I have. If someone could help me it would be greatly appreciated :)
I got a problem for few days, i'm trying to access to firestore in xamarin forms. To do so I am using the environment variable GOOGLE_APPLICATION_CREDENTIALS as you can see in the code below. The environment variable stting is successfull as you can see I did some test and everything is ok about this part. But when I call the method FirestoreClient.Create() I got this exception:
System.TypeLoadException: Could not resolve type with token 0100003b (from typeref, class/assembly System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
I'm using Google.Cloud.Firestore and Google.Cloud.Firestore.V1Beta1 both on version 1.0.0-beta02
Here is the code :
public void InitializeFirestore()
{
var assembly = Assembly.GetExecutingAssembly();
Stream steam = assembly.GetManifestResourceStream("AIGallery.AppMobile.CarouselReservation.FirestoreDir.Book-A-Room-Bot-13b38d0674e5.json");
string text = "";
//I create the json files to get the path, because can't get the path from an embedded ressource
string json = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "creditential.json");
//Here I just copy past the json file from google inside creditential.json
using (var reader = new StreamReader(steam))
{
text = reader.ReadToEnd();
}
using (var w = new StreamWriter(json))
{
w.WriteLine(text);
w.Flush();
}
//Here was just to be sure everything was wirtten inside json, it works
text = "";
using (var reader = new System.IO.StreamReader(json))
{
text = reader.ReadToEnd();
}
//Set the variable
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", json);
//See the content, worked well
var t = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
//Here on Create, it crash
client = FirestoreClient.Create();
I'm trying to find out what is wrong for few days, can't figure it out. Thanks in advance
I'm trying to upload file to Sharepoint 2013 using web service copy.asmx
I've created simple project with the following method:
public bool UploadFile(string file, string destination)
{
bool success = false;
CopySoapClient client = new CopySoapClient();
if (client.ClientCredentials != null)
{
client.ClientCredentials.Windows.ClientCredential = new NetworkCredential("admin", "password", "domain");
}
try
{
client.Open();
string filename = Path.GetFileName(file);
string destinationUrl = destination +#"/"+ filename;
string[] destinationUrls = { destination };
FieldInformation i1 = new FieldInformation { DisplayName = "Title", InternalName = "Title", Type = FieldType.Text, Value = filename};
FieldInformation[] info = { i1 };
CopyResult[] result;
byte[] data = File.ReadAllBytes(file);
uint ret = client.CopyIntoItems(file, destinationUrls, info, data, out result);
if (result != null && result.Length > 0 && result[0].ErrorCode == 0)
success = true;
}
finally
{
if (client.State == System.ServiceModel.CommunicationState.Faulted)
client.Abort();
if (client.State != System.ServiceModel.CommunicationState.Closed)
client.Close();
}
return success;
}
CopySoapClient is part Copy service reference
http://SPSITE/_vti_bin/copy.asmx
The method is called using following parameters:
UploadFile(#"C:\temp\test.txt", "http://SPSITE/sites/Connector/documents/test.txt");
The problem is, when program executes
uint ret = client.CopyIntoItems(file, destinationUrls, info, data, out result);
the web service returns in result "Unknown error" with description "Object reference not set to an instance of an object."
I really don't know what I'm missing. Can anyone help me out?
Thank you.
P.S. I've noticed in examples provided on the Internet that people are using a Copy class from copy.asmx. But I only have CopySoapClient class.
you used the right web services but on wrong SharePoint site. Try to make this web services reference on the same sharepoint site you have posted here as target library.
missing the OPTIONAL element of <Fields> and <FieldInformation >, resulted ErrorCode="Unknown" ErrorMessage="Object reference not set to an instance of an object." . even though, Field and FieldInformation supposed to be optional. It could be the server side configuration. Anyway, it works for me now, adding all attributed, required/optional.
Since i am using asp.net2.0 when i used the below class i am getting the following error.
Error 1 : The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)
The class i have used.How can i use this code in asp.net2.0 without getting any error
public static XElement GetGeocodingSearchResults(string address)
{
// Use the Google Geocoding service to get information about the user-entered address
// See http://code.google.com/apis/maps/documentation/geocoding/index.html for more info...
var url = String.Format("http://maps.google.com/maps/api/geocode/xml?
address={0}&sensor=false", HttpContext.Current.Server.UrlEncode(address));
// Load the XML into an XElement object (whee, LINQ to XML!)
var results = XElement.Load(url);
// Check the status
var status =results.Element ("status").Value;
if (status != "OK" && status != "ZERO_RESULTS")
// Whoops, something else was wrong with the request...
throw new ApplicationException("There was an error with Google's Geocoding Service: " + status);
return results;
}
var is simply a shortcut for the actual type of the right-side expression.
public static XElement GetGeocodingSearchResults(string address)
{
// Use the Google Geocoding service to get information about the user-entered address
// See http://code.google.com/apis/maps/documentation/geocoding/index.html for more info...
string url = String.Format("http://maps.google.com/maps/api/geocode/xml?address={0}&sensor=false",
HttpContext.Current.Server.UrlEncode(address));
// Load the XML into an XElement object (whee, LINQ to XML!)
XElement results = XElement.Load(url);
// Check the status
string status =results.Element ("status").Value;
if (status != "OK" && status != "ZERO_RESULTS")
// Whoops, something else was wrong with the request...
throw new ApplicationException("There was an error with Google's Geocoding Service: " + status);
return results;
}
BUT LINQ to XML (and whole LINQ functionality) is only available in .NET 3.5 and above. You should either upgrade to .NET 3.5 or switch to System.Xml
as shown here its possible to get the "default" IIS mime types from HKEY_Classes_Root.
However when I register a new type I cannot find the entry - does anyone know how I get read all IIS registered mime types progamatically ?
Sorry to answer my own question but the answer posted here (shown below) resolves this for both IIS 6 & 7
NameValueCollection map = new NameValueCollection();
using (DirectoryEntry entry = new DirectoryEntry("IIS://localhost/MimeMap"))
{
PropertyValueCollection properties = entry.Properties["MimeMap"];
Type t = properties[0].GetType();
foreach (object property in properties)
{
BindingFlags f = BindingFlags.GetProperty;
string ext = t.InvokeMember("Extension", f, null, property, null) as String;
string mime = t.InvokeMember("MimeType", f, null, property, null) as String;
map.Add(ext, mime);
}
}
You may have to add it in IIS.
http://technet.microsoft.com/en-us/library/cc725608(WS.10).aspx
Update
You could try the DirectoryServices API:
public static string GetMimeTypeFromExtension(string extension)
{
using (DirectoryEntry mimeMap =
new DirectoryEntry("IIS://Localhost/MimeMap"))
{
PropertyValueCollection propValues = mimeMap.Properties["MimeMap"];
foreach (object value in propValues)
{
IISOle.IISMimeType mimeType = (IISOle.IISMimeType)value;
if (extension == mimeType.Extension)
{
return mimeType.MimeType;
}
}
return null;
}
}
Can I setup an IIS MIME type in .NET?