Does anyone have a good example or helper class that would allow me to read the connection string in a web application from a T4 template residing in ANOTHER assembly referenced by the web application. I am generating some code from the database that it references and i would appresiate some help on how to get the connection string for this use.
ive read George Js example here however it only works when the template resides in the web app, please help!!!
var path = Host.ResolvePath(#"../Web.config");
var map = new ExeConfigurationFileMap { ExeConfigFilename = path };
var config = ConfigurationManager.OpenMappedExeConfiguration(
map,ConfigurationUserLevel.None);
var appSettings = config.AppSettings;
var connectionStrings = config.ConnectionStrings.ConnectionStrings;
You could try to do something like that:
var config = ConfigurationManager.OpenExeConfiguration("../somePathTo/web.config")
// use the config to get values like: config.AppSettings
after a bit of searching around ive found my answer in t4 one may use
path = Host.ResolvePath(relativeFileName)
Related
I am using the CachedImage component of ffimageloading. I have a kind of gallery with a carousel view.
All the images are loaded through an internet URL, they are not local images. I would like to add the image sharing function. But I don't want to download the file again, I would like to know if there is a way to access the file that the CachedImage component already downloaded to be able to reuse it in the share function.
try using MD5Helper
var path = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey")'
Thanks Jason
I share with you how part of my code is:
var key = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey");
var imagePath = await ImageService.Instance.Config.DiskCache.GetFilePathAsync(key);
var tempFile = Path.Combine(Path.GetTempPath(), "test.jpg");
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
File.Copy(imagePath, tempFile);
await Share.RequestAsync(new ShareFileRequest
{
Title = "Test",
File = new ShareFile(tempFile)
});
The temporary file I believe, since the cached file has no extension and the applications do not recognize the type.
In a ASP.NET MVC 4 project, I'd like to reference a versioned script file like this:
// Just some pseudo-code:
<script src="#Latest("~/Scripts/jquery-{0}.min.js")"></script>
// Resolves to the currently referenced script file
<script src="/Scripts/jquery-1.10.2.min.js"></script>
so that when a new Script version is updated via NuGet, the reference is updated automatically. I know of the bundling-and-minification feature, but it's just to much. I just want the little part which resolves the wildcards. My files are already minified, and also I don't want the bundles.
Do you have some smart ideas how to solve this?
Even though it's a little over kill to use the Bundling in MVC, but I think that will be your best bet. It's already been done and proven so why spend more time to write some proprietary code.
That being said, if you want a simple sample of what you can do, then you can try the following.
public static class Util
{
private const string _scriptFolder = "Scripts";
public static string GetScripts(string expression)
{
var path = HttpRuntime.AppDomainAppPath;
var files = Directory.GetFiles(path + _scriptFolder).Select(x => Path.GetFileName(x)).ToList();
string script = string.Empty;
expression = expression.Replace(".", #"\.").Replace("{0}", "(\\d+\\.?)+");
Regex r = new Regex(#expression, RegexOptions.IgnoreCase);
foreach (var f in files)
{
Match m = r.Match(f);
while (m.Success)
{
script = m.Captures[0].ToString();
m = m.NextMatch();
}
}
return script;
}
}
This will return you the last match in your Scripts director or it will return empty string.
Using this call
#Html.Raw(MvcApplication1.Util.GetScripts("jquery-{0}.min.js"))
Will get you this result if 1.8.2 is the last file that matched your string.
jquery-1.8.2.min.js
Hope this will help you get started.
Does anyone know if its possible to call aspnet_compiler from an azure role startup task to force a precompilation inplace. (And if so as a foregroudn/background or simple task?)
Perhaps something like:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_precompile.exe -v / -p "F:\siteroot\0"
Or are there any better ways to accomplish this?
Yes, that should work once you figure out the right path to the compiler although I haven't tried this specific approach.
An alternative I've tried is to use ClientBuildManager.PrecompileApplication as described in this answer. I tried calling that from inside OnStart() but you can compile C# code as a .NET assembly and use that from PowerShell or just call .NET primitives from PowerShell as described here and that way call it from the startup task.
A start-up task is possible, but one problem with that is that the siteroot path is hardcoded and that can change. Instead add the following to the RoleEntryPoint OnStart method:
using (var serverManager = new ServerManager())
{
string siteName = RoleEnvironment.CurrentRoleInstance.Id + "_" + "Web";
var siteId = serverManager.Sites[siteName].Id;
var appVirtualDir = $"/LM/W3SVC/{siteId}/ROOT"; // Do not end this with a trailing /
var clientBuildManager = new ClientBuildManager(appVirtualDir, null, null,
new ClientBuildManagerParameter
{
PrecompilationFlags = PrecompilationFlags.Default,
});
clientBuildManager.PrecompileApplication();
}
As we know that a virtual direcoty can be linked to a folder with a diffrent name, how can I get the physical path of a virtual directory ?
I've been trying with HttpContext.Current.server.MapPath but it returns me the physic path plus the path I send in parameter even if the directory doesn't even exist or if it exists with a diffrent name.
Exemple :
C:\blabla\Sites\Application1\Imaageesss
- On disc
Application1\Images (In ISS, my virutal directory)
But if I do a MapPath on "/Images" it will never give me
C:\blabla\Sites\Application1\Imaageesss but
C:\inetpub\wwwroot\Images which is not the real directory linked to.
Server.MapPath("~/Images")
is the correct way to go about it as "~" references the root of your application.
This is what worked for me:
string physicalPath =
System.Web.Hosting.HostingEnvironment.MapPath(HttpContext.Current.Request.ApplicationPath);
What if you try this little snippet?
string physicalPath = HttpContext.Current.Request.MapPath(appPath);
After some more research I was able to create a method to get the physical path of a virtual IIS directory:
public static string VirtualToPhysicalPath(string vPath) {
// Remove query string:
vPath = Regex.Replace(vPath, #"\?.+", "").ToLower();
// Check if file is in standard folder:
var pPath = System.Web.Hosting.HostingEnvironment.MapPath("~" + vPath);
if (System.IO.File.Exists(pPath)) return pPath;
// Else check for IIS virtual directory:
var siteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
var sm = new Microsoft.Web.Administration.ServerManager();
var vDirs = sm.Sites[siteName].Applications[0].VirtualDirectories;
foreach (var vd in vDirs) {
if (vd.Path != "/" && vPath.Contains(vd.Path.ToLower())) pPath = vPath.Replace(vd.Path.ToLower(), vd.PhysicalPath).Replace("/", "\\");
}
return pPath;
}
Caveat: this solution assumes that you only have a root application (Applications[0]).
The following should work just fine:
var physicalPath = HostingEnvironment.MapPath("~/MyVirtualDirectory");
This might answer your question:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.physicalpath.aspx
However, I can't currently provide an example, because I have got a lot of work to do. When I'll find some time I'll send detailed information.
I am trying to get a xml file with data into Flex application. There are a lot of examples online passing parameter into flex I found very helpful. However, it doesn't really work in my case.
here is my code in HTML:
var flashvars = {};
flashvars.storageStatsXML = "stats.xml";
var params = {};
swfobject.embedSWF("mySWF.swf", "mySWF", "1000", "500", "10.0.0", "js/expressInstall.swf", flashvars, params);
here is the code in mxml:
[Bindable]
public var storageStats:XML;
protected function start(event:FlexEvent):void
{
storageStats = Application.application.parameters.storageStatsXML;
}
And then the XML file got parsed in the application.
I think there is something not right about the code, any thoughts?
Thanks.
The Application.application.parameters.storageStatsXML property is not the XML data you are expecting, it is a String containing the text "stats.xml".
In the same way that the file path "c:\temp\info.txt" (or "/temp/info.txt") isn't the file itself, it just tells you how to find the file on disk.
You will need to use a URLRequest to load the XML file specified by the storageStatsXML property.
Have a look at the Actionscript documentation and here on StackOverflow for examples on how to load external data.