ASP.NET MVC Reference script file with version wildcard (without bundling) - asp.net

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.

Related

Read AzureDevOps Pipeline Variables in C#

I need develop a C# .NetCore Console Application to access my DevOps account, select a release and read all variables in Pipeline Variables[
Anybody can give me an example?
Found a solution do read variables from Azure DevOps with REST API.
https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-6.1
Here I have a rough draft to read the variables from a release definition. You can create the .NET helper objects by creating helper classes from the JSON. There are sites on the internet for this.
Main() {
var pat = Environment.GetEnvironmentVariable("????");
var baseUrl = "https://dev.azure.com/{organization}";
var apiversion = "api-version=6.0";
var project = "????";
var search = "Releasename";
var actUrl = string.Format("{0}/{1}/_apis/release/definitions?searchText={2}&{3}",baseUrl,project,search,apiversion);
var json = await GetJsonFromUrlPAT(actUrl, pat);
cReleases varReleases = JsonConvert.DeserializeObject<cReleases>(json);
int ReleaseId=0;
if (varReleases.count == 1)
{
ReleaseId = varReleases.values[0].id;
actUrl = string.Format("{0}/{1}/_apis/release/definitions/{2}?{3}",baseUrl,project,ReleaseId,apiversion);
var json2 = await GetJsonFromUrlPAT(actUrl, pat);
cReleasedefinition varReleaseDef = JsonConvert.DeserializeObject<cReleasedefinition>(json2);
string jsonstring = JsonConvert.SerializeObject(varReleaseDef);
foreach (KeyValuePair<String,JToken> element in varReleaseDef.variables)
{
string varname = element.Key;
string varvalue = ((JObject)(element.Value)).GetValue("value").ToString();
}
foreach (var element in varReleaseDef.environments)
{
string environmentname = element.name;
foreach (KeyValuePair<String, JToken> item in element.variables)
{
string varname = item.Key;
string varvalue = ((JObject)(item.Value)).GetValue("value").ToString();
}
}
}
}
No worries!
To get your pipeline variables applied to your application configuration, you're going to want to use the File Transform task within your pipeline and configure it to point to your configuration JSON file within the Target Files
File Transform Task: https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/file-transform?view=azure-devops
What this task is going to do is use the variables you've associated with your pipeline to replace values within your JSON configuration.
Some things to note when using File Transform:
It can only perform replace operations, it cannot add to your configuration. So, be sure to have placeholders for every value you are looking to replace within your JSON file.
To access a nested value within JSON, you want to use a period within your naming conventions. In your case for example, you'll want to change ConnectionStrings:StorageAccountLogs to **ConnectionStrings.StorageAccountLogs" ** in order to correctly perform the variable substitution.

Read (audio) file from subfolder in AndroidAssets in Xamarin.Forms

I try to eneable audio in my Xamarin.Forms application. I want to have the audio files in a Subfolderof the Assetsfolder like this Assets/Subfolder/Audio.mp3
I have found a plugin SimpleAudioPlayer which provide an example.
The following code works like provided.
var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
player.Load("Audio.mp3");
Now I want to place the audio file in a subfolder and I tried to call
player.Load("Subfolder/Audio.mp3");
But I get an Java.IO.FileNotFoundException
I looked then into the implementation of the Load function and I fould the following code
public bool Load(string fileName)
{
player.Reset();
AssetFileDescriptor afd = Android.App.Application.Context.Assets.OpenFd(fileName);
player?.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
return PreparePlayer();
}
where the filename is pasted to the Assets.OpenFd() function. which returns an AndroidFileDesriptor
The documentation does not really provide any information from Microsoft and from the Android site.
My questions are
How can I receive the file from the subfolder in Android Assets?
What can I paste into the Assets.OpenFd() function (subfolders etc)?
I would appreciate any advice, since after a long time trying to resolve it I don't really have an idea.
According to the docs of the package, you won't be able to do just that because you have to use player.Load(GetStreamFromFile("mysound.wav")); where GetStreamFromFile is basically
Stream GetStreamFromFile(string filename)
{
var assembly = typeof(App).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream("App." + filename);
// Obviously App in the line above should be replaced with your app
return stream;
}
And secondly you have to player.Load(GetStreamFromFile("Subfolder.mysound.wav")); where Subfolder is the name of your subfolder.

How do I parse specific data from a website within Codename One?

