Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, January 22, 2016

C# .NET Windows UAC - Check if User is in Admin Group

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace UACStatus
{
    ///
    /// 2011 David Moore
    /// http://www.davidmoore.info/blog/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/
    ///
    public class UACSecurity
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength);

        ///
        /// Passed to to specify what
        /// information about the token to return.
        ///
        enum TokenInformationClass
        {
            TokenUser = 1,
            TokenGroups,
            TokenPrivileges,
            TokenOwner,
            TokenPrimaryGroup,
            TokenDefaultDacl,
            TokenSource,
            TokenType,
            TokenImpersonationLevel,
            TokenStatistics,
            TokenRestrictedSids,
            TokenSessionId,
            TokenGroupsAndPrivileges,
            TokenSessionReference,
            TokenSandBoxInert,
            TokenAuditPolicy,
            TokenOrigin,
            TokenElevationType,
            TokenLinkedToken,
            TokenElevation,
            TokenHasRestrictions,
            TokenAccessInformation,
            TokenVirtualizationAllowed,
            TokenVirtualizationEnabled,
            TokenIntegrityLevel,
            TokenUiAccess,
            TokenMandatoryPolicy,
            TokenLogonSid,
            MaxTokenInfoClass
        }

        ///
        /// The elevation type for a user token.
        ///
        enum TokenElevationType
        {
            TokenElevationTypeDefault = 1,
            TokenElevationTypeFull,
            TokenElevationTypeLimited
        }

        public bool CurrentUserIsAdminRole()
        {
            var identity = WindowsIdentity.GetCurrent();
            if (identity == null) throw new InvalidOperationException("Couldn't get the current user identity");
            var principal = new WindowsPrincipal(identity);

            // Check if this user has the Administrator role. If they do, return immediately.
            // If UAC is on, and the process is not elevated, then this will actually return false.
            if (principal.IsInRole(WindowsBuiltInRole.Administrator)) return true;

            // If we're not running in Vista onwards, we don't have to worry about checking for UAC.
            if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
            {
                // Operating system does not support UAC; skipping elevation check.
                return false;
            }

            int tokenInfLength = Marshal.SizeOf(typeof(int));
            IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength);

            try
            {
                var token = identity.Token;
                var result = GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);

                if (!result)
                {
                    var exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                    throw new InvalidOperationException("Couldn't get token information", exception);
                }

                var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);

                switch (elevationType)
                {
                    case TokenElevationType.TokenElevationTypeDefault:
                        // TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.
                        return false;
                    case TokenElevationType.TokenElevationTypeFull:
                        // TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator.
                        return true;
                    case TokenElevationType.TokenElevationTypeLimited:
                        // TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator.
                        return true;
                    default:
                        // Unknown token elevation type.
                        return false;
                }
            }
            finally
            {
                if (tokenInformation != IntPtr.Zero) Marshal.FreeHGlobal(tokenInformation);
            }
        }
    }
}

Monday, January 10, 2011

Taunting dotNET - Rhino Mocks

RhinoMocks is a best-practice Object Mocking Framework for dotNET written by uber-dev Ayende Rahien.

Official RhinoMocks Page

Central Forum - Google Group

Good Intro Examples
- Stephen Walther

http://en.wikibooks.org/wiki/How_to_Use_Rhino_Mocks/Introduction
http://www.ayende.com/wiki/Rhino+Mocks+Introduction.ashx
http://en.wikibooks.org/wiki/How_to_Use_Rhino_Mocks/Introduction
http://house9-code-samples.blogspot.com/2008/02/rhinomocks-basics.html

Martin Fowler - Mocks/Behaviour vs Stubs/State Testing:

... I've also adjusted my vocabulary to match that of the Gerard Meszaros's xUnit patterns book... Meszaros uses the term Test Double as the generic term for any kind of pretend object used in place of a real object for testing purposes... Meszaros then defined four particular kinds of double:

