Acrovations Blog

Технический блог

Еще немного о счетчиках в .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 проверка MD5

using (var md5 = MD5.Create())
{
    using (var stream = File.OpenRead(filename))
    {
        return md5.ComputeHash(stream);
    }
}

http://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file

.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();
		}
	}
}

.NET запуск приложений из приложения (exe)

Process myProcess = new Process();
myProcess.StartInfo.FileName = "someApp.exe";
myProcess.Start();

Ошибка при компиляции типа 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); // добавляем элемент в грид
Bookmark and Share