Let's say you need to create a folder on behalf of a user and protect it from access by anyone but this user. Use DirectorySecurity.SetAccessRuleProtection procedure like this:
DirectoryInfo dir = new DirectoryInfo (DirPath);
if (!dir.Exists)
{
dir.Create();
DirectorySecurity ds = dir.GetAccessControl();
ds.SetAccessRuleProtection(true , false );
ds.AddAccessRule(new FileSystemAccessRule (DomainName + "\\\\" + UserName,
FileSystemRights .FullControl, AccessControlType .Allow));
dir.SetAccessControl(ds);
}
Please be noted that local administrator could request and get access rights even for protected folders. Admins are admins.
4059305d-8abe-416c-96b8-ac6940a9cccc|0|.0
When you try to connect your client App to a server through self-signed SSL certificate (which is normal during development, but obviously is not in production), by default you will get a security exception because such certificate could not be validated. The good approach is to warn user and let him choose whatever he wants to take this risk or not. Add the following code to your class/form to give him such choise. The good idea is to store his response in a local variable and use it to skip this warning in future requests.
ServicePointManager .ServerCertificateValidationCallback = (s, cert, ch, er) =>
{
// Check is this case has been valuated:
if (Program .IsCertVerified)
return true ;
if (er == System.Net.Security.SslPolicyErrors .None)
return true ;
else
{
// Warn user:
if (MessageBox .Show(String .Format("Certificate \\"{0}\\" could not be verified! Do you want to continue?" ,
cert.Subject), "Certificate Warning" ,
MessageBoxButtons .YesNo, MessageBoxIcon .Warning) == System.Windows.Forms.DialogResult .Yes)
{
// Set the local variable to skip this dialog:
Program .IsCertVerified = true ;
return true ;
}
else
{
Program .IsCertVerified = false ;
return false ;
}
}
};
c7164f9e-8a44-4e7a-96ea-df1f81bd3e98|0|.0
Most programmers who work with remote HTTP services prefer to use WebClient over WebRequest/WebResponse because of its simplicity. The only WebClient's feature I missed is ability to customize request timeout interval but fortunatelly it is very easy to fix by creating own class derived from WebClient. Here is how....
public class WebClientEx : WebClient
{
// Timeout in milliseconds
public int Timeout { get ; set ; }
/// <summary>
/// Sets default timeout
/// </summary>
public WebClientEx()
: base ()
{
this .Timeout = 10000;
}
/// <summary>
/// Sets custom timeout
/// </summary>
/// <param name="timeout">Timeout in milliseconds</param>
public WebClientEx(int timeout)
: base ()
{
this .Timeout = timeout;
}
/// <summary>
/// Overriding base method to set timeout
/// </summary>
/// <param name="address">Server Url</param>
/// <returns>A WebRequest with a timeout assigned</returns>
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest wr = base .GetWebRequest(address);
wr.Timeout = this .Timeout;
return wr;
}
}
abb375a3-7c47-4aaf-ae6b-a828fb8e4332|1|5.0
As you know, any Windows Service operates under certain rights. It could be Network Service, Local System or a specific user. IIS process is not an exception. However, sometimes it is necessary to refer to the operating system using a different user account. In such cases your calls to the resources should be impersonalized. Below I'm glad to offer a way you can do it.
class UserImpersonation : IDisposable
{
private bool disposed = false;
[DllImport("advapi32.dll")]
public static extern int LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
WindowsImpersonationContext wic;
string _userName;
string _domain;
string _passWord;
public UserImpersonation(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
public bool ImpersonateValidUser()
{
WindowsIdentity wi;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUser(_userName, _domain, _passWord, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
wi = new WindowsIdentity(tokenDuplicate);
wic = wi.Impersonate();
if (wic != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
private void CleanUp(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (wic != null)
wic.Dispose();
}
RevertToSelf();
}
disposed = true;
}
public void Dispose()
{
CleanUp(true);
GC.SuppressFinalize(this);
}
~UserImpersonation()
{
CleanUp(false);
}
}
And here is how to use this class:
using (UserImpersonation user = new UserImpersonation(UserName, Domain, Password))
{
if (user.ImpersonateValidUser())
{
// Do your work here.
}
else
{
// Something goes wrong. Check it here.
}
}
6b7cc83f-8809-4a46-9821-1a19e96c7990|0|.0
Geolocation manipulations become quite often programming task. Below is a simple function that calculated distance between two coordinates in kilometers. If you prefer miles, simply multiply results by 0.6214.
public static double GetDistance(double Lat1, double Lon1, double Lat2, double Lon2)
{
int R = 6371;
double rLat1 = ToRadian(Lat1);
double rLat2 = ToRadian(Lat2);
double dLat = rLat2 - rLat1;
double dLon = ToRadian(Lon2 - Lon1);
double a = Math .Pow(Math .Sin(dLat / 2), 2) +
Math .Pow(Math .Sin(dLon / 2), 2) *
Math .Cos(rLat1) * Math .Cos(rLat2);
double b = 2 * Math .Atan2(Math .Sqrt(a), Math .Sqrt(1 - a));
return R * b;
}
public static double ToRadian(double Grad)
{
return Math .PI * Grad / 180;
}
Enjoy!
c9597141-4791-4636-aef7-d72fc9bbabfa|0|.0
If you are a web developer who works on a mobile web site, you need to test look and feel of your job at least in major mobile OS. It’s easy if you optimize your site just for iOS or Android and you have these devices physically or their emulators. But in case you can’t, you can use desktop browsers to make this job done by using different user-agent strings. Safari already has something that helps; Chrome (as I heard) has command line switchers; Firefox – a plugin. But what about IE?
IE9 also includes dev tool as well: just press F12 key to bring it on. This is the place where we will put custom user-agent strings. So…
- Open up IE development tools by pressing F12 in IE9 main window.
- Click menu Tools -> Change user agent string -> Custom…
- Put a Friendly Name that will help you to recognize this string.
- Finally put user-agent string to “User Agent String” field and you are done!
Now every time when you will need to test your site with different browsers mode, simply go to IE dev mode (F12), click Tools -> Change user agent string and select a user-agent from the very bottom menu part. Of course, this way just emulate another browser but script and rendering engines will stay the same but this realy helps especially when you need to debug your site when logic is depended from browser that connects to.
When you played enough with custom string, just close IE – user-agent string will return to default, no manual changes required.
Just one thing we left: where to get browser agent strings? I found many sites in the Internet which spread this data and this one is a good example.
f901ed8c-34e5-44bf-a990-de30f73d8680|0|.0
If you call a Web service from your Android App (I believe this should work in other Java Apps as well but personally tested in Android), you probably will want to convert InputStream into a string which is not that simple. And here is simpliest way how to do that:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inStream = new BufferedInputStream(conn.getInputStream());
// Here are we go:
String res = new Scanner(inStream).useDelimiter("\\\\A").next();
}
0a0f90a6-1dcf-4337-8c6d-d73f16ce6013|0|.0
Faced an interesting problem: when I want to change ApplicationBar visibility by by changing instance IsVisible property, I always get NullReference exception. To avoid this use static member instead:
ApplicationBar.IsVisible = true;
Guess why? Because ApplicationBar is not a Silverlight element and general behavior doesn’t apply to it.
Update: the same happens when you want to add/remove a button – so use static Button property.
66eb7d14-deed-41f1-baca-cf2d4afa944c|0|.0
When you gonna run an WCF REST service within an MVC project, you may noticed that you need to add this service to MVC routing table in Global.asax.cs file. By default it is suggested to be like this:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new ServiceRoute("MyRest", new WebServiceHostFactory(), typeof(MyRest)));
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
But in this case each of your ordinary MVC Action Url will be replaced to this: /MyRest?action=Index&controller=Home which won’t work. If you put REST route to the bottom of RegisterRoutes procedure, your service will become unavailable and you’ll get 404 “Not Found” when you try to call it. Sounds like order does matter.
So the only way is to map all your routes together at the same time. Here is how your RegisterRoutes should look like:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { controller = "^(?!MyRest).*" }
);
routes.Add(new ServiceRoute("MyRest", new WebServiceHostFactory(), typeof(MyRest)));
Quite tricky and not obvious at least to me. Have fun coding!
Technorati Tags:
ASP.NET MVC,
RESTful
88cbd550-99c3-49c1-930a-f48376486b9f|2|5.0
Use this snippet when you need to get an Url to virtual root path in your ASP.NET projects. You may need this, for example, when you want to call dynamically a REST Web service which is part of the same project (my story). I have found few ways to do this including storing such kind of info in Web.config file. But below is more short and convenient way. Just don’t forget to add trailing slash to the end because this function doesn’t do it by its self.
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
Hope this helps.
a9e95bdc-5211-4c3c-92e8-4bd48b6b8142|0|.0