getReport(dateFrom, dateTo) {
return axios.post(this.config.getReportUrl, {
from: dateFrom,
to: dateTo
}, {
baseURL: this.config.baseUrl,
withCredentials: true,
responseType: 'blob',
headers: {
"Accept": "*/*",
"Cache-Control": "no-cache",
}
});
};
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Domain.ValueConversion
{
public static class EntityFrameworkCoreModelBuilderExtensions
{
public static void AddDateTimeOffsetConverter(this ModelBuilder builder)
{
// SQLite does not support DateTimeOffset
foreach (var property in builder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(DateTimeOffset)))
{
property.SetValueConverter(
new ValueConverter<DateTimeOffset, DateTime>(
convertToProviderExpression: dateTimeOffset => dateTimeOffset.UtcDateTime,
convertFromProviderExpression: dateTime => new DateTimeOffset(dateTime)
));
}
foreach (var property in builder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(DateTimeOffset?)))
{
property.SetValueConverter(
new ValueConverter<DateTimeOffset?, DateTime>(
convertToProviderExpression: dateTimeOffset => dateTimeOffset.Value.UtcDateTime,
convertFromProviderExpression: dateTime => new DateTimeOffset(dateTime)
));
}
}
public static void AddDateTimeUtcKindConverter(this ModelBuilder builder)
{
// If you store a DateTime object to the DB with a DateTimeKind of either `Utc` or `Local`,
// when you read that record back from the DB you'll get a DateTime object whose kind is `Unspecified`.
// Here is a fix for it!
var dateTimeConverter = new ValueConverter<DateTime, DateTime>(
v => v.Kind == DateTimeKind.Utc ? v : v.ToUniversalTime(),
v => DateTime.SpecifyKind(v, DateTimeKind.Utc));
var nullableDateTimeConverter = new ValueConverter<DateTime?, DateTime?>(
v => !v.HasValue ? v : (v.Value.Kind == DateTimeKind.Utc ? v : v.Value.ToUniversalTime()),
v => v.HasValue ? DateTime.SpecifyKind(v.Value, DateTimeKind.Utc) : v);
foreach (var property in builder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties()))
{
if (property.ClrType == typeof(DateTime))
{
property.SetValueConverter(dateTimeConverter);
}
if (property.ClrType == typeof(DateTime?))
{
property.SetValueConverter(nullableDateTimeConverter);
}
}
}
}
}
using Microsoft.EntityFrameworkCore;
using MySql.Data.EntityFrameworkCore.Extensions;
namespace Infrastructure.Data.Contexts
{
/// <summary>
/// Контекст для работы с БД событий.
/// </summary>
public class SystemEventContext : DbContextEx
{
public DbSet<SystemEvent> Events { get; set; }
public SystemEventContext(DbContextOptions<SystemEventContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
const string TIMESTAMP_COLUMN_TYPE = "timestamp(3)";
// ...
base.OnModelCreating(builder);
// ...
builder.AddDateTimeOffsetConverter();
builder.AddDateTimeUtcKindConverter();
}
}
}
app.UseCookiePolicy(new CookiePolicyOptions
{
MinimumSameSitePolicy = SameSiteMode.Strict,
HttpOnly = HttpOnlyPolicy.Always,
// При включении HTTPS нужно вернуть CookieSecurePolicy.Always
Secure = CookieSecurePolicy.None,
});
app.UseSecureJwt();
app.UseAuthentication();
// Не забыть вернуть в app.UseCookiePolicy параметр Secure = CookieSecurePolicy.Always,
//app.UseHttpsRedirection();
app.UseMvc();
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(...);
#Clear-Host
$pathToFile = Get-Item C:\Windows\explorer.exe
$bytes = [System.IO.File]::ReadAllBytes($pathToFile)
"Размер файла $pathToFile составляет $($bytes.Length) байт"
"Размер: {0:n3} мегабайт" -f $($bytes.Length / 1mb)
$pathToFile = Get-Item C:\Windows\explorer.exe
$fileInfo = [System.IO.FileInfo]::new($pathToFile);
"Размер файла $pathToFile составляет $($fileInfo.Length) байт"
"Размер: {0:n3} мегабайт" -f $($fileInfo.Length / 1mb)
<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();
}
}
}
BEGIN TRANSACTION
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
SET DEADLOCK_PRIORITY LOW;
DECLARE @Quantity INT = 5;
IF OBJECT_ID('tempdb..##GroupIDs_{0}') IS NULL
BEGIN
CREATE TABLE ##GroupIDs_{0} (
ID INT NOT NULL,
CONSTRAINT PK_GroupIDs_ID_{0} PRIMARY KEY(ID),
);
END
INSERT INTO ##GroupIDs_{0} (ID)
SELECT TOP(@Quantity) ID FROM SOME_GROUP WITH(UPDLOCK, READPAST) WHERE REPLICATED <> 1
-- Первый запрос, вызываемый из C# кода в одной транзакции.
-- 1 ------------------------------------------------------------------
UPDATE SOME_GROUP SET REPLICATED = 2
OUTPUT
INSERTED.ID
,INSERTED.NAME
WHERE ID IN(SELECT ID FROM ##GroupIDs_{0})
-- Второй запрос, вызываемый из C# кода в одной транзакции.
-- 2------------------------------------------------------------------
UPDATE SOME_CHILD_ONE SET REPLICATED = 2
OUTPUT
INSERTED.ID
,INSERTED.GROUP_ID
,INSERTED.UPDATED
WHERE GROUP_ID IN(SELECT ID FROM ##GroupIDs_{0}) AND REPLICATED <> 1
-- Третий запрос, вызываемый из C# кода в одной транзакции.
-- 3 ------------------------------------------------------------------
UPDATE SOME_CHILD_TWO SET REPLICATED = 2
OUTPUT
INSERTED.ID
,INSERTED.GROUP_ID
,INSERTED.NAME
,INSERTED.CREATED
WHERE GROUP_ID IN(SELECT ID FROM ##GroupIDs_{0}) AND REPLICATED <> 1
DROP TABLE ##GroupIDs_{0};
-- 3 ------------------------------------------------------------------
COMMIT TRANSACTION