Showing posts with label CodeProject. Show all posts
Showing posts with label CodeProject. Show all posts

Friday, June 13, 2014

List Example

What is a List?

A list is a collection of data.


Example

  • Create a new list

//initialize an empty list for objects with type of INTEGER
List<int> numbers = new List<int>();

//initialize an empty list for objects with type of STRING
List<string> names = new List<string>();

//initialize a list with objects type of INTEGER
List<int> numbers = new List<int>() {1,2,3,4}; //List with 4 integer elements

//initialize a list with objects type of STRINGList<string> names = new List<string>() {"Dad","Mum","Child"}; //List with 3 string elements





  • Add elements to a list

//add one element at the end 
numbers.Add(5);

//add a collection of new elements at the end
numbers.AddRange(new List<int>() { 6, 7, 8 });


//add one element at the end 
names.Add("Child2");

//add a collection of new elements at the end
names.AddRange(new List<string>() { "Child3", "Child4" });



//add one element at a defined position
numbers.Insert(8, 9);

//add one element at a defined position
names.Insert(6, "Child5");



//add a collection of new elements starting at a defined position
numbers.InsertRange(9, new List<int>() { 10, 11, 12 });

//add a collection of new elements starting at a defined position

names.InsertRange(7, new List<string>() { "Child6", "Child7" });




  • Remove elements from a list

//remove the object with the value 8 from the list            
numbers.Remove(8);

//remove the opbject with the value Child from the list            
names.Remove("Child");

//remove object at position 3            
numbers.RemoveAt(3);

//remove 2 elements, starting at position 4            
numbers.RemoveRange(4, 2);


Blogverzeichnis blogwolke.de - Das Blog-Verzeichnis Icon RSS Newsfeed Verzeichnis Web-Feed.de Blogverzeichnis FreakDeveloper Contributes to DaniWeb Blogtotal Foxload TopBlogs.de das Original - Blogverzeichnis | Blog Top Liste

Monday, June 2, 2014

Impersonator C#


I think everybody was already at this point... A program should handle file transfers or modifications but the access to the target path is not given to everybody.
How to handle this situation? :-(

One answer could be, to use one common account (inside the program) to do these actions.

I have tried to solve this situation like following:


1) Create a new class "Impersonator"

using System;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.ComponentModel;


namespace Test.Impersonator

{
    public class Impersonator : IDisposable
    {
        public Impersonator(string userName, string domainName, string password)
        {
            ImpersonateValidUser(userName, domainName, password);
        }

        public void Dispose()
        {
            UndoImpersonation();
        }

        [DllImport("advapi32.dll", SetLastError = true)]
        private 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)]
        private static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool CloseHandle(IntPtr handle);

        private const int LOGON32_LOGON_INTERACTIVE = 2;
        private const int LOGON32_PROVIDER_DEFAULT = 0;

        private void ImpersonateValidUser(string userName, string domain, string password)
        {
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            impersonationContext = tempWindowsIdentity.Impersonate();
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(tokenDuplicate);
                }
            }
        }

        private void UndoImpersonation()
        {
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }
        }

        private WindowsImpersonationContext impersonationContext = null;
    }
}



2) Use the Impersonator class in you main program around the function which should run under a different user.

using...
using Test.Impersonator;
namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void StartDataTransfer()
        {

              //Do something as User1
            using (new Impersonator("UserName", "Domain", "Password"))
            {

                     //Do something as User2
            }
        }

    }
}
  


Feel free to ask/feedback :-)

Kind regards,
FreaksOfDeveloper

Blogverzeichnis blogwolke.de - Das Blog-Verzeichnis Icon RSS Newsfeed Verzeichnis Web-Feed.de Blogverzeichnis FreakDeveloper Contributes to DaniWeb Blogtotal Foxload TopBlogs.de das Original - Blogverzeichnis | Blog Top Liste