I have a C# Model Class where I am trying to access a .cshtml page which is supposed to be an email format template. I'm using the following code:
string body = string.Empty;
using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailConfTemplate.cshtml")))
{
body = reader.ReadToEnd();
}
But i am getting the following error message:
The name Server does not exist in the current context
Is there any error in the code or the Server class can't be accessed in POCO class. Please help.
To execute it inside a .Net pipeline, you can find it as an instance present in HttpContext
System.Web.HttpContext.Current.Server.MapPath()
Instead of
Server.MapPath("~/EmailConfTemplate.cshtml")
Try using
string fullPath = new DirectoryInfo(string.Format("{0}\\EmailConfTemplate.cshtml", HttpContext.Current.Server.MapPath(#"\"))).ToString();
Related
I am trying to get Tags to work in a C# AWS CDK project but I can't seem to get anything to work except for the Depreciated syntax. For example in the following code:
using Amazon.CDK;
using Amazon.CDK.AWS.S3;
namespace HelloCdk
{
public class HelloCdkStack : Stack
{
internal HelloCdkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
// The code that defines your stack goes here
var g_bucket = new Bucket(this, "GameContent", new BucketProps
{
Versioned = false,
PublicReadAccess = true,
AutoDeleteObjects = true, //delete and
RemovalPolicy = RemovalPolicy.DESTROY, //destroy bucket when CF Stack deleted.
WebsiteIndexDocument = "index.html",
WebsiteErrorDocument = "index.html"
});
Tag.Add(g_bucket, "key", "value");
}
}
}
The above code will succeed when I issue the cdk synth command. However, I get a warning message that says:
warning CS0618: 'Tag.Add(Construct, string, string, ITagProps?)' is obsolete: 'use "Tags.of(scope).add()"'
But, when I try to use "Tags.of...", the cdk synth command throws the following error:
error CS1061: 'TagManager' does not contain a definition for 'of' and no accessible extension method 'of'...
What do I need to change to get the recommended tagging approach to work?
Your source code with Tags.of should not compile as there is no such a method for .NET defined.
Documentation specifies Tags.Of - https://docs.aws.amazon.com/cdk/latest/guide/tagging.html
Tags.Of(myConstruct).Add("key", "value");
(!) Notice that the stack object has the Tags property, so make sure you do not access the Tags property of the stack, but Tags class.
Make sure you're using the correct Tags class in Amazon.CDK namespace, and not the Stack.Tags property. Here's how you can get to it directly:
Amazon.CDK.Tags.Of(CONSTRUCT).Add(KEY, VALUE);
The developer of this particular library seems to be MIA.
https://github.com/Kamiizumi/NmapXmlParser
To test the issue grab his library (NmapXmlParser) from Nu-Get and make sure you have
using System.Xml.Serialization;
using System.IO;
using Xunit;
The code he gives on the example looks like this
var xmlSerializer = new XmlSerializer(typeof(nmaprun));
var result = default(nmaprun);
using (var xmlStream = new StreamReader("NmapResults.xml"))
{
result = xmlSerializer.Deserialize(xmlStream) as nmaprun;
}
Console.WriteLine(result.args);
This works when getting the elements inside of the nmaprun object.
He does not give any other examples so I assumed if I wanted to check the host object i would change all instances of nmaprun in above code to host. And then on the Console line change to an element inside the host object like this
var xmlSerializer = new XmlSerializer(typeof(host));
var result = default(host);
using (var xmlStream = new StreamReader("NmapResults.xml"))
{
result = xmlSerializer.Deserialize(xmlStream) as host;
}
Console.WriteLine(result.reason);
The Intellisense inside of the Console.Writeline wants to autocomplete to the elements so I feel its set up right but I keep getting this error.
System.InvalidOperationException: 'There is an error in XML document (5, 2).'
Inner Exception InvalidOperationException: was not expected.
You can use the example XML in his Github if you do not have an Nmap xml output file
I have a web app that allows importing of contacts from Hotmail, Yahoo and GMail. I finally have it almost completed but since I added the importing of GMail, I am getting ambiguous reference errors and I am unsure how to fix them without breaking any code.
Here is a screen shot of the errors:
Try to use unique class names as much as possible. This will be the better solution in the end.
Write the entire namespace when referencing
OAuth.OAuthBase a = new ...;
Google.GData.Client.OAuthBase b = new ...;
Make an using alias for one or both:
using n2 = OAuth;
using Google.GData.Client;
n2.OAuthBase a = new ...; // referenced using namespace
OAuthBase b = new ...; // referenced through existing `using`
you can try something like this..
using GoogleOAuthBase = Google.GData.Client.OAuthBase;
namespace abc
{
public class Program
{
//make sure this Google.GData.Client.OAuthBase is instansiateable
var googleBase = new GoogleOAuthBase();
}
}
you can try entire name space as well.
var googleBase = new Google.GData.Client.OAuthBase();
I have in my funcs.cs file:
using System;
using System.Collections.Generic;
using System.Web;
public static class AuthData
{
public const string USERNAME = "zheref";
public const string PASSWORD = "Altairis";
}
And I'm trying to access the USERNAME and PASSWORD constants in my AuthData class from my Razor Code (auth.cshtml file):
#{
if(IsPost)
{
var u = Request.Form["username"];
var c = Request.Form["password"];
if(u == AuthData.USERNAME && c == AuthData.PASSWORD)
{
Response.Redirect("~/default");
}
else
{
Response.Redirect("~/logon");
}
}
}
This is generating a Compilation Error:
"An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately."
If that's not the way I'm not sure how to do that. Thanks.
You need to put your funcs.cs file in your App_Code folder, if it doesn't exist create it. This assumes that all namespaces are resolvable and you don't need any using statements in your razor file.
In my attempt to further future-proof a project I am trying to find the best way to retrieve the full path and filename of the index/default page in a web directory using C# and without knowing the web server's list of filename possibilities.
'Server.MapPath("/test/")' gives me 'C:\www\test\'
...so does: 'Server.MapPath(Page.ResolveUrl("/test/"))'
...but I need 'C:\www\test\index.html'.
Does anyone know of an existing method of retrieving the filename that the webserver will serve up when someone browses to that directory - be it default.aspx, or index.html, or whatever?
Thanks for any help,
fodder
ASP.NET has no knowledge of this. You would need to query IIS for the default document list.
The reason for this is that IIS will look in your web folder for the first matching file in the IIS default document list then hand off to the matching ISAPI extension for that file type (by extension) in the script mappings.
To obtain the default document list you can do the following (using the Default Website as an example where the IIS Number = 1):
using System;
using System.DirectoryServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (DirectoryEntry w3svc =
new DirectoryEntry("IIS://Localhost/W3SVC/1/root"))
{
string[] defaultDocs =
w3svc.Properties["DefaultDoc"].Value.ToString().Split(',');
}
}
}
}
It would then be a case of iterating the defaultDocs array to see which file exists in the folder, the first match is the default document. For example:
// Call me using: string doc = GetDefaultDocument("/");
public string GetDefaultDocument(string serverPath)
{
using (DirectoryEntry w3svc =
new DirectoryEntry("IIS://Localhost/W3SVC/1/root"))
{
string[] defaultDocs =
w3svc.Properties["DefaultDoc"].Value.ToString().Split(',');
string path = Server.MapPath(serverPath);
foreach (string docName in defaultDocs)
{
if(File.Exists(Path.Combine(path, docName)))
{
Console.WriteLine("Default Doc is: " + docName);
return docName;
}
}
// No matching default document found
return null;
}
}
Sadly this won't work if you're in a partial trust ASP.NET environment (for example shared hosting).