本文整理汇总了C#中OperationContext.OpenSystemSession方法的典型用法代码示例。如果您正苦于以下问题:C# OperationContext.OpenSystemSession方法的具体用法?C# OperationContext.OpenSystemSession怎么用?C# OperationContext.OpenSystemSession使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OperationContext
的用法示例。
在下文中一共展示了OperationContext.OpenSystemSession方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendAsync
public async Task SendAsync(OperationContext context, NotificationMessage message) {
Util.CheckNotEmpty(message.Recipients, "Recipient(s) not specified.");
try {
var session = context.OpenSystemSession();
var subject = message.GetString("Subject") ?? GetTemplatedValue(session, message, "Subject");
var body = message.GetString("Body") ?? GetTemplatedValue(session, message, "Body");
Util.CheckNotEmpty(message.From, "Email From address not specified in message.");
Util.CheckNotEmpty(subject, "Subject not specified or Subject template '{0}.Subject' not found.", message.Type);
Util.CheckNotEmpty(body, "Email body not specified or Body template '{0}.Body' not found.", message.Type);
message.Status = MessageStatus.Sending;
var mail = new MailMessage(message.From, message.Recipients, subject, body);
await _emailService.SendAsync(context, mail);
message.Status = MessageStatus.Sent;
} catch (Exception ex) {
message.Status = MessageStatus.Error;
message.Error = ex.ToLogString();
}
}
示例2: LogClientError
public Guid LogClientError(OperationContext context, Guid? id, string message, string details, string appName, DateTime? localTime = null)
{
try {
var session = context.OpenSystemSession();
IErrorLog errInfo;
Guid idValue = id == null ? Guid.Empty : id.Value;
if (idValue != Guid.Empty) {
//Check for duplicates
errInfo = session.GetEntity<IErrorLog>(idValue);
if (errInfo != null)
return idValue;
}
errInfo = session.NewEntity<IErrorLog>();
if(idValue != Guid.Empty)
errInfo.Id = idValue;
errInfo.ExceptionType = "ClientError";
//Some messages might be really long; check length to fit into the field; full message will still go into details column
errInfo.Message = Util.CheckLength(message, 250);
errInfo.Details = details;
errInfo.MachineName = Environment.MachineName;
errInfo.LocalTime = localTime != null ? localTime.Value : App.TimeService.Now;
errInfo.CreatedOn = App.TimeService.UtcNow;
errInfo.AppName = appName ?? context.App.AppName;
errInfo.OperationLog = context.GetLogContents();
errInfo.UserName = context.User.UserName;
if (context.UserSession != null)
errInfo.UserSessionId = context.UserSession.SessionId;
if (context.WebContext != null)
errInfo.WebCallId = context.WebContext.Id;
errInfo.IsClientError = true;
session.SaveChanges();
OnErrorLogged(context, new Exception("ClientError: " + message + Environment.NewLine + details));
return errInfo.Id;
} catch(Exception logEx) {
Util.WriteToTrace(logEx, "Fatal failure in database error log. See next error log entry for original error.");
Util.WriteToTrace(message, details, null, copyToEventLog: true);
return Guid.NewGuid();
}
}
示例3: Logout
public void Logout(OperationContext context)
{
var user = context.User;
Util.Check(user.Kind == UserKind.AuthenticatedUser, "Cannot logout - user is not authenticated.");
var session = context.OpenSystemSession();
var login = session.EntitySet<ILogin>().Where(lg => lg.UserId == user.UserId).FirstOrDefault();
if(login == null)
return;
OnLoginEvent(context, LoginEventType.Logout, login);
App.UserLoggedOut(context);
if(_sessionService != null)
_sessionService.EndSession(context);
context.Values.Clear();
}
示例4: LoginUser
public LoginResult LoginUser(OperationContext context, Guid userId)
{
var session = context.OpenSystemSession();
var login = session.EntitySet<ILogin>().Where(lg => lg.UserId == userId).FirstOrDefault();
if(login == null || login.Flags.IsSet(LoginFlags.Inactive))
return new LoginResult() { Status = LoginAttemptStatus.Failed };
context.User = login.CreateUserInfo();
if(_sessionService != null)
AttachUserSession(context, login);
App.UserLoggedIn(context);
var lastLogin = login.LastLoggedInOn; //save prev value
UpdateLastLoggedInOn(login);
OnLoginEvent(context, LoginEventType.Login, login, userName: login.UserName);
var sessionToken = context.UserSession == null ? null : context.UserSession.Token;
return new LoginResult() { Status = LoginAttemptStatus.Success, Login = login, User = context.User, SessionToken = sessionToken, LastLoggedInOn = lastLogin };
}
示例5: Login
public LoginResult Login(OperationContext context, string userName, string password, Guid? tenantId = null,
string deviceToken = null)
{
context.ThrowIf(password.Length > 100, ClientFaultCodes.InvalidValue, "password", "Password too long, max size: 100.");
var webCtx = context.WebContext;
userName = CheckUserName(context, userName);
var session = context.OpenSystemSession();
var login = FindLogin(session, userName, password, tenantId);
if(login == null) {
if(webCtx != null)
webCtx.Flags |= WebCallFlags.AttackRedFlag;
OnLoginEvent(context, LoginEventType.LoginFailed, null, userName: userName);
LogIncident(context, LoginIncidentType, LoginEventType.LoginFailed.ToString(), "User: " + userName, null, userName);
return new LoginResult() { Status = LoginAttemptStatus.Failed };
}
var device = login.GetDevice(deviceToken);
try {
var status = CheckCanLoginImpl(login, device);
//Check non-success statuses
switch(status) {
case LoginAttemptStatus.Success:
PostLoginActions actions = GetPostLoginActions(login);
context.User = login.CreateUserInfo();
if(_sessionService != null)
AttachUserSession(context, login, device);
App.UserLoggedIn(context);
var lastLogin = login.LastLoggedInOn; //save prev value
UpdateLastLoggedInOn(login);
OnLoginEvent(context, LoginEventType.Login, login, userName: userName);
var sessionToken = context.UserSession == null ? null : context.UserSession.Token;
return new LoginResult() { Status = status, Login = login, Actions = actions, User = context.User, SessionToken = sessionToken, LastLoggedInOn = lastLogin };
case LoginAttemptStatus.PendingMultifactor:
OnLoginEvent(context, LoginEventType.LoginPendingMultiFactor, login, userName: userName);
return new LoginResult() { Status = status, Login = login };
case LoginAttemptStatus.AccountInactive:
OnLoginEvent(context, LoginEventType.LoginFailed, login, "Login failed due to inactive status", userName: userName);
return new LoginResult() { Status = status, Login = login };
case LoginAttemptStatus.Failed:
default:
OnLoginEvent(context, LoginEventType.LoginFailed, login, userName: userName);
return new LoginResult() { Status = status };
}
} finally {
session.SaveChanges();
}
}
示例6: CreateSampleBooks
public static void CreateSampleBooks(EntityApp app)
{
//Create identity for sample data generator; this results in SampleDataGenerator showing up in UserSession/UserTransaction tables
// Books and coupons will reference these transactions as 'CreatedIn'
var session = app.OpenSystemSession();
var dataGenUser = session.NewUser("SampleDataGenerator", UserType.StoreAdmin);
session.SaveChanges();
var userInfo = new UserInfo(dataGenUser.Id, dataGenUser.UserName);
var dataGenOpCtx = new OperationContext(app, userInfo);
session = dataGenOpCtx.OpenSystemSession();
session.EnableCache(false);
//Publishers and authors
var msPub = session.NewPublisher("MS Books"); //we are using extension method here
var kidPub = session.NewPublisher("Kids Books");
var johnBio = ConstructLongText(4000);
var authorJohn = session.NewAuthor("John", "Sharp", johnBio);
var authorJack = session.NewAuthor("Jack", "Pound");
var authorJim = session.NewAuthor("Jim", "Hacker"); //this author is not user - we'll use this author to check some tricky query in tests
var john = authorJohn.User = session.CreateUser("John", UserType.Author);
var pubDate = DateTime.Today.AddYears(-1);
//Books on programming from MS Books
var csBook = session.NewBook(BookEdition.Paperback | BookEdition.EBook, BookCategory.Programming,
"c# Programming", "Expert programming in c#", msPub, pubDate, 20.0m);
// Some multiline text in Abstract
csBook.Abstract = @"Expert guide to programming in c# 4.0.
Highly recommended for beginners and experts.
Covers c# 4.0.";
csBook.CoverImage = LoadImageFromResource(session, "csBookCover.jpg");
csBook.Authors.Add(authorJohn); //this is many-to-many
csBook.Authors.Add(authorJack);
csBook.Editor = session.EntitySet<IUser>().First(u => u.UserName == "Linda");
var vbBook = session.NewBook(BookEdition.Paperback | BookEdition.Hardcover, BookCategory.Programming,
"VB Programming", "Expert programming in VB", msPub, pubDate, 25.0m);
vbBook.Authors.Add(authorJack);
vbBook.CoverImage = LoadImageFromResource(session, "vbBookCover.jpg");
//Folk tale, no authors
var kidBook = session.NewBook(BookEdition.Hardcover, BookCategory.Kids,
"Three little pigs", "Folk tale", kidPub, pubDate, 10.0m);
var winBook = session.NewBook(BookEdition.Hardcover, BookCategory.Programming,
"Windows Programming", "Introduction to Windows Programming", msPub, pubDate.AddYears(-10), 30.0m);
winBook.Authors.Add(authorJohn);
winBook.CoverImage = LoadImageFromResource(session, "winBookCover.jpg");
var comicBook = session.NewBook(BookEdition.Paperback, BookCategory.Fiction, "IronMan", null, kidPub, null, 3);
//Coupons
var coupon1 = session.NewCoupon("C1", 10, DateTime.Now.AddMonths(1));
var coupon2 = session.NewCoupon("C2", 10, DateTime.Now.AddMonths(1));
var coupon3 = session.NewCoupon("C3", 10, DateTime.Now.AddMonths(1));
try {
session.SaveChanges(); //Save books, coupons, users and logins
} catch(ClientFaultException ex) {
var msgs = ex.GetMessages();
Debug.WriteLine(msgs);
throw;
}
//Orders
var dora = session.EntitySet<IUser>().First(u => u.UserName == "Dora");
var doraOrder = session.NewOrder(dora);
doraOrder.Add(csBook, 1);
doraOrder.Add(kidBook, 2);
doraOrder.CompleteOrder("C1");
//Create one empty order, for testing includes in queries
var doraOrder2 = session.NewOrder(dora);
doraOrder2.Status = OrderStatus.Canceled;
var diego = session.EntitySet<IUser>().First(u => u.UserName == "Diego");
var diegoOrder = session.NewOrder(diego);
diegoOrder.Add(vbBook, 1);
diegoOrder.Add(csBook, 1);
diegoOrder.CompleteOrder();
//Reviews
var doraReview = session.NewReview(dora, csBook, 5, "Very interesting book!", "Liked it very much!");
var diegoReview = session.NewReview(diego, vbBook, 1, "Not worth it.", "Did not like it at all.");
// special reviews with text including wildcards for LIKE operator - will use them to test wildcard escaping in LIKE
var duffy = session.EntitySet<IUser>().First(u => u.UserName == "Duffy");
session.NewReview(duffy, comicBook, 1, "'Boo", "'Boo");
session.NewReview(duffy, comicBook, 1, "_Boo", "_Boo");
session.NewReview(duffy, comicBook, 1, "%Boo", "%Boo");
session.NewReview(duffy, comicBook, 1, "[Boo]", "[Boo]");
session.NewReview(duffy, comicBook, 1, "]Boo[", "]Boo[");
session.NewReview(duffy, comicBook, 1, @"\Boo\oo", @"\Boo\oo");
session.NewReview(duffy, comicBook, 1, @"/Boo/oo", @"/Boo/oo");
//Save orders
try {
session.SaveChanges();
} catch (ClientFaultException ex) {
var msgs = ex.GetMessages();
Debug.WriteLine(msgs);
throw;
}
}
示例7: GetActiveProcess
public ILoginProcess GetActiveProcess(OperationContext context, LoginProcessType processType, string token)
{
Util.Check(!string.IsNullOrWhiteSpace(token), "Process token may not be null");
var session = context.OpenSystemSession();
var hash = Util.StableHash(token);
//get process without expiration checking, we check it later
var query = from p in session.EntitySet<ILoginProcess>()
where p.ProcessType == processType && p.TokenHash == hash && p.Token == token
select p;
var process = query.FirstOrDefault();
if(process == null) {
LogIncident(context, LoginIncidentType, "ProcessNotFound", "Login process not found.", null, token);
return null;
}
if(process.Status != LoginProcessStatus.Active)
return null;
if (process.FailCount >= _settings.MaxFailCount) {
process.Status = LoginProcessStatus.AbortedAsFraud;
session.SaveChanges();
LogIncident(context, LoginIncidentType, "Aborted", "Login process aborted after too many failures.", process.Login, token);
return null;
}
var userName = process.Login.UserName;
if(process.ExpiresOn < App.TimeService.UtcNow) {
process.Status = LoginProcessStatus.Expired;
session.SaveChanges();
LogIncident(context, LoginIncidentType, "Expired", "Login process expired.", process.Login, token);
return null;
}
return process;
}
示例8: FindLoginExtraFactor
public ILoginExtraFactor FindLoginExtraFactor(OperationContext context, ExtraFactorTypes factorType, string factor)
{
//We search by hash first, then decrypt and compare value
var hash = Util.StableHash(factor);
var session = context.OpenSystemSession();
var hashMatches = session.EntitySet<ILoginExtraFactor>().Where(ef => ef.FactorType == factorType && ef.InfoHash == hash).ToList();
foreach(var match in hashMatches) {
var recFactor = match.Info.DecryptString(_settings.EncryptionChannelName);
if(recFactor == factor) {
VerifyExpirationSuspensionDates(match.Login);
return match;
}
}
return null;
}