Счетчики производительности 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;
            }
        }
    }

Telerik RadGridView - UserControl в ячейке

Иногда в RadGridView нужно засунуть что-то специфическое вот как это сделать:

Значит для начала надо сделать класс вашего нового типа колонки

public class MyNewColumn : GridViewBoundColumnBase
{
	public override FrameworkElement CreateCellEditElement(GridViewCell cell, object dataItem)
	{
		this.BindingTarget = MyNewControl.MyNewProperty;
		var control = new MyNewControl();
		control.SetBinding(this.BindingTarget, this.CreateValueBinding());
		return control;
	}
	private Binding CreateValueBinding()
	{
		var valueBinding = new Binding();
		valueBinding.Mode = BindingMode.TwoWay;
		valueBinding.NotifyOnValidationError = true;
		valueBinding.ValidatesOnExceptions = true;
		valueBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
		valueBinding.Path = new PropertyPath(this.DataMemberBinding.Path.Path);
		return valueBinding;
	}
}

MyNewControl – это мой User Control который мы хотим поместить в ячейку.
MyNewControl.MyNewProperty – а это то свойство которое мы будем биндить.

Так,в юзер контроле надо это свойство сделать как DependencyProperty:

public static readonly DependencyProperty MyNewPropertyProperty =
            DependencyProperty.Register("MyNewProperty", typeof(int), typeof(MyNewControl), new PropertyMetadata(0, OnSelectedDateChanged));
public int MyNewProperty
{
	get
	{
		return (int)this.GetValue(MyNewProperty);
	}
	set
	{
		this.SetValue(MyNewProperty, value);
	}
}

Теперь как вы заметили мы указали метод OnSelectedDateChanged

private static void OnSelectedDateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
	var control = (MyNewControl)d;
	control.OnSelectedDateChanged(control. MyNewProperty);
}

private void OnSelectedDateChanged(int item)
{
	// А вот тут мы уже делаем то, что нам нужно
	// обращаясь к свойству MyNewProperty
	// мы в нашем контроле
}

Ну и подключаем это в RadGridView
(сам контрол у меня в корне проекта)

xmlns:uc="clr-namespace:MyTestProgram"


<telerik:RadGridView ItemsSource="{Binding DocumentList, Mode=TwoWay}"  
					 AutoGenerateColumns="False" >
	<telerik:RadGridView.Columns>
		<uc:MyNewColumn   Width="1*" Header="My property" DataMemberBinding="{Binding CurrentOwners}">
			<uc:MyNewColumn.CellEditTemplate>
				<DataTemplate>
					<Grid>
						<uc:MyNewControl  MyNewProperty ="{Binding CurrentOwners}"  />
					</Grid>
				</DataTemplate>
			</uc:MyNewColumn.CellEditTemplate>
			<uc:MyNewColumn.CellTemplate>
				<DataTemplate>
					<Grid IsEnabled="False">
							<uc:MyNewControl  MyNewProperty ="{Binding CurrentOwners}"  />
					</Grid>
				</DataTemplate>
			</uc:MyNewColumn.CellTemplate>
		</uc:OwnerColumn>
	</telerik:RadGridView.Columns>
</telerik:RadGridView>

 

Arduino C\C++ и Visual Studio

Arduino  - это очень интересно, но родная среда разработки не самая удобная. По этому вот как можно разрабатывать приложения для Arduino в Visual Studio и писать на C или С++.
Для этого надо пойти в Tools -> Extensions and Update и найти  в поиске arduino for visual studio (http://www.visualmicro.com/)

После инсталяции можно будет создавать проект для  Arduino. НО!
Это нормальный С++ проект, по этому можно писать на нормальном С/С++

.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>