- DUMMY objects are passed around but never actually used. Usually they are just used to fill parameter lists.
- FAKE objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
- STUBS provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
- MOCKS are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Friday, December 17, 2010

MS Castle Windsor [IOC Container] Cheat-Sheet

Martin Fowler
IOC Containers and the Dependency Injection pattern

Wiki: Castle Windsor

Fluent API
Fluent Registration API

INSTANCE REGISTRATION
- Can you register an existing instance of a type?
- Castle Windsor – Registering Existing Object Instances
- Can you register an existing instance of a type in the container?

REGISTRATION & RESOLUTION OF NAMED INSTANCE

IWindsorContainer.Register(Component.For<ClassType>().Named("instanceKey").Instance(instanceOfClassType));

ClassType retrievedInstance = IWindsorContainer.Resolve("instanceKey");

StackOverflow Thread

REGISTER & RESOLVE BASED ON INTERFACE


Register Types Implementing Specified Interface:

container.Register(
AllTypes.
FromThisAssembly(). // register all types from parent assembly
BasedOn). // that inherit/implement interface IDialogService
WithService.FromInterface(). // allow resolution based on interface
Configure(c => c.LifeStyle.Is(LifestyleType.Transient)) // construct new
);

Resolve Instance of Class by Interface

IDialogService dialogService = container.Resolve();



Note on Registering/Resolving Generic Lists by Instance
I have been unable to register & resolve generic lists, e.g. List, by instance.
However, if you wrap the generic list in a custom class, e.g.

public class IntList : List
{
}

then you can register & resolve by instance with no problems.

Monday, December 13, 2010

Re-Usable Controls in WPF

MSDN Article - Developing Reusable Controls with the Model-View-ViewModel Pattern
http://blogs.msdn.com/b/nathannesbit/archive/2009/03/13/developing-reusable-controls-with-the-model-view-viewmodel-pattern.aspx

WPF: Binding to Properties in your UserControl or Window
http://decav.com/blogs/andre/archive/2007/05/27/wpf-binding-to-properties-in-your-usercontrol-or-window.aspx

Thursday, October 21, 2010

WPF Tutorials

http://bea.stollnitz.com/blog/?page_id=47

Sunday, July 11, 2010

Python Client Consumes WCF Web Service


End-Point = ABC
- Address
- Binding
- Contract

WSDL Components

definition
    types
    message
    portType = interface implementation
        operation
            input
            output
    binding = abstract interface
        operation
            documentation
            input
            output
    service
        wsdl:port (name, binding)
            x:address (location)

 
Example Publicly Accessible / iNet WSDL

GlobalWeather.com
- http://www.webservicex.com/globalweather.asmx?wsdl

wsf.cdyne.com
- http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL

thomas-bayer.com
- http://www.thomas-bayer.com/axis2/services/BLZService?wsdl
 
External Links

- Make a SOAP client with Python
- StackOverFlow - How can I consume a WSDL (SOAP) web service in Python?
- SourceForge - Python Web Services Project

Sunday, May 30, 2010

Unit Testing C# with NUnit

MonoDevelop
http://www.dijksterhuis.org/using-nunit-with-monodevelop/

Tuesday, March 23, 2010

DevExpress XtraGrid - Group by Column - Enable/Disable

assuming you have

DevExpress.XtraGrid.GridControl gridControl;
DevExpress.XtraGrid.Views.Grid.GridView gridView;

to enable grouping capability
gridView.OptionsView.ShowGroupPanel = true

to disable
gridView.OptionsView.ShowGroupPanel = false

Wednesday, October 21, 2009

log4net - Force New (Specified) Log File


private static readonly ILog alog = LogManager.GetLogger("AlgoLogger");