I have run into a road block developing my Codename One app. One of my classes in my project parses 3 specific html "td" elements from a website and saves the text to a string where I then input that text data into a Codename One multibutton. I originally used jSoup for this operation but soon realized that Codename One doesn't support 3rd party jar files so I used this method as shown below.
public void showOilPrice() {
if (current != null) {
current.show();
return;
}
WebBrowser b = new WebBrowser() {
#Override
public void onLoad(String url) {
BrowserComponent c = (BrowserComponent) this.getInternal();
JavascriptContext ctx = new JavascriptContext(c);
String wtiLast = (String) ctx.get("document.getElementById('pair_8849').childNodes[4].innerText");
String wtiPrev = (String) ctx.get("document.getElementById('pair_8849').childNodes[5].innerText");
String wtiChange = (String) ctx.get("document.getElementById('pair_8849').childNodes[8].innerText");
Form op = new Form("Oil Prices", new BoxLayout(BoxLayout.Y_AXIS));
MultiButton wti = new MultiButton("West Texas Intermediate");
Image icon = null;
Image emblem = null;
wti.setEmblem(emblem);
wti.setTextLine2("Current Price: " + wtiLast);
wti.setTextLine3("Previous: " + wtiPrev);
wti.setTextLine4("Change: " + wtiChange);
op.add(wti);
op.show();
}
};
b.setURL("https://sslcomrates.forexprostools.com/index.php?force_lang=1&pairs_ids=8833;8849;954867;8988;8861;8862;&header-text-color=%23FFFFFF&curr-name-color=%230059b0&inner-text-color=%23000000&green-text-color=%232A8215&green-background=%23B7F4C2&red-text-color=%23DC0001&red-background=%23FFE2E2&inner-border-color=%23CBCBCB&border-color=%23cbcbcb&bg1=%23F6F6F6&bg2=%23ffffff&open=show&last_update=show");
}
This method works in the simulator (and gives a "depreciated API" warning), but does not run when I submit my build online after signing. I have imported the parse4cn1 and cn1JSON libraries and have gone through a series of obstacles but I still receive a build error when I submit. I want to start fresh and use an alternative method if one exists. Is there a way that I can rewrite this segment of code without having to use these libraries? Maybe by using the XMLParser class?
The deprecation is for the WebBrowser class. You can use BrowserComponent directly so WebBrowser is redundant in this case.
I used XMLParser for this use case in the past. It should work with HTML as it was originally designed to show HTML.
It might also be possible to port JSoup to Codename One although I'm not sure about the scope of effort involved.
It's very possible that onLoad isn't invoked for a site you don't actually see rendered so the question is what specifically failed on the device?

aspnet_compiler in Azure starup task

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();
}

How to rename a file in C#

Consider:
strPath= c:\images\gallery\add.gif
I need to rename this file from add.gif to thumb1.gid, and I should write one command method, whatever the file name. We need to
replace that name with this like below.
string strfilename = **"thumb"**
****Result thum.gif**
strPath= c:\images\gallery\thum.gif **
You have several problems, looking up the value in the XML file, and renaming the file.
To look up the number corresponding to Gallery2 or whatever, I would recommend having a look at Stack Overflow question How to implement a simple XPath lookup which explains how to look up nodes/values in an XML file.
To rename a file in .NET, use something like this:
using System.IO;
FileInfo fi = new FileInfo("c:\\images\\gallery\\add.gif");
if (fi.Exists)
{
fi.MoveTo("c:\\images\\gallery\\thumb3.gif");
}
Of course, you would use string variables instead of string literals for the paths.
That should give you enough information to piece it together and solve your particular lookup-rename problem.
I created a utility method to help encapsulate how to rename a file.
public class FileUtilities
{
public static void RenameFile(string oldFilenameWithPathWithExtension, string newFilenameWithoutPathWithExtension)
{
try
{
string directoryPath = Path.GetDirectoryName(oldFilenameWithPathWithExtension);
if (directoryPath == null)
{
throw new Exception($"Directory not found in given path value:{oldFilenameWithPathWithExtension}");
}
var newFilenameWithPath = Path.Combine(directoryPath, newFilenameWithoutPathWithExtension);
FileInfo fileInfo = new FileInfo(oldFilenameWithPathWithExtension);
fileInfo.MoveTo(newFilenameWithPath);
}
catch (Exception e)
{
//Boiler plate exception handling
Console.WriteLine(e);
throw;
}
}
}
I omitted several other file system checks that could optionally be done, but as #JoelCoehoorn pointed out in a comment on this page, the File System is Volatile, so wrapping it in a try-catch may be all that is necessary.
With that class in your library, now you can simply call:
var fullFilename = #"C:\images\gallery\add.gif";
var newFilename = "Thumb.gif";
FileHelper.RenameFile(fullFilename,newFilename);

Resources