DelegateCommand

/// <summary>
/// Provides a simple ICommand implementation.
/// </summary>
// metadata token 020001E2
public class DelegateCommand : System.Object, System.Windows.Input.ICommand
{
	private readonly System.Action<object > execute;
	private readonly System.Predicate<object > canExecute;
	private System.Collections.Generic.List<System.WeakReference > canExecuteChangedHandlers;

	// metadata token 06001564
	public DelegateCommand(System.Action<object > execute) {}

	// metadata token 06001565
	public DelegateCommand(System.Action<object > execute, System.Predicate<object > canExecute) {
		if (execute == null)
		{
			throw new ArgumentNullException("execute");
		}
		this.execute = execute;
		this.canExecute = canExecute;
	}

	/// <summary>
	/// Raises the CanExecuteChanged event.
	/// </summary>
	// metadata token 06001568
	public void InvalidateCanExecute() {}

	/// <summary>
	/// Defines the method that determines whether the command can execute in its current
	/// state.
	/// </summary>
	/// <param name="parameter">Data used by the command. If the command does not require
	/// data to be passed, this object can be set to null.</param>
	/// <returns>
	/// True if this command can be executed, otherwise - false.
	/// </returns>
	// metadata token 06001569
	public bool CanExecute(object parameter) {}

	/// <summary>
	/// Defines the method to be called when the command is invoked.
	/// </summary>
	/// <param name="parameter">Data used by the command. If the command does not require
	/// data to be passed, this object can be set to null.</param>
	// metadata token 0600156A
	public void Execute(object parameter) {}


	/// <summary>
	/// Occurs when changes occur that affect whether the command should execute.
	/// </summary>
	public virtual event System.EventHandler CanExecuteChanged;
}



.net шифрование RSA с помощью открытого или закрытого ключа

Для начала нам нужно получить открытый и закрытый ключи, далее их нужно где-то сохранить для последующей работы.

Затем взять нужные данные, сконвертировать их в массив байтов и зашифровать
Ну а затем расшифровать.

Собственно открытым мы шифруем, закрытым дешифруем.


Собственно вот пример кода который все иллюстрирует

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            RSACryptoServiceProvider RsaKey = new RSACryptoServiceProvider();
            string publickey = RsaKey.ToXmlString(false); //получим открытый ключ
            string privatekey = RsaKey.ToXmlString(true); //получим закрытый ключ

           

            File.WriteAllText("private.xml", privatekey, Encoding.UTF8);
            File.WriteAllText("public.xml", publickey, Encoding.UTF8);


            byte[] EncryptedData;
            byte[] data = new byte[1024];
            data = Encoding.UTF8.GetBytes("Hello");
            EncryptedData = RsaKey.Encrypt(data, false);


            byte[] DecryptedData = new byte[1024];
            DecryptedData = RsaKey.Decrypt(EncryptedData, false);


            RSACryptoServiceProvider RsaKey_n = new RSACryptoServiceProvider();
            RsaKey_n.FromXmlString(publickey + privatekey); //можно использовать только открытый ключ, или пару открытый и закрыты 
            DecryptedData = new byte[1024];
            DecryptedData = RsaKey.Decrypt(EncryptedData, false);


            Console.Read();
        }
     }
       
}

Счетчики производительности ASP.NET и не только

