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
<%@ 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);
}
}
}
<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
}