November 28, 2012

C# - Accessing Remote File By Using Impersonation

Sometime we may face “Could not create the file” or “Access denied on 'Some file Name' ” or "Unable to copy file. Access to the path is denied"  error while try to access or modify a file on a remote machine. After reviewing the code you find out, that because the current user does not have access on a remote machine.

Now we want to force your application to do some restricted activity by a user that who not having privileges to do. we call this procedure Impersonation.

In General Impersonation is, A person act like another.

Unprivileged user can access remote machine like privileged one by using privileged users credentials.

We can achieve Impersonation in may ways, I`m taking "WNetCancelConnection2" function from  GAC dll ("mpr.dll").

Note:
mpr.dll is a module containing functions used to handle communication between the Windows operating system and the installed network providers.

Download Here or copy and use below Remote Access Helper class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Net;
 
namespace SomeNamespace.Utility
{
    public class RemoteAccessHelper
    {
        public class NetworkConnection : IDisposable
        {
            string _networkName;
 
            public NetworkConnection(string networkName, NetworkCredential credentials)
            {
                _networkName = networkName;
 
                var netResource = new NetResource()
                {
                    Scope = ResourceScope.GlobalNetwork,
                    ResourceType = ResourceType.Disk,
                    DisplayType = ResourceDisplaytype.Share,
                    RemoteName = networkName
                };
 
                var result = WNetAddConnection2(
                    netResource,
                    credentials.Password,
                    credentials.UserName,
                    0);
 
                if (result != 0)
                {
                    throw new Win32Exception(result, "Error connecting to remote share");
                }
            }
 
            ~NetworkConnection()
            {
                Dispose(false);
            }
 
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
 
            protected virtual void Dispose(bool disposing)
            {
                WNetCancelConnection2(_networkName, 0, true);
            }
 
            [DllImport("mpr.dll")]
            private static extern int WNetAddConnection2(NetResource netResource,
                string password, string username, int flags);
 
            [DllImport("mpr.dll")]
            private static extern int WNetCancelConnection2(string name, int flags,
                bool force);
        }
 
        [StructLayout(LayoutKind.Sequential)]
        public class NetResource
        {
            public ResourceScope Scope;
            public ResourceType ResourceType;
            public ResourceDisplaytype DisplayType;
            public int Usage;
            public string LocalName;
            public string RemoteName;
            public string Comment;
            public string Provider;
        }
 
        public enum ResourceScope : int
        {
            Connected = 1,
            GlobalNetwork,
            Remembered,
            Recent,
            Context
        };
 
        public enum ResourceType : int
        {
            Any = 0,
            Disk = 1,
            Print = 2,
            Reserved = 8,
        }
 
        public enum ResourceDisplaytype : int
        {
            Generic = 0x0,
            Domain = 0x01,
            Server = 0x02,
            Share = 0x03,
            File = 0x04,
            Group = 0x05,
            Network = 0x06,
            Root = 0x07,
            Shareadmin = 0x08,
            Directory = 0x09,
            Tree = 0x0a,
            Ndscontainer = 0x0b
        }
    }
}


Below i`m describing some piece of code to show, how to use RemoteAccessHelper.cs ?

var oNetworkCredential = 
    new System.Net.NetworkCredential()
    {
        Domain = "domainName",
        UserName = "domainName" + "\\" + "admin login name",
        Password = "admin password"
    };
            
using (new RemoteAccessHelper.NetworkConnection(@"\\" + "domainName", oNetworkCredential))
{
    String[] sFolderNames = Directory.GetDirectories( "domainName" + "\\FolderName");
    foreach (String sFolderName in sFolderNames)
    {
        string[] sarrZipFiles = Directory.GetFiles(sFolderName, "*.txt");
        foreach (String sFile in sarrZipFiles)
        {
            // Some unprivileged operations
        }
    }
}
Source: Stackoverflow

November 26, 2012

Fixed - AJAX AsyncFileUpload is Not Working in IE9


Today i got a mail from client, says that "File Upload functionality not seems working."
I went to site and find out.
 "AJAX AsyncFileUpload control not access-able, It was enabled false" 
i knew, Problem not made by me, it from somewhere. After plugging my hair for an hour,  got this solution.
Problem not comes from CSS, Script or Code Behind,

Solution:
Problem was, i`m using AJAX control tool kit version 3.5.40412.2, This one not up-to-date, It having errors with IE9.

Download Latest version of Ajax Control Toolkit Or use the below one.
http://ajaxcontroltoolkit.codeplex.com/releases/view/63654
The new release solved my AsyncFileUpload problem with IE 9.

Jason Overview - Cascade Dropdown Using JSON

Javascript
Below i have specified sample of cascaded Dropdown using JSON.

function fnDrpChange()
{
try
{
 
var countries =
{
    "table" :
    [
        {"countryid": "0", "countryname": "Japan"},
        {"countryid": "1", "countryname": "India"},
        {"countryid": "2", "countryname": "Pakistan"},
        {"countryid": "3", "countryname": "Srilanka"}
    ]
};
 
var listItems ="";
for (var i = 0; i < countries.table.length; i++) {
    listItems += "<option value='" + countries.table[i].countryid + "'>" + countries.table[i].countryname + "</option>";
}
document.getElementById("ddlcountries").innerHTML =listItems;
}
catch(e)
{
alert(e);
}
}
 
 
function fnCountryChange(countryid)
{
try
{
 
var states =
{
    "table" :
    [
        {"countryid": "1", "stateid": "1", "statename": "TamilNadu"},
        {"countryid": "1", "stateid": "2", "statename": "Andra"},
        {"countryid": "1", "stateid": "3", "statename": "Kerala"}
    ]
};
 
 
var listItems ="";
for (var i = 0; i < states.table.length; i++) {
if(countryid == states.table[i].countryid)
{
    listItems += "<option value='" + states.table[i].stateid + "'>" + states.table[i].statename + "</option>";
}
}
document.getElementById("ddlstates").innerHTML =listItems;
}
catch(e)
{
alert(e);
}
}

Click Here to See Demo