using System;
using System.Collections.Generic;
using static Numbers.NumberAlgorithm;
namespace Numbers
{
public static class NumberAlgorithm
{
public static bool AreDigitsIncreasing(int number)
{
int prevDigit = 0;
int counter = 0;
foreach (int digit in GetDigits(number))
{
if (counter != 0 && prevDigit >= digit)
{
return false;
}
++counter;
prevDigit = digit;
}
return counter > 1;
}
public static bool AreDigitsDecreasing(int number)
{
int prevDigit = 0;
int counter = 0;
foreach (int digit in GetDigits(number))
{
if (counter != 0 && prevDigit <= digit)
{
return false;
}
++counter;
prevDigit = digit;
}
return counter > 1;
}
public static IEnumerable<int> GetDigits(int source)
{
int digit = 0;
int coefficient = (int)Math.Pow(10, GetCountOfDigits(source));
do
{
source -= coefficient * digit;
coefficient /= 10;
digit = source / coefficient;
yield return digit;
} while (coefficient > 1);
}
public static int GetCountOfDigits(int number)
{
return number == 0 ? 1 : (int)Math.Ceiling(Math.Log10(Math.Abs(number) + 0.5));
}
}
class Program
{
private const string DigitsAreIncreasing = "Цифры возрастают слева направо";
private const string DigitsAreDecreasing = "Цифры понижаются слева направо";
private const string DigitsAreMixed = "Цифры не упорядочены";
static void Main(string[] args)
{
int[] numbers = { 123456789, 987654321, 2312, 0 };
for (int i = 0; i < numbers.Length; i++)
{
int number = numbers[i];
string message;
if (AreDigitsIncreasing(number))
{
message = DigitsAreIncreasing;
}
else if (AreDigitsDecreasing(number))
{
message = DigitsAreDecreasing;
}
else
{
message = DigitsAreMixed;
}
Console.WriteLine($"{(i + 1):D2}: Исходное число {number.ToString()}. {message}.");
}
Console.ReadKey();
}
}
}
using System;
namespace Types
{
public class Person
{
public string FirstName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Так как class это ссылочный тип данных (Reference Type), то
// в стеке создаётся ссылка на экземпляр класса Person,
// под который выделена память в области, называемой кучей (Heap).
var person = new Person
{
FirstName = "John",
Age = 30
};
// Передаём в метод ссылку. Ссылка копируется, а данные
// так и остаются в куче, с ними ничего не происходит.
// Данных может быть хоть мегабайт, они не копируются, а вот
// ссылка копируется и имеет разный размер в зависимости от
// архитектуры x86 или x64, но размер этот крайне маленький (4 байта или 8 байт)
Display(person);
Console.ReadKey();
}
private static void Display(Person person)
{
// Здесь внутри метода находится копия ссылки.
Console.WriteLine($"Name = {person.FirstName}, Age = {person.Age.ToString()}");
}
}
}
-
// Ссылка, так как это class
Person person;
// Ссылка на экземпляр класса, так как мы выделили память в куче.
person = new Person();
using System;
namespace Types
{
class MyClass
{
MyClass my;
}
class Program
{
static void Main(string[] args)
{
// Выделяем память в куче.
// Ссылается на экземпляр класса MyClass, внутри
// которого есть поле типа MyClass со значением null.
MyClass data = new MyClass();
Console.ReadKey();
}
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ProgressBarExample
{
internal class Analyzer
{
private readonly SynchronizationContext _synchronizationContext;
public Analyzer()
{
// Если экземпляр класса будет создан в UI потоке,
// то здесь будет контекст синхронизации UI потока, иначе пула потоков
_synchronizationContext = SynchronizationContext.Current ?? new SynchronizationContext();
}
public event EventHandler<AnalyzerEventArgs> ProgressChanged;
public async Task<Data> LoadDataInDB()
{
var result = await Task.Run(async () =>
{
for (int i = 0; i < 100; i++)
{
await Task.Delay(250);
OnProgressChanged(new AnalyzerEventArgs("line " + (i + 1), 100));
}
return new Data() { Text = "Данные " };
});
return result;
}
private void OnProgressChanged(AnalyzerEventArgs args)
{
// Перенаправляем выполнение в UI поток не ожидая пока отработает метод обработчик события.
_synchronizationContext.Post(state =>
{
ProgressChanged?.Invoke(this, (AnalyzerEventArgs)state);
}, args); // args передаётся в переменную state (грубо говоря)
}
}
}
namespace ProgressBarExample
{
public class AnalyzerEventArgs
{
public int MaxLines { get; }
public string CurrentLine { get; }
public AnalyzerEventArgs(string currentLine, int maxLines)
{
CurrentLine = currentLine;
MaxLines = maxLines;
}
}
}
namespace ProgressBarExample
{
public class Data
{
public string Text { get; set; }
}
}
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
namespace ProgressBarExample
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private readonly Analyzer _analyzer;
private readonly Style _normalBarStyle;
private readonly Style _loadBarStyle;
private readonly Style _errorBarStyle;
private string _maxLines;
private string _currentLine;
public string MaxLines
{
get { return _maxLines; }
set
{
_maxLines = value;
OnPropertyChanged();
}
}
public string CurrentLine
{
get { return _currentLine; }
set
{
_currentLine = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MainWindow()
{
InitializeComponent();
_normalBarStyle = FindResource("NormalStatusBar") as Style;
_loadBarStyle = FindResource("LoadDataStatusBar") as Style;
_errorBarStyle = FindResource("ErrorStatusBar") as Style;
_statusBar.Style = _normalBarStyle;
_analyzer = new Analyzer();
_analyzer.ProgressChanged += OnAnalyzerProgressChanged;
}
private void OnAnalyzerProgressChanged(object sender, AnalyzerEventArgs args)
{
// Передавать каждый раз одно и тоже бессмысленно, сделаете сами как нужно
MaxLines = args.MaxLines.ToString();
CurrentLine = args.CurrentLine;
}
private async void LoadDataToDB_Click(object sender, RoutedEventArgs e)
{
_statusBar.Style = _loadBarStyle;
Mouse.OverrideCursor = Cursors.Wait;
try
{
var data = await _analyzer.LoadDataInDB();
MessageBox.Show(data.Text);
}
finally
{
Mouse.OverrideCursor = Cursors.Arrow;
_statusBar.Style = _normalBarStyle;
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<Window
x:Class="ProgressBarExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ProgressBarExample"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
mc:Ignorable="d">
<Window.Resources>
<Style x:Key="NormalStatusBar" TargetType="DockPanel">
<Setter Property="Background" Value="#FF007ACC" />
</Style>
<Style x:Key="LoadDataStatusBar" TargetType="DockPanel">
<Setter Property="Background" Value="#9333FF" />
</Style>
<Style x:Key="ErrorStatusBar" TargetType="DockPanel">
<Setter Property="Background" Value="#eb4034" />
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<Menu VerticalAlignment="Top">
<MenuItem Header="File">
<MenuItem
x:Name="LoadDataToDB"
Click="LoadDataToDB_Click"
Header="LoadDataToDB" />
</MenuItem>
</Menu>
<DockPanel
x:Name="_statusBar"
Grid.Row="1"
Style="{StaticResource LoadDataStatusBar}">
<!-- Style меняться во время выполнения LoadDataInDB() -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="0"
Margin="10,0,0,0"
Foreground="White"
Text="Статус данных" />
<DockPanel Grid.Column="1" HorizontalAlignment="Right">
<TextBlock
Margin="0,0,5,0"
Foreground="White"
Text="{Binding CurrentLine}" />
<!-- должно меняться во время выполнения LoadDataInDB() -->
<TextBlock
Margin="0,0,5,0"
Foreground="White"
Text="/" />
<TextBlock
Margin="0,0,10,0"
Foreground="White"
Text="{Binding MaxLines}" />
</DockPanel>
</Grid>
</DockPanel>
</Grid>
</Window>
using System;
namespace ConsoleApp1
{
public class ModelBase
{
protected bool CheckValueTypeField<T>(T field)
where T : struct
{
return field.Equals(default(T));
}
protected bool CheckReferenceTypeField<T>(T field)
where T : class
{
return field == null;
}
protected void ThrowIfNotDefault<T>(T field)
where T : struct
{
if (!CheckValueTypeField(field))
{
throw new InvalidOperationException();
}
}
protected void ThrowIfNotNull<T>(T field)
where T : class
{
if (!CheckReferenceTypeField(field))
{
throw new InvalidOperationException();
}
}
}
public class TestModel : ModelBase
{
private string _name;
private int _value;
public string Name
{
get { return _name; }
set
{
ThrowIfNotNull(_name);
_name = value;
}
}
public int Value
{
get { return _value; }
set
{
ThrowIfNotDefault(_value);
_value = value;
}
}
}
class Program
{
static void Main(string[] args)
{
var test = new TestModel();
test.Name = "test name";
test.Value = 1;
try
{
test.Name = "new name";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
test.Value = 5;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Display(test);
}
static void Display(TestModel model)
{
Console.WriteLine(
$"{nameof(model.Name)} == {model.Name}; {nameof(model.Value)} == {model.Value};");
}
}
}
public class TestModel : ModelBase
{
private string _name;
private int _value;
public string Name
{
get { return _name; }
set
{
if (!CheckReferenceTypeField(_name))
{
_name = value;
}
}
}
public int Value
{
get { return _value; }
set
{
if (!CheckValueTypeField(_value))
{
_value = value;
}
}
}
}
using System;
namespace ConsoleApp1
{
public abstract class ModelBase
{
private readonly bool _throwAnExceptionInsteadOfAnEvent;
public event EventHandler FieldIsNotDefault;
protected ModelBase(bool throwAnExceptionInsteadOfAnEvent = true)
{
_throwAnExceptionInsteadOfAnEvent = throwAnExceptionInsteadOfAnEvent;
}
protected bool CheckValueTypeField<T>(T field)
where T : struct
{
return field.Equals(default(T));
}
protected bool CheckReferenceTypeField<T>(T field)
where T : class
{
return field == null;
}
protected void AssertIsNotDefault<T>(T field)
where T : struct
{
if (!CheckValueTypeField(field))
{
if (_throwAnExceptionInsteadOfAnEvent)
{
throw new InvalidOperationException();
}
OnFieldIsNotDefault();
}
}
protected void AssertIsNotNull<T>(T field)
where T : class
{
if (!CheckReferenceTypeField(field))
{
if (_throwAnExceptionInsteadOfAnEvent)
{
throw new InvalidOperationException();
}
OnFieldIsNotDefault();
}
}
protected void OnFieldIsNotDefault()
{
FieldIsNotDefault?.Invoke(this, EventArgs.Empty);
}
}
public class TestModel : ModelBase
{
private string _name;
private int _value;
public string Name
{
get { return _name; }
set
{
AssertIsNotNull(_name);
_name = value;
}
}
public int Value
{
get { return _value; }
set
{
AssertIsNotDefault(_value);
_value = value;
}
}
public TestModel()
: base(false)
{
}
}
class Program
{
static void Main(string[] args)
{
var test = new TestModel();
test.FieldIsNotDefault += OnFieldIsNotDefault;
test.Name = "test name";
test.Value = 1;
try
{
test.Name = "new name";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
test.Value = 5;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
test.FieldIsNotDefault -= OnFieldIsNotDefault;
Display(test);
}
private static void OnFieldIsNotDefault(object sender, EventArgs e)
{
Console.WriteLine("Поле уже установлено");
}
static void Display(TestModel model)
{
Console.WriteLine(
$"{nameof(model.Name)} == {model.Name}; {nameof(model.Value)} == {model.Value};");
}
}
}
var sync = new SynchronizationContext();
var data = (SomeType[])context;
var filtered = data.Where(...);
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0-preview-20170914-09" />
<PackageReference Include="xunit" Version="2.3.0-beta5-build3769" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.0-beta5-build3769" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RazorLesson.Model\RazorLesson.Model.csproj" />
</ItemGroup>
</Project>
using System;
using System.Diagnostics;
using System.IO;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
string result = LinuxTerminal.GetOutput("find /sys/class/input -maxdepth 1 -name \"mouse*\"|wc -l");
int outputValue = int.Parse (result);
Console.WriteLine (outputValue);
Console.ReadKey ();
}
}
}
using System;
using System.Diagnostics;
namespace Test
{
public static class LinuxTerminal
{
private const string TerminalPath = "/bin/bash";
public static void ExecuteCommand(string command)
{
var proc = new Process();
proc.StartInfo.FileName = TerminalPath;
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.Start();
}
public static int GetExitCode(string command)
{
var proc = new Process();
proc.StartInfo.FileName = TerminalPath;
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.WaitForExit();
return proc.ExitCode;
}
public static string GetOutput(string command)
{
var proc = new Process();
proc.StartInfo.FileName = TerminalPath;
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.WaitForExit();
return proc.StandardOutput.ReadToEnd();
}
}
}
using System.Diagnostics;
namespace ProcessStart
{
public static class CommandLine
{
public static int ExecuteCommand(string applicationPath, string command = "")
{
var proc = new Process();
proc.StartInfo.FileName = applicationPath;
proc.StartInfo.Arguments = command;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
return proc.ExitCode;
}
}
}
using System;
using System.IO;
namespace ProcessStart
{
class Program
{
private static Program _program;
static void Main(string[] args)
{
_program = new Program();
_program.Run();
}
private void Run()
{
const string ProgramName = "ReturnRandomNumber.exe";
string appName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ProgramName);
int exitCode = CommandLine.ExecuteCommand(appName);
Console.WriteLine(exitCode.ToString());
Console.ReadKey();
}
}
}
<!-- Чтобы выполнились сразу 2 действия, нужно в качестве Condition указать 1 у обоих действий -->
<Publish Dialog="SettingsDlg" Control="Next" Event="DoAction" Value="DoMethodAction2" Order="1" >1</Publish>
<Publish Dialog="SettingsDlg" Control="Next" Event="NewDialog" Value="SettingsPreviewDlg" Order="2">1</Publish>
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebAppSendMessage.Views.Index" %>
<asp:Content ID="header" ContentPlaceHolderID="head" runat="server">
<style>
input[type=text] {
margin-top: 5px;
margin-left: 3px;
margin-right: 3px;
width: 100%;
}
input[type=submit] {
margin-top: 5px;
margin-left: 3px;
margin-right: 3px;
}
</style>
</asp:Content>
<asp:Content ID="mainContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<form id="mainForm" method="post" runat="server">
<asp:TextBox ID="textBox" runat="server" />
<br />
<asp:Button ID="sendMessageButton" runat="server" Text="Отправить сообщение" OnClick="SendMessageButton_OnClick"/>
</form>
</asp:Content>
using System;
using System.Web;
using System.Web.UI;
namespace WebAppSendMessage.Views
{
public partial class Index : Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["mainMessage"];
if (cookie != null)
{
string message = cookie["Message"];
if (message != null)
{
textBox.Text = message;
}
}
}
protected void SendMessageButton_OnClick(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["mainMessage"];
if (cookie == null)
{
cookie = new HttpCookie("mainMessage");
cookie.Expires = DateTime.Now.AddYears(1);
}
string message = Request.Form[textBox.UniqueID];
cookie["Message"] = message;
Session["Message"] = message;
Session["BackAddress"] = Request.RawUrl;
Response.Charset = "utf-8";
Response.Cookies.Add(cookie);
Response.Redirect("Message.aspx");
}
}
}
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="Message.aspx.cs" Inherits="WebAppSendMessage.Views.Message" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<form id="mainForm" runat="server">
<asp:Label runat="server" Text="<%# Text %>"></asp:Label>
<br />
<asp:Button ID="backButton" runat="server" Text="Вернуться" OnClick="GoToBackButton_OnClick" />
</form>
</asp:Content>
using System;
using System.Web;
using System.Web.UI;
namespace WebAppSendMessage.Views
{
public partial class Message : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBind();
}
}
protected string Text
{
get { return (string)Session["Message"]; }
}
protected void GoToBackButton_OnClick(object sender, EventArgs e)
{
string returnUrl = Session["BackAddress"] as string ?? "Index.aspx";
Response.Redirect(returnUrl);
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
var source = new Person[]
{
new Person { Age = 20, Name = "Сергей" },
new Person { Age = 32, Name = "Дмитрий" },
new Person { Age = 18, Name = "Андрей" }
};
var copy = new Person[source.Length];
Array.Copy(source, copy, source.Length);
DisplayPersons(copy);
Console.WriteLine();
int index = 0;
foreach (Person person in copy)
{
Console.WriteLine(person.Name + " удалён из исходного массива");
source[index++] = null;
}
if (source.Any(p => p != null))
{
Console.WriteLine("Не удалось удалить все элементы исходного массива.");
}
Console.ReadKey();
}
static void DisplayPersons(IEnumerable<Person> persons)
{
foreach (Person person in persons)
{
Console.WriteLine("Имя: {0}, возраст: {1}", person.Name, person.Age);
}
}
}
<Window x:Class="Wpf_Task.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="525"
Height="350"
WindowStartupLocation="CenterScreen">
<Window.Resources>
<Storyboard x:Key="OnLoaded1"
RepeatBehavior="Forever">
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="border"
Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)">
<EasingDoubleKeyFrame KeyTime="0"
Value="0" />
<EasingDoubleKeyFrame KeyTime="0:0:1"
Value="360" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource OnLoaded1}" />
</EventTrigger>
</Window.Triggers>
<Grid>
<Button x:Name="executeButton"
Width="75"
Margin="0,216,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Click="Button_Click"
Content="Выполнить"
TextOptions.TextFormattingMode="Display" />
<Rectangle x:Name="border"
Width="100"
Height="100"
Margin="208,57,208,161"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RenderTransformOrigin="0.5,0.5">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Offset="0" Color="#FFD1BD69" />
<GradientStop Offset="1" Color="#FFFFF5C9" />
</LinearGradientBrush>
</Rectangle.Fill>
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform />
<SkewTransform />
<RotateTransform />
<TranslateTransform />
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
<TextBlock x:Name="_result"
Margin="0,187,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Text="..."
TextOptions.TextFormattingMode="Display"
TextWrapping="Wrap" />
</Grid>
</Window>
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace Wpf_Task
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
executeButton.IsEnabled = false;
Task<int>.Factory.StartNew(() =>
{
return Auth.Login();
})
.ContinueWith(task => //Выполнить код в основном потоке (TaskScheduler.FromCurrentSynchronizationContext())
{
executeButton.IsEnabled = true;
_result.Text = task.Result.ToString();
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
public static class Auth
{
private static int _counter;
public static int Login()
{
Thread.Sleep(1000);
return ++_counter;
}
}
}
public MainViewModel Main
{
get
{
return !ViewModelBase.IsInDesignModeStatic ?
_container.Resolve<MainViewModel>() :
_designerMainVm ?? (_designerMainVm =
new MainViewModel(null, null, null, null) { Settings = new AppSettings() });
}
}
public class ViewModelLocator : ViewModelLocatorBase
{
private readonly IContainer _container;
private static ViewModelLocator _locator;
public ViewModelLocator()
{
_locator = this;
if (!ViewModelBase.IsInDesignModeStatic)
{
Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
Application.Current.MainWindow.Loaded += MainWindow_Loaded;
Application.Current.MainWindow.Closing += MainWindow_Closing;
}
LogManager.Logger.LogPath = LocalConfiguration.Instance.Folders.Logs;
DispatcherHelper.Initialize();
CorrelationsLocator.Initialize();
if (!ViewModelBase.IsInDesignModeStatic)
{
ProgramIdentification.Initialize(ProgramIdentifier.CbpOperator);
LocalConfiguration.Instance.Folders.CheckFolders();
LocalConfiguration.Instance.LoadAppConfig();
LocalConfiguration.Instance.LoadLocalSettings();
WpfSingleInstance.AppIsAlreadyRunning += (sender, args) =>
MessageBox.Show(string.Format("Приложение: {0} уже запущено", args.AppName));
WpfSingleInstance.Make();
}
_container = RegisterDependencies(LocalConfiguration.Instance);
}
private IContainer RegisterDependencies(LocalConfiguration config)
{
var builder = new ContainerBuilder();
builder.RegisterType<LauncherViewModel>().SingleInstance();
builder.RegisterType<ShutdownViewModel>().SingleInstance();
builder.RegisterType<CommandManager>().SingleInstance();
builder.RegisterType<AccountControllerVm>().SingleInstance();
builder.RegisterType<ComponentEditorViewModel>().SingleInstance();
builder.RegisterType<ComponentSelectorViewModel>().SingleInstance();
builder.RegisterType<RecipeTimeSetEditorViewModel>().SingleInstance();
builder.RegisterType<CategoryEditorViewModel>().SingleInstance();
builder.RegisterType<AboutDialogViewModel>().SingleInstance();
builder.RegisterType<L1ApplicationManagerViewModel>().SingleInstance();
builder.RegisterType<CarEditorViewModel>() //Редактор машин
.OnActivated(e =>
{
e.Instance.WindowSettings = config.Settings.CarsWindowSettings; //Настройки окна (положение, размер, состояние)
}).SingleInstance();
builder.RegisterType<ClientsEditorViewModel>() //Редактор клиентов
.OnActivated(e =>
{
e.Instance.WindowSettings = config.Settings.ClientsWindowSettings; //Настройки окна (положение, размер, состояние)
}).SingleInstance();
builder.RegisterType<ReportsWindowViewModel>() //Отчёты
.OnActivated(e =>
{
e.Instance.WindowSettings = config.Settings.ReportsWindowSettings; //Настройки окна (положение, размер, состояние)
e.Instance.ReportsFolder = config.Folders.Documents;
e.Instance.ReportMode = ReportMode.Applications;
});
builder.RegisterType<EventLogViewModel>() //Журнал событий
.OnActivated(e =>
{
e.Instance.WindowSettings = config.Settings.EventLogWindowSettings; //Настройки окна (положение, размер, состояние)
e.Instance.SetConfiguration(config.Config, config.Folders.EventReportFolder);
});
builder.RegisterType<RecipesEditorViewModel>() //Редактор рецептов
.OnActivated(e =>
{
e.Instance.WindowSettings = config.Settings.RecipeWindowSettings; //Настройки окна (положение, размер, состояние)
e.Instance.SetEditorSettings(config.Settings.RecipeEditorConfig);
})
.SingleInstance();
builder.RegisterType<ApplicationsEditorViewModel>() //Редактор заявок
.OnActivated(e =>
{
e.Instance.LastSelectedItems = config.Settings.LastSelectedItemsInAppWindow; //Состояние последних выбранных элементов.
e.Instance.WindowSettings = config.Settings.AppEditorWindowSettings;
})
.SingleInstance();
builder.RegisterType<MainViewModel>()
.OnActivated(e =>
{
var appManager = e.Context.Resolve<L1ApplicationManagerViewModel>();
appManager.Main = e.Instance;
if (!ViewModelBase.IsInDesignModeStatic)
{
e.Instance.Title = ProgramIdentification.GetCurrentProgramName();
}
e.Instance.Settings = config.Settings.ApplicationSettings;
})
.SingleInstance();
return builder.Build();
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
WindowManager.Instance.Initialize(Application.Current.MainWindow, Main);
Main.OnWindowLoaded();
}
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
Debug.WriteLine("Начало: MainWindow_Closing");
Window window = (Window)sender;
Debug.WriteLine("Конец: MainWindow_Closing");
if (WindowManager.Instance.OpenMessageDialog(DialogIcons.Help, DialogButtons.YesNo,
"Выход из программы",
"Вы действительно хотите завершить работу приложения?") == UserDialogResult.No)
e.Cancel = true;
else
{
window.Closing -= MainWindow_Closing;
try
{
LocalConfiguration.Instance.SaveLocalSettings();
LocalConfiguration.Instance.SaveCurrentAppConfig();
}
catch (Exception ex)
{
LogManager.Logger.AppendException(ex);
}
}
}
private void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
LogManager.Logger.AppendException(e.Exception);
MessageBox.Show(e.Exception.ToString());
}
#region Свойства
public static ViewModelLocator Current
{
get { return _locator; }
}
public MainViewModel Main
{
get { return _container.Resolve<MainViewModel>(); }
}
public L1ApplicationManagerViewModel ApplicationsManager
{
get { return _container.Resolve<L1ApplicationManagerViewModel>(); }
}
public AccountControllerVm AccountController
{
get { return _container.Resolve<AccountControllerVm>(); }
}
public ShutdownViewModel Shutdown
{
get { return _container.Resolve<ShutdownViewModel>(); }
}
public CategoryEditorViewModel CategoryEditor
{
get { return _container.Resolve<CategoryEditorViewModel>(); }
}
public ApplicationsEditorViewModel ApplicationsEditor
{
get { return _container.Resolve<ApplicationsEditorViewModel>(); }
}
public RecipesEditorViewModel RecipesEditor
{
get { return _container.Resolve<RecipesEditorViewModel>(); }
}
public ComponentEditorViewModel ComponentEditor
{
get { return _container.Resolve<ComponentEditorViewModel>(); }
}
public ComponentSelectorViewModel ComponentsSelector
{
get { return _container.Resolve<ComponentSelectorViewModel>(); }
}
/// <summary>Редактор клиентов</summary>
public ClientsEditorViewModel ClientsEditor
{
get { return _container.Resolve<ClientsEditorViewModel>(); }
}
public CarEditorViewModel CarsEditor
{
get { return _container.Resolve<CarEditorViewModel>(); }
}
public CommandManager CommonCommands
{
get { return _container.Resolve<CommandManager>(); }
}
public LauncherViewModel Launcher
{
get { return _container.Resolve<LauncherViewModel>(); }
}
public AboutDialogViewModel About
{
get { return _container.Resolve<AboutDialogViewModel>(); }
}
/// <summary>
/// Возвращает новый экземпляр модели представления Отчётов
/// </summary>
public ReportsWindowViewModel NewReport
{
get { return _container.Resolve<ReportsWindowViewModel>(); }
}
/// <summary>
/// Возвращает новый экземпляр модели представления Журнала событий
/// </summary>
public EventLogViewModel NewEventLog
{
get { return _container.Resolve<EventLogViewModel>(); }
}
#endregion
#region Методы
#endregion
}