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();
}
Related
I'm trying to get the php sha1(md5($Password)); like this
public static string GetSha1MD5Pass(string value)
{
var data = System.Text.Encoding.ASCII.GetBytes(value);
var datamd5 = System.Security.Cryptography.MD5.Create().ComputeHash(data);
var data64 = Convert.ToBase64String(datamd5);
var data64e = Encoding.ASCII.GetBytes(data64);
var hashData = new SHA1Managed().ComputeHash(data64e);
var hash = string.Empty;
foreach (var b in hashData)
{
hash += b.ToString("X2");
}
return hash;
}
I call it like this :
command.Parameters.AddWithValue("#pwd", Crypto.GetSha1MD5Pass(password));
where Crypto its class I made were GetSha1MD5Pass resides
but it clearly failed, maybe someone here can help me, thank you
MD5 is not recommended for secure hashing. It's considered a deprecated algorithm because it is relatively easy to break. The current recommendation is to use PBKDF2-HMAC-SHA256 with 310,000 iterations.
You can achieve this relatively easy in ASP.NET Core using the PasswordHasher helper in the Microsoft.AspNetCore.Identity package. It has HashPassword and a VerifyHashedPassword methods. By default, the number of iterations is set to 10,000, but you can reconfigure that yourself:
builder.Services.Configure<PasswordHasherOptions>(options =>
{
options.IterationCount = 310000;
});
I have a working example of using the PasswordHasher here: https://github.com/mikebrind/Razor-Pages-In-Action/tree/main/Chapter13/PasswordHasherDemo
If you are migrating an old PHP app to .NET Core, now is the time to improve your security. Anyone who tries to log in using their old PHP password should be told that their password needs resetting, and then you can store the reset one using up-to-date APIs. Store it in a new column, perhaps, so you know whether someone had updated their password or not.
I have an ASP.NET project that sends its logs to NLog.
However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.
I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.
How can this be accomplished?
This is the code that creates the logger:
// create the module name
var ProcessName = Process.GetCurrentProcess().ProcessName;
_ModuleName = ProcessName + " (\"" + Oracle.GuessMyName() + "\")";
// create the logger configuration
var Configuration = new LoggingConfiguration();
// create the file target
var FileTarget = new FileTarget ("file")
{
FileName = #"x:\Logs\${processname}.log",
ArchiveFileName = #"x:\Logs\${processname}.{#}.log",
Layout = #"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
ArchiveEvery = FileArchivePeriod.Day,
ArchiveNumbering = ArchiveNumberingMode.Rolling,
MaxArchiveFiles = 7,
ConcurrentWrites = true
};
Configuration.AddTarget(FileTarget);
// create the viewer target
var ViewerTarget = new NLogViewerTarget ("viewer")
{
Layout = #"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
IncludeSourceInfo = true,
IncludeCallSite = true,
Address = #"udp://127.0.0.1:9999"
};
Configuration.AddTarget(ViewerTarget);
// set the rules
Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));
// set the configuration
LogManager.Configuration = Configuration;
// create a new logger
_Logger = LogManager.GetLogger(_ModuleName);
and this is also how ASP.net gets attached to nlog:
LoggerFactory.AddNLog();
Application.AddNLogWeb();
Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)
so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.
the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.
Look at the code of NLog.Extensions.Logging, where it injects its own custom log-provider.
You can do the same and just wrap your global-logger object:
https://github.com/NLog/NLog.Extensions.Logging/blob/e48d6cc54d9abd70d976066265c7992117cbac5a/src/NLog.Extensions.Logging/NLogLoggerProvider.cs
https://github.com/NLog/NLog.Extensions.Logging/blob/1474ffe5b26d2ac95534ed01ef259133133bfb67/src/NLog.Extensions.Logging/NLogLoggerFactory.cs
https://github.com/NLog/NLog.Extensions.Logging/blob/2c05a4fbdda0fe026e60814d535e164e18786aef/src/NLog.Extensions.Logging/ConfigureExtensions.cs
public static ILoggerFactory AddNLog(this ILoggerFactory factory, NLogProviderOptions options)
{
ConfigureHiddenAssemblies();
using (var provider = new NLogLoggerProvider(options))
{
factory.AddProvider(provider);
}
return factory;
}
You could also create a custom-target, and redirect all non-global-logger messages to this target using NLog rules:
https://github.com/nlog/NLog/wiki/Configuration-file#rules
The custom target can then just forward the log-event to the global-logger:
https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target
You should be careful with cyclic logging. Maybe have a filter in the custom-target to ignore messages from the global-logger.
But I think this is an ugly solution, and I fail to understand the restriction of only one logger-object. Especially when the reason is because it should be named after the application. Why not not a global variable for the name instead of abusing the logger-name?
Alternative you can create a custom target wrapper, that fixes the Logger on LogEventInfo's, so when forwarded to the wrapped target (UDP- / File-target), then it looks like they are all come from the same logger.
Similar to what this guy is trying to do:
https://github.com/NLog/NLog/issues/2352
Again really ugly solution, and should only be used when not able to figure out, how to avoid using the logger-name in the configuration of the wanted Nlog-targets (Ex. configure file-target-filename using something else).
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.
I'm trying to get a list of the available users from the Core Service. I spend quite some time looking at the available service methods and the most obvious seemed to be this:
TrusteesFilterData trusteesFilterData = new TrusteesFilterData
{
BaseColumns = ListBaseColumns.IdAndTitle,
IsPredefined = false,
ItemType = ItemType.User
};
XElement listTrustees = client.GetSystemWideListXml(trusteesFilterData);
However, the code throws an error when calling GetSystemWideListXml - Unable to create Abstract Class. Am I using the correct approach and, if so what am I doing wrong? If not, what should I be doing instead?
Take a look at the samples in the open source project for workflow notification
http://code.google.com/p/tridion-notification-framework/source/browse/NotificationService/NotificationService/Worker.cs
Lines 22 - 26 in the DoWork() method should do what you need - I think need to use UsersFilterData rather than TrusteesFilterData
var users = client.GetSystemWideList(new UsersFilterData { BaseColumns = ListBaseColumns.IdAndTitle, IsPredefined = false });
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)