public static class PerfomanceCounters
    {
        private static readonly PerformanceCounter cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        private static readonly PerformanceCounter memUsage = new PerformanceCounter("Memory", "Available MBytes");
        private static readonly PerformanceCounter pageUsage = new PerformanceCounter("Paging File", "% Usage", "_Total");
        private static readonly PerformanceCounter procCount = new PerformanceCounter("System", "Processes");
        private static readonly PerformanceCounter threadCount = new PerformanceCounter("System", "Threads");
        private static readonly PerformanceCounter contextSwith = new PerformanceCounter("System", "Context Switches/sec");
        private static readonly PerformanceCounter uptime = new PerformanceCounter("System", "System Up Time");

        //http://msdn.microsoft.com/en-us/library/ms972959.aspx
        private static readonly PerformanceCounter process_1 = new PerformanceCounter("Process", "% Processor Time","_Total"); //тотал - типа для всех, но мы то понимает что нам нужно
        private static readonly PerformanceCounter process_2 = new PerformanceCounter("Process", "Handle Count", "_Total");
        private static readonly PerformanceCounter process_3 = new PerformanceCounter("Process", "Thread Count", "_Total");
        private static readonly PerformanceCounter process_4 = new PerformanceCounter("Process", "Private Bytes", "_Total");
        private static readonly PerformanceCounter process_5 = new PerformanceCounter("Process", "Virtual Bytes", "_Total");

        //private static readonly PerformanceCounter ws_1 = new PerformanceCounter("Web Service", "Current Connections");
        //private static readonly PerformanceCounter ws_2 = new PerformanceCounter("Web Service", "Total Method Requests/sec");
        //private static readonly PerformanceCounter ws_3 = new PerformanceCounter("Web Service", "ISAPI Extension Requests/sec");

        //http://msdn.microsoft.com/en-us/library/fxk122b4(v=vs.100).aspx
        //http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/a8c5b994-7722-4dc6-a246-7dfe667c6816.mspx?mfr=true
        private static readonly PerformanceCounter aspnet_1 = new PerformanceCounter("ASP.NET", "Application Restarts");
        private static PerformanceCounter aspnet_2 = new PerformanceCounter("ASP.NET", "Applications Running");
        private static readonly PerformanceCounter aspnet_3 = new PerformanceCounter("ASP.NET", "Requests Disconnected");
        private static readonly PerformanceCounter aspnet_4 = new PerformanceCounter("ASP.NET", "Requests Queued");
        private static readonly PerformanceCounter aspnet_5 = new PerformanceCounter("ASP.NET", "Requests Rejected");
        private static readonly PerformanceCounter aspnet_6 = new PerformanceCounter("ASP.NET", "Request Wait Time");
        private static readonly PerformanceCounter aspnet_8 = new PerformanceCounter("ASP.NET", "State Server Sessions Abandoned");
        private static readonly PerformanceCounter aspnet_9 = new PerformanceCounter("ASP.NET", "State Server Sessions Timed Out");
        private static readonly PerformanceCounter aspnet_10 = new PerformanceCounter("ASP.NET", "State Server Sessions Total");
        private static readonly PerformanceCounter aspnet_11 = new PerformanceCounter("ASP.NET", "Worker Process Restarts");
        private static PerformanceCounter aspnet_12 = new PerformanceCounter("ASP.NET", "Worker Processes Running");

        private static readonly PerformanceCounter aspnetApp_1 = new PerformanceCounter("ASP.NET Applications", "Anonymous Requests", "__Total__");//или имя другое какие-то
        private static readonly PerformanceCounter aspnetApp_2 = new PerformanceCounter("ASP.NET Applications", "Anonymous Requests/Sec", "__Total__");
        private static readonly PerformanceCounter aspnetApp_3 = new PerformanceCounter("ASP.NET Applications", "Cache Total Entries", "__Total__");
        private static readonly PerformanceCounter aspnetApp_4 = new PerformanceCounter("ASP.NET Applications", "Cache Total Hits", "__Total__");
        private static readonly PerformanceCounter aspnetApp_5 = new PerformanceCounter("ASP.NET Applications", "Cache Total Misses", "__Total__");
        private static readonly PerformanceCounter aspnetApp_6 = new PerformanceCounter("ASP.NET Applications", "Cache Total Hit Ratio", "__Total__");
        private static readonly PerformanceCounter aspnetApp_7 = new PerformanceCounter("ASP.NET Applications", "Cache Total Turnover Rate", "__Total__");
        private static readonly PerformanceCounter aspnetApp_8 = new PerformanceCounter("ASP.NET Applications", "Cache API Entries", "__Total__");
        private static readonly PerformanceCounter aspnetApp_9 = new PerformanceCounter("ASP.NET Applications", "Cache API Hits", "__Total__");
        private static readonly PerformanceCounter aspnetApp_10 = new PerformanceCounter("ASP.NET Applications", "Cache API Misses", "__Total__");
        private static readonly PerformanceCounter aspnetApp_11 = new PerformanceCounter("ASP.NET Applications", "Cache API Hit Ratio", "__Total__");
        private static readonly PerformanceCounter aspnetApp_12 = new PerformanceCounter("ASP.NET Applications", "Cache API Turnover Rate", "__Total__");
        private static readonly PerformanceCounter aspnetApp_13 = new PerformanceCounter("ASP.NET Applications", "Compilations Total", "__Total__");
        private static readonly PerformanceCounter aspnetApp_14 = new PerformanceCounter("ASP.NET Applications", "Debugging Requests", "__Total__");
        private static readonly PerformanceCounter aspnetApp_15 = new PerformanceCounter("ASP.NET Applications", "Errors During Preprocessing", "__Total__");
        private static readonly PerformanceCounter aspnetApp_16 = new PerformanceCounter("ASP.NET Applications", "Errors During Compilation", "__Total__");
        private static readonly PerformanceCounter aspnetApp_17 = new PerformanceCounter("ASP.NET Applications", "Errors During Execution", "__Total__");
        private static readonly PerformanceCounter aspnetApp_18 = new PerformanceCounter("ASP.NET Applications", "Errors Unhandled During Execution", "__Total__");
        private static readonly PerformanceCounter aspnetApp_19 = new PerformanceCounter("ASP.NET Applications", "Errors Unhandled During Execution/Sec", "__Total__");
        private static readonly PerformanceCounter aspnetApp_20 = new PerformanceCounter("ASP.NET Applications", "Errors Total", "__Total__");
        private static readonly PerformanceCounter aspnetApp_21 = new PerformanceCounter("ASP.NET Applications", "Errors Total/Sec", "__Total__");
        private static readonly PerformanceCounter aspnetApp_22 = new PerformanceCounter("ASP.NET Applications", "Output Cache Entries", "__Total__");
        private static readonly PerformanceCounter aspnetApp_23 = new PerformanceCounter("ASP.NET Applications", "Output Cache Hits", "__Total__");
        private static readonly PerformanceCounter aspnetApp_24 = new PerformanceCounter("ASP.NET Applications", "Output Cache Misses", "__Total__");
        private static readonly PerformanceCounter aspnetApp_25 = new PerformanceCounter("ASP.NET Applications", "Output Cache Hit Ratio", "__Total__");
        private static readonly PerformanceCounter aspnetApp_26 = new PerformanceCounter("ASP.NET Applications", "Output Cache Turnover Rate", "__Total__");
        private static readonly PerformanceCounter aspnetApp_27 = new PerformanceCounter("ASP.NET Applications", "Pipeline Instance Count", "__Total__");
        private static readonly PerformanceCounter aspnetApp_28 = new PerformanceCounter("ASP.NET Applications", "Request Bytes In Total", "__Total__");
        private static readonly PerformanceCounter aspnetApp_29 = new PerformanceCounter("ASP.NET Applications", "Request Bytes Out Total", "__Total__");
        private static readonly PerformanceCounter aspnetApp_30 = new PerformanceCounter("ASP.NET Applications", "Requests Executing", "__Total__");
        private static readonly PerformanceCounter aspnetApp_31 = new PerformanceCounter("ASP.NET Applications", "Requests Failed", "__Total__");
        private static readonly PerformanceCounter aspnetApp_32 = new PerformanceCounter("ASP.NET Applications", "Requests Total", "__Total__");
        private static readonly PerformanceCounter aspnetApp_33 = new PerformanceCounter("ASP.NET Applications", "Requests/Sec", "__Total__");
        private static readonly PerformanceCounter aspnetApp_34 = new PerformanceCounter("ASP.NET Applications", "Sessions Active", "__Total__");
        private static readonly PerformanceCounter aspnetApp_35 = new PerformanceCounter("ASP.NET Applications", "Sessions Abandoned", "__Total__");
        private static readonly PerformanceCounter aspnetApp_36 = new PerformanceCounter("ASP.NET Applications", "Sessions Timed Out", "__Total__");
        private static readonly PerformanceCounter aspnetApp_37 = new PerformanceCounter("ASP.NET Applications", "Sessions Total", "__Total__");
        private static readonly PerformanceCounter aspnetApp_38 = new PerformanceCounter("ASP.NET Applications", "Transactions Aborted", "__Total__");
        private static readonly PerformanceCounter aspnetApp_39 = new PerformanceCounter("ASP.NET Applications", "Transactions Committed", "__Total__");
        private static readonly PerformanceCounter aspnetApp_40 = new PerformanceCounter("ASP.NET Applications", "Transactions Total", "__Total__");
        private static readonly PerformanceCounter aspnetApp_41 = new PerformanceCounter("ASP.NET Applications", "Transactions/Sec", "__Total__");
        private static readonly PerformanceCounter aspnetApp_42 = new PerformanceCounter("ASP.NET Applications", "Session State Server Connections Total", "__Total__");
        private static readonly PerformanceCounter aspnetApp_43 = new PerformanceCounter("ASP.NET Applications", "Session SQL Server Connections Total", "__Total__");

        private static List<PerformanceCounter> netUsage;

        private static System.Timers.Timer timer;

        public static void Start()
        {
            netUsage = GetNetCounters();
            timer = new System.Timers.Timer();
            timer.Elapsed += tmr_Elapsed;
            timer.Interval = 1000;
            timer.Start();
        }

        public static void Stop()
        {
            if (timer != null)
            {
                timer.Stop();
            }
        }

        private static void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //cont.Children.Clear();
            //cont.Children.Add(new Label() { Content = "Processor " + cpuUsage.NextValue() + " %" });
            // cont.Children.Add(new Label() { Content = "memory free  " + memUsage.NextValue() + " mb" });

            //var w1 = ws_1.NextValue();
            //var w2 = ws_2.NextValue();
            //var w3 = ws_3.NextValue();

            var SS1 = process_1.NextValue();
            var SS2 = process_2.NextValue();
            var SS3 = process_2.NextValue();
            var SS4 = process_2.NextValue();
            var SS5 = process_2.NextValue();

            var x1 = aspnet_1.NextValue(); 
            //var x2 = aspnet_2.NextValue();  
            var x3 = aspnet_3.NextValue();  
            var x4 = aspnet_4.NextValue();  
            var x5 = aspnet_5.NextValue();  
            var x6 = aspnet_6.NextValue();  
            var x8 = aspnet_8.NextValue();  
            var x9 = aspnet_9.NextValue();  
            var x10 = aspnet_10.NextValue(); 
            var x11 = aspnet_11.NextValue();
            var x12 = aspnet_12.NextValue(); 

            var a1 = aspnetApp_1.NextValue();
            var a2 = aspnetApp_2.NextValue();
            var a3 = aspnetApp_3.NextValue();
            var a4 = aspnetApp_4.NextValue();
            var a5 = aspnetApp_5.NextValue();
            var a6 = aspnetApp_6.NextValue();
            var a7 = aspnetApp_7.NextValue();
            var a8 = aspnetApp_8.NextValue();
            var a9 = aspnetApp_9.NextValue();
            var a10 = aspnetApp_10.NextValue();
            var a11 = aspnetApp_11.NextValue();
            var a12 = aspnetApp_12.NextValue();
            var a13 = aspnetApp_13.NextValue();
            var a14 = aspnetApp_14.NextValue();
            var a15 = aspnetApp_15.NextValue();
            var a16 = aspnetApp_16.NextValue();
            var a17 = aspnetApp_17.NextValue();
            var a18 = aspnetApp_18.NextValue();
            var a19 = aspnetApp_19.NextValue();
            var a20 = aspnetApp_20.NextValue();
            var a21 = aspnetApp_21.NextValue();
            var a22 = aspnetApp_22.NextValue();
            var a23 = aspnetApp_23.NextValue();
            var a24 = aspnetApp_24.NextValue();
            var a25 = aspnetApp_25.NextValue();
            var a26 = aspnetApp_26.NextValue();
            var a27 = aspnetApp_27.NextValue();
            var a28 = aspnetApp_28.NextValue();
            var a29 = aspnetApp_29.NextValue();
            var a30 = aspnetApp_30.NextValue();
            var a31 = aspnetApp_31.NextValue();
            var a32 = aspnetApp_32.NextValue();
            var a33 = aspnetApp_33.NextValue();
            var a34 = aspnetApp_34.NextValue();
            var a35 = aspnetApp_35.NextValue();
            var a36 = aspnetApp_36.NextValue();
            var a37 = aspnetApp_37.NextValue();
            var a38 = aspnetApp_38.NextValue();
            var a39 = aspnetApp_39.NextValue();
            var a40 = aspnetApp_40.NextValue();
            var a41 = aspnetApp_41.NextValue();

            var cpu = cpuUsage.NextValue();
            var memory = memUsage.NextValue();
            var proc = procCount.NextValue();
            var therd = threadCount.NextValue();
            var mem1 = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory;
            var mem2 = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailableVirtualMemory;
            var mem3 = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
            var mem4 = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalVirtualMemory;
            var comp = new Microsoft.VisualBasic.Devices.Computer();
            var serv = new Microsoft.VisualBasic.Devices.ServerComputer();
            var net = new Microsoft.VisualBasic.Devices.Network();
            var swit = contextSwith.NextValue();

            foreach (var item in netUsage)
            {
                // cont.Children.Add(new Label() { Content = "network  " + item.NextValue() });
            }
        }

        private static List<PerformanceCounter> GetNetCounters()
        {
            string filter = "MS TCP Loopback interface";
            List<string> nics = new List<string>();
            PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface", System.Environment.MachineName);
            if (category.GetInstanceNames() != null)
            {
                foreach (string nic in category.GetInstanceNames())
                {
                    if (!nic.Equals(filter, StringComparison.InvariantCultureIgnoreCase))
                    {
                        nics.Add(nic);
                    }
                }
                List<PerformanceCounter> nicCounters = new List<PerformanceCounter>();
                foreach (string nicInstance in nics)
                {
                    nicCounters.Add(new PerformanceCounter("Network Interface", "Bytes Total/sec", nicInstance, System.Environment.MachineName));
                }
                return nicCounters;
            }
            else
            {
                return null;
            }
        }
    }