public void SwitchToNewUniqueAlgoLogFile(long scheduleID)
{
ILoggerRepository logRepos = LogManager.GetRepository();
IAppender[] logAppenders = logRepos.GetAppenders();

string targetAppenderName = "myAppender"

// first find the logger we are actually looking for

for (int i = 0; i < logAppenders.Length; i++)
{
IAppender appender = logAppenders[i];

if (appender.Name == targetAppenderName )
{
// cast generic appender to our type
RollingFileAppender rfa = appender as RollingFileAppender;

// get full name of current log file
string oldFName = rfa.File;

// extract path
int indexOfLastSlash = oldFName.LastIndexOf(@"\");
string path = oldFName.Substring(0, indexOfLastSlash + 1);

// generate new log file name
string newLogFileName = "newLog.txt"
string newFullFileName = path + newLogFileName;

// set new file name
rfa.File = newFullFileName;

// indicate to change
rfa.ActivateOptions();

break;
}
}
}

Switching Log-Files During Logging



private static readonly ILog alog = LogManager.GetLogger("AlgoLogger");

public void SwitchToNewUniqueAlgoLogFile(long scheduleID)
{
ILoggerRepository logRepos = LogManager.GetRepository();
IAppender[] logAppenders = logRepos.GetAppenders();

string targetAppenderName = "myAppender"

// first find the logger we are actually looking for

for (int i = 0; i < logAppenders.Length; i++)
{
IAppender appender = logAppenders[i];

if (appender.Name == targetAppenderName )
{
// cast generic appender to our type
RollingFileAppender rfa = appender as RollingFileAppender;
string oldFName = rfa.File;
int indexOfLastSlash = oldFName.LastIndexOf(@"\");
string path = oldFName.Substring(0, indexOfLastSlash + 1);

// generate new log file name

string scheduleName = SQLHandler.GetScheduleName(scheduleID);

string newLogFileName = "newLog.txt"
string newFullFileName = path + newLogFileName ;

rfa.File = newFullFileName;
rfa.ActivateOptions();

break;
}
}
}

Wednesday, June 10, 2009

Member Field Serialisation for Config Storage

using System;

using System.Reflection;
using System.IO;
using System.Collections;

namespace ConfigTester
{


public class CFG
{
public int pi = 3;
public string word = "tetragrammatron";
public TimeSpan time = new TimeSpan(1,6,6,6);

public string homeDir = @"/home/david/Desktop/";
public string configFName = "config.cfg";

public CFG()
{
}

// ===== ----- ===== ----- =====

public string FieldToSerial(string fieldName, int fieldValue)
{
return string.Format("{0},{1}", fieldName, fieldValue.ToString());
}

public string FieldToSerial(string fieldName, string fieldValue)
{
return string.Format("{0},{1}", fieldName, fieldValue);
}

public string FieldToSerial(string fieldName, TimeSpan fieldValue)
{
return string.Format("{0},{1},{2},{3},{4}", fieldName, fieldValue.Days, fieldValue.Hours, fieldValue.Minutes, fieldValue.Seconds);
}

// ===== ----- ===== ----- =====

public string[] FieldsToSerial()
{
ArrayList lines = new ArrayList();

Type cfgType = typeof(CFG);
FieldInfo[] fieldInfos = cfgType.GetFields();

foreach (FieldInfo fieldInfo in fieldInfos)
{
string name = fieldInfo.Name;
Type fieldType = fieldInfo.FieldType;

if (fieldInfo.FieldType == typeof(string))
{
string val = (string)(fieldInfo.GetValue(this));
lines.Add(this.FieldToSerial(name, val));
}

if (fieldInfo.FieldType == typeof(int))
{
int val = (int)(fieldInfo.GetValue(this));
lines.Add(this.FieldToSerial(name, val));
}

if (fieldInfo.FieldType == typeof(TimeSpan))
{
TimeSpan val = (TimeSpan)(fieldInfo.GetValue(this));
lines.Add(this.FieldToSerial(name, val));
}
}

int fieldCount = lines.Count;

string[] fields = new string[fieldCount];

for (int fieldNum = 1; fieldNum <= fieldCount; fieldNum++)
fields[fieldNum - 1] = (string)(lines[fieldNum - 1]);

return fields;
}

// ===== ----- ===== ----- =====

public void ListFieldInfo()
{

Console.WriteLine();
Console.WriteLine("FIELD INFO");
Console.WriteLine();

Type cfgType = typeof(CFG);
FieldInfo[] fieldInfos = cfgType.GetFields();

foreach (FieldInfo fieldInfo in fieldInfos)
{
string name = fieldInfo.Name;
Console.WriteLine("name: {0}", name);

Type fieldType = fieldInfo.FieldType;
Console.WriteLine("type: {0}", fieldType);

object obj = fieldInfo.GetValue(this);
Console.WriteLine("value: {0}", obj.ToString());

Console.WriteLine();
}

Console.WriteLine("{0} fields", fieldInfos.Length);
}

// ===== ----- ===== ----- =====

public void SerializeFields()
{
string fullFName = this.homeDir + this.configFName;

try
{
FileStream fileStream = new FileStream(fullFName, FileMode.Create);
StreamWriter streamWriter = new StreamWriter(fileStream);

this.SerializeFields(streamWriter);

streamWriter.Close();
}
catch (Exception exc)
{
throw new Exception("ConfigSaveException");
}
}

// ===== ----- ===== ----- =====

public void SerializeFields(TextWriter tw)
{
string[] lines = this.FieldsToSerial();

foreach (string line in lines)
tw.WriteLine(line);
}

// ===== ----- ===== ----- =====
// ===== ----- ===== ----- =====
// ===== ----- ===== ----- =====

// ===== ----- ===== ----- =====

public void LoadSerialised()
{
string fullFName = this.homeDir + this.configFName;

ArrayList lines = new ArrayList();

try
{
FileStream fileStream = new FileStream(fullFName, FileMode.Open);
StreamReader streamReader = new StreamReader(fileStream);

string line;
while ((line = streamReader.ReadLine()) != null)
lines.Add(line);

streamReader.Close();

int fieldCount = lines.Count;

string[] serials = new string[fieldCount];
for (int fieldNum = 1; fieldNum <= fieldCount; fieldNum++)
serials[fieldNum - 1] = (string)(lines[fieldNum - 1]);

this.FieldsFromSerials(serials);
}
catch (Exception exc)
{
throw new Exception("ConfigLoadException");
}
}

// ===== ----- ===== ----- =====

public string StringFromSerial(string serial)
{
return serial;
}

// ===== ----- ===== ----- =====

public int IntFromSerial(string serial)
{
return Convert.ToInt32(serial);
}

// ===== ----- ===== ----- =====

public TimeSpan TimeSpanFromSerial(string serial)
{
string[] vals = serial.Split(',');

if (vals.Length != 4)
throw new Exception("timespan serial has incorrect number of variables");

int days = Convert.ToInt32(vals[0]);
int hrs = Convert.ToInt32(vals[1]);
int mins = Convert.ToInt32(vals[2]);
int secs = Convert.ToInt32(vals[3]);

return new TimeSpan(days, hrs, mins, secs);
}

// ===== ----- ===== ----- =====

public string MatchKey(string key, string[] keys, string[] values)
{
if (keys.Length != values.Length)
throw new Exception("key count must match value count, but does not");

for (int num = 1; num <= keys.Length; num++)
if (key == keys[num - 1])
return values[num - 1];

return null;
}

// ===== ----- ===== ----- =====

public void FieldsFromSerials(string[] serials)
{
// separate names & serialised form of fields retrieved from storage

int fieldCount = serials.Length;

string[] names = new string[fieldCount];
string[] forms = new string[fieldCount];

for (int fieldNum = 1; fieldNum <= fieldCount; fieldNum++)
{
int splitMarker = serials[fieldNum - 1].IndexOf(',');

string name = serials[fieldNum - 1].Substring(0, splitMarker);
string form = serials[fieldNum - 1].Substring(splitMarker + 1);

names[fieldNum - 1] = name;
forms[fieldNum - 1] = form;
}

// scan through this instantiated object

Type cfgType = typeof(CFG);
FieldInfo[] fieldInfos = cfgType.GetFields();

foreach (FieldInfo fieldInfo in fieldInfos)
{
string name = fieldInfo.Name;
Type fieldType = fieldInfo.FieldType;

string serialString = this.MatchKey(name, names, forms);

if (fieldInfo.FieldType == typeof(string))
{
string val = this.StringFromSerial(serialString);
fieldInfo.SetValue(this, val);
}

if (fieldInfo.FieldType == typeof(int))
{
int val = this.IntFromSerial(serialString);
fieldInfo.SetValue(this, val);
}

if (fieldInfo.FieldType == typeof(TimeSpan))
{
TimeSpan val = this.TimeSpanFromSerial(serialString);
fieldInfo.SetValue(this, val);
}
}

}

// ===== ----- ===== ----- =====

} // class
} // namespace

Monday, May 25, 2009

GTK-Sharp: Scrollable (Window) Table Example



using System;
using Gtk;

namespace gtkTest
{

public class WinTable
{

private Gtk.ScrolledWindow sWinRef;
private Table table;

private uint rowCount, colCount, rowSpacing, colSpacing;

// ==========================================================

public WinTable(uint pRowCount, uint pColCount, uint pRowSpacing, uint pColSpacing, Gtk.ScrolledWindow pSWinRef)
{
sWinRef = pSWinRef;

rowCount = pRowCount;
colCount = pColCount;

rowSpacing = pRowSpacing;
colSpacing = pColSpacing;

bool homogeneous = true;
table = new Table (rowCount, colCount, homogeneous);

for (uint rowNum = 1; rowNum <= rowCount; rowNum++)
table.SetRowSpacing(rowNum - 1, rowSpacing);

for (uint colNum = 1; colNum <= colCount; colNum++)
table.SetColSpacing(colNum - 1, colSpacing);

sWinRef.AddWithViewport(table);
}

// ==========================================================

/* for e.g. = 2 x 2 table, say (horiz,vert), then

(0,0) (1,0) (2,0)

(0,1) (1,1) (2,1)

(0,2) (1,2) (2,2)

*/

public void PackWidgetAtXY(Widget widget, uint x, uint y)
{
uint leftAttach = x - 1;
uint rightAttach = x;
uint topAttach = y - 1;
uint bottomAttach = y;

//Gtk.AttachOptions xOptions = new Gtk.AttachOptions(); // fill, shrink, expand

table.Attach(widget, leftAttach, rightAttach, topAttach, bottomAttach);
widget.Show();
}

// ==========================================================

public void Demo()
{

for (uint rowNum = 1; rowNum <= rowCount; rowNum++)
for (uint colNum = 1; colNum <= colCount; colNum++)
{
string text = "one\ntwo\nthree\nfour";
Label label = new Label(text);
this.PackWidgetAtXY(label, rowNum, colNum);
}

this.table.Show();
}


// ==========================================================
}


//####################################################

public partial class MainWindow: Gtk.Window
{
public MainWindow (): base (Gtk.WindowType.Toplevel)
{
Build ();
}

protected void OnDeleteEvent (object sender, DeleteEventArgs a)
{
Application.Quit ();
a.RetVal = true;
}
}

//####################################################

class MainClass
{
public static void Main (string[] args)
{
Application.Init ();
MainWindow mainWin = new MainWindow ();

uint rowCount = 8, colCount = 7;
uint rowSpacing = 80, colSpacing = 200;

mainWin.ShowAll();

Window priWin = new Window("Primary Window");
priWin.SetDefaultSize(250, 200);
priWin.SetPosition(WindowPosition.Center);

Gtk.ScrolledWindow sWin = new Gtk.ScrolledWindow();
sWin.SetPolicy(Gtk.PolicyType.Always, Gtk.PolicyType.Always);

priWin.Add(sWin);
sWin.Show();

WinTable winTable = new WinTable(rowCount, colCount, rowSpacing, colSpacing, sWin);
winTable.Demo();

priWin.Show();

Application.Run ();
}
}

}