NLog Web - AspNet-User-Identity without domain - asp.net

I'm currently using the NLog.Web package for writing my .Net logs in my application.
After reading the NLog.Web I've noticed that unlike the ${windows-identity} layout renderer, the ${aspnet-user-identity} layout renderer got no domain parameter for it.
For example, if I want to log the current running windows identity, it logs out: domain\user, but when specifying domain=false, it logs only user.
How do I implement this kind of ability with the ${aspnet-user-identity}? Because when I configured ${aspnet-user-identity:domain=false} it didn't work.

The WindowsIdentity.Name, used in NLog, will always give the full name, including domain.
The logon name is in the form DOMAIN\USERNAME.
https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.name(v=vs.110).aspx
I think you need a custom layout renderer, and split it by-hand on the /.
Something like this: (maybe also add soms checks for outOfIndex)
using NLog.LayoutRenderers;
....
//register ${my-aspnet-user-identity}
LayoutRenderer.Register("my-aspnet-user-identity",
(logEvent) => HttpContext.Current?.User?.Identity?.Name?.Split('/')[1]);
Register it as soon as possible.

I found a different way to solve this issue #Julian
in the NLog.config file, i created a variable:
<variable name="aspnetIdentity" value="${replace:searchFor=^\\w+\\\\:replaceWith=:regex=true:inner=${aspnet-user-identity}}" />
As defined in the variable, the regex searches for at least one word (at the start) and finally searching for a backslash.
the other backslashes are written to escape special characters and also double backslashing. Finally, what was found (it's the domain name) will be replaced with an empty string and therefore I got only the username and not the Domain\Username
Thanks for the help #Julian

Related

Does Kentico allow query strings with question mark?

I'm trying to migrate my ASPX site to Kentico, and as part of my task I'm migrating URLs. I need to preserve my URL structure, so I need to keep URLs which look like : "foo.com/bar.aspx?pageid=1".
I checked page's "URLs" property tried to use wildcards, some patterns like /bar/{pageid}- /bar/{?pageid?}-, etc but Kentico always replaces question marks.
Is there a way to achieve that via the admin interface?
You don't need to do anything in order to use "foo.com/bar.aspx?pageid=1" url.
Create a page under the root and call it bar, so you'll get a page # foo.com/bar.aspx. Kentico and/or .net does not care what you add to a url after question mark, so foo.com/bar.aspx?pageid=1 will work as well as foo.com/bar.aspx?someparam=sdf, or foo.com/bar.aspx?id=1&p=3&t=3.
You may (or may not) implement some functionality based on query string (e.g. paging), so it will parse query string and act in appropriate way.
By default Kentico UI does not handle adding URL aliases with URL parameters like you show. There is an article on the DevNet for a URL Redirection module which has code you can import into your site to allow you to perform these redirects within the Kentico UI. I'd suggest using this approach.
Unfortunately, I can't share a code sample since it's an article but it also has a link to download the code too. This appears to only be coded for Kentico 8.2 right now but I'm guessing you could do some work to make it work for other versions if you needed.
I think there are few concepts that you are clubbing here. I will start with your line code here
/bar/{pageid} - {pageid} is a positional parameter in Kentico's language if you choose to use dynamic URLS based on patterns. SO if you have a code that relies on pageid parameter to fetch some data then Kentico will pass that value. E.g in case of /bar/420, it will pass pageid as 420 different web parts on your template
/bar/{?pageid?} - This will search for query string parameter "pageid" on the request URL and replace its value here. So if you passed foo.com/bar.aspx?pageid=366, the resulting URL will be /bar/366
The #1 is positional parameter and #2 is the way in which Kentico resolves query string macros.
I hope this clarifies.

How can I change this .NET code to File.Exists?

I am working with a framework written in .NET and I do not know .NET. I just need to change this one line where it checks to see if a variable exists, and I need to change it to instead just check on the server to see if the file itself exists.
Here is what is there now:
#if (!string.IsNullOrEmpty(Model.DrawingLink2){
Is this the correct code to change it to check if the file exists instead?
#if (File.Exists(/Portfolio/#(Model.FileNumber)/Images/Large_#(Model.FileNumber)_1.jpg))
You need to map that file, relative to the root of the web application, to the physical file system. You can use HttpServerUtility.MapPath for that. You also need quotes around string literals. The process running the code also needs read access to the directory (very likely the case, just mentioning it to be complete).
#if (File.Exists(HttpServerUtility.MapPath("/Portfolio/#(Model.FileNumber)/Images/Large_#(Model.FileNumber)_1.jpg"))

ASP.net problem with Regional & Language Options (win2k3)

I have a TextBox in an Asp.net form. there is a simple javascript witch separates each three digits in TextBox. it works fine when you enter data in TextBox. I used coma , for separating digits and used dot . as floating point character.
as I said every thing works fine when I am entering data in TextBox. but when the post-back occurs and saved data returns to client, every .(s) has been removed (for example 2.3 saved as 23 and digits in TextBox are separated by . instead of ,.
this problem occurs just in a specific server (windows server 2003 sp1) and works fine in other windows server 2003 (SP1)! I am experiencing this problem for first time!
But I think the problem is because of specific Regional & Language Options in the server. This server is joined to a domain controller. when I change the regional and language options to this set:
Decimal Symbol -> .
Digit Grouping Symbol -> ,
nothing changes.
when I check the following item after customizing settings :
Apply All Settings to the current user account and to the default user profile -> checked
when I restart the Server, It jumps out from domain and need to be re-joined to domain controller! and of-course nothing changes again!
Do you had this problem? any solution please!
I can not post code here, because the code is too complex and I am sure problem is not because of code because it is working every where unless the specified server.
EDIT
Also setting regional and language options for network service user may help to solve the problem. any body knows how can I do this ?
Have you tried using the globalization tag in your web.config? This prevents you from running into trouble when multiple servers are configured differently (ie. different languagepacks).
<configuration>
<system.web>
<globalization
culture="en-US"
uiCulture="en-US" />
</system.web>
</configuration>
After goofing around with a similar problem for WAY to long I did the following with the help of a number of clues (also found on StackOverFlow, StackOverFlow rocks by the way...)
The first thing I did was dump out what the server was actually thinking (Page_Load):
var dtInfo = System.Globalization.DateTimeFormatInfo.CurrentInfo;
DisplayDebugInfo(String.Format(
"Culture({0}/{1}), DateFormat(SD:{2},DS:{3})",
System.Globalization.CultureInfo.CurrentCulture.Name,
System.Globalization.CultureInfo.CurrentUICulture.Name,
dtInfo.ShortDatePattern, dtInfo.DateSeparator));
Also on Windows 2003, I tried fixing the regional setting via the regular control panel but with no success.
I also tried setting the globalization settings in the web.config as mentioned in the other solution but with little effect.
It seems that once you start messing with the regional setting you can quickly get to the point where things are messed up. I decided to avoid messing with the registry and go for a code solution because then I would not have to worry when my code was released to production.
I added the following code to the base class for my page so that it would fix it everywhere. You could also place it in the Page_Load.
using System.Globalization;
using System.Threading;
// Fix the cultural settings...
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
culture.DateTimeFormat.DateSeparator = "/";
Thread.CurrentThread.CurrentCulture = culture;
Problem solved. For me anyway.

ASP.NET routing: Literal sub-segment between tokens, and route values with a character from the literal sub-segment

The reason I'm asking is because IIS protects certain ASP.NET folders, like Bin, App_Data, App_Code, etc. Even if the URL does not map to an actual file system folder IIS rejects a URL with a path segment equal to one of the mentioned names.
This means I cannot have a route like this:
{controller}/{action}/{id}
... where id can be any string e.g.
Catalog/Product/Bin
So, instead of disabling this security measure I'm willing to change the route, using a suffix before the id, like these:
{controller}/{action}_{id} // e.g. Catalog/Product_Bin
{controller}/{action}/_{id} // e.g. Catalog/Product/_Bin
But these routes won't work if the id contains the new delimeter, _ in this case, e.g.
// These URL won't work (I get 404 response)
Catalog/Product_Bin_
Catalog/Product/_Bin_
Catalog/Product/__Bin
Why? I don't know, looks like a bug to me. How can I make these routes work, where id can be any string?
Ok, I have a definitive answer. Yes, this is a bug. However, at this point I regret to say we have no plans to fix it for a couple of reasons:
It's a breaking change and could be a very hard to notice one at that.
There's an easy workaround.
What you can do is change the URL to not have the underscore:
{controller}/{action}/_{id}
Then add a route constraint that requires that the ID parameter starts with an underscore character.
Then within your action method you trim off the underscore prefix from the id parameter. You could even write an action filter to do this for you if you liked. Sorry for the inconvenience.
You can use characters that are not allowed for a directory or file name like: *,?,:,",<,>,|.
With ASP.NET MVC if you look at the source they have a hard-coded value for the path separator (/) and to my knowledge cannot be changed.

Asp.NET / VB.NET: Getting the path from the URL / URI?

Say I have a project that I am deploying at
www.foo.com/path1/default.aspx
and
www.foo.com/path2/default.aspx
What would be the most reliable way to know if I was in the folder "path1", or "path2"? Can I grab that directly, or do I need to split() somehow on the Request.Url.AbsolutePath, or... ?
I just want to change colors, etc. based on which folder the user is in.
Thanks for any assistance!
If you want to code that logic directly into the page, then yeah, I'd go with split() on Request.Url.AbsolutePath.
That said, I'd consider storing this kind of setting in the AppSettings section of web.config. That way if you decide to change the color in path2, you just need to edit the web.config for path2. If you need to add a new path, just deploy there and edit the web.config as appropriate.
Yeah use Request.Url.AbsolutePath.
I do it to create Breadcrumbs, using Split to split the URL, then in your case I suggest to use Switch statement to change color based on the case of the Switch statement
Here is a great article about Paths in ASP.
Check out the MSDN docs on System.IO.Path. It contains a number of useful functions for dealing with path names. You can get GetDirectoryName() or GetFullPath() or GetFileName() or GetFileNameWithoutExtension().

Resources