.Net локализация ресурсов .NET

Внезапно открыл для себя дополенение к Visual Studio Resource Translator от Microsoft. ( http://visualstudiogallery.msdn.microsoft.com/c23de518-d3bc-4b1a-a8d8-6ce43fdb2ff4?SRC=VSIDE )
Ставить его можно прямо из Visual Studio.
После установки жмете правой кнопкой на файле ресурсов который нужно локализировать выби��аете язык и вперед.

Тип значения по умолчанию не совпадает с типом свойства (The default style does not match the type of the property) XAML

Когда вы делаете DependencyProperty и  у вас появляеться подобная ошбика – это говорит о том что вы не указали значение по умолчинию

public List<bool> SomeList
{
	get { return (List<bool>)GetValue(SomeListProperty); }
	set { SetValue(SomeListProperty, value); }
}

public static readonly DependencyProperty SomeListProperty =
DependencyProperty.Register("SomeList", typeof(List<bool>), 
typeof(MyControl), new PropertyMetadata(new List<bool>()));

Обратите внимания на последний параметр
new PropertyMetadata(new List<bool>()));

именно тут нужно указать значение по умолчанию для вашего параметра

Еще немного о счетчиках в .NET

Внезапно, если подключить библиотеку Microsoft.VisualBasic
То тогда можно получить нормальный доступ к счетчиками памяти

 

var mem1 = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory;
var mem2 = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailableVirtualMemory;
var mem3 = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
var mem4 = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalVirtualMemory;


а также узнать о языковых параметрах и версии OS

.NET Запуск от имени администратора

WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
bool isRunAsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

// Если нет прав админа 
if (!isRunAsAdmin)
{
	ProcessStartInfo proc = new ProcessStartInfo();
	proc.UseShellExecute = true;
	proc.WorkingDirectory = Environment.CurrentDirectory;
	proc.FileName = System.Windows.Forms.Application.ExecutablePath;
	proc.Verb = "runas";
	proc.Arguments = string.Empty;

	try
	{
		Process.Start(proc);
	}
	catch
	{

	}

	Application.Current.Shutdown();  // Выходим
}

.NET завершить процесс

 
var ps1 = System.Diagnostics.Process.GetProcessesByName("Process Name").ToList();
if (ps1.Count > 1)
{
	foreach (Process p1 in ps1)
	{
		if (p1.Id != System.Diagnostics.Process.GetCurrentProcess().Id)
		{
			p1.Kill();
		}
	}
}

Ошибка при компиляции типа The "EnsureBindingRedirects" task failed unexpectedly.

Ошибка:
Error 1 The "EnsureBindingRedirects" task failed unexpectedly.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Roxel.BuildTasks.EnsureBindingRedirects.MergeBindingRedirectsFromElements(IEnumerable`1 dependentAssemblies)
   at Roxel.BuildTasks.EnsureBindingRedirects.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__20.MoveNext() 

Лечиться просто, нужно в web.config в  <dependentAssembly>  добавить атрибут culture="neutral" к сборкам


Чтобы получилось вот так:

<dependentAssembly>
	<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"  culture="neutral"/>
	<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>

WPF xaml разметка из кода на C#

Разметка Grid из кода
Установка фиксированного размера:

TableGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new System.Windows.GridLength(50) });
TableGrid.RowDefinitions.Add(new RowDefinition() { Height = new System.Windows.GridLength(50) });

Установа отностиельного размера, типа вездочка  (*) или Auto:

LayoutRoot.ColumnDefinitions[1] = new ColumnDefinition() { Width = new System.Windows.GridLength(2, System.Windows.GridUnitType.Star) };
LayoutRoot.RowDefinitions[1] = new  RowDefinition() { Height = new System.Windows.GridLength(2, System.Windows.GridUnitType.Auto) };

Помещение элемента в сетку:

TextBox  txtbox = new TextBox();
Grid.SetRow(txtbox, 2); 
Grid.SetColumn(txtbox, 3);
Grid.SetColumnSpan(txtbox, 2);
Grid.SetRowSpan(txtbox, 3);
TableGrid.Children.Add(txtbox); // добавляем элемент в грид

MVVM Command – еще один способ

 

public class TestViewModel : BaseViewModel
{
public ICommand MyCommand { get; set; }
public TestViewModel ()
{
this.MyCommand = new DelegateCommand(this.MyCommandExecuted, this.CanMyCommandCanExecuted);        
}
public void MyCommandExecuted(object param)
{
// что-то делаем
}
private bool CanMyCommandCanExecuted(object param)
{
return param != null;
}
}


или собранное в кучу на делегатах:

public ICommand MyCommand
        {
            get
            {
                return new DelegateCommand((executedParam) =>
                {
                    //executed code
                }, 
                (canExecutedParam) =>
                {
                    //CanCxecuted code
                    return true;
                }); 
            }
        }