text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using Microsoft.Ajax.Utilities; using TellStoryTogether.Models; using WebGrease.Css.Extensions; using WebMatrix.WebData; namespace TellStoryTogether.Helper { public class DAL { readonly UsersContext _context = new UsersContext(); private readonly UserProfile _user; private readonly int _userId = -1; public Article CurrentArticle; public DAL() { } public DAL(string name) { if (!WebSecurity.IsAuthenticated) return; _userId = WebSecurity.GetUserId(name); _user = _context.UserProfiles.First(p => p.UserId == _userId); } public DAL(int currentUserId) { if (!WebSecurity.IsAuthenticated) return; _userId = currentUserId; _user = _context.UserProfiles.First(p => p.UserId == _userId); } public int UserId() { return _userId; } public int UserPoint() { try { return _userId < 0 ? 0 : _context.UserProfiles.First(p => p.UserId == _userId).UserPoint; } catch (Exception) { return 0; } } public List<Article> GetArticlesByIdentifier(string identifier) { List<Article> articles = new List<Article>(); if (identifier == Constant.New) { } else { List<int> parallels = identifier.Split('-').Select(Int32.Parse).ToList(); int articleId = parallels[0]; Article articleTemp = _context.Articles.Include("Owner").Include("Genre").Include("Language").First(p => p.ArticleId == articleId); articles.Add(articleTemp); parallels.RemoveAt(0); foreach (int parallel in parallels) { articleTemp = _context.Articles.Include("Owner").First(p => p.ArticleInitId == articleId && p.Parallel == parallel); articles.Add(articleTemp); articleId = articleTemp.ArticleId; } } return articles; } public List<Genre> GetGenres() { return _context.Genres.ToList(); } public void SaveArticle(ref HttpPostedFileBase blob, string title, int articleInitId, string text, int serial, int min, int max, int languageId, int genreId, string identifier) { Guid guid = Guid.NewGuid(); string uniqueString = guid.ToString(); var fullPath = blob == null ? null : "/Images/StoryImage/" + uniqueString + ".png"; int parallel = 1; if (articleInitId != -1) { parallel = _context.Articles.Count(p => p.ArticleInitId == articleInitId) + 1; _context.Articles.First(p => p.ArticleId == articleInitId).IsLast = false; } Language language = _context.Languages.First(p => p.LanguageId == languageId); Genre genre = _context.Genres.First(p => p.GenreId == genreId); Article newArticle = new Article { ArticleInitId = articleInitId, Title = title, Text = text, PictureUrl = fullPath, Point = 0, Seen = 0, Serial = serial, Parallel = parallel, Favorite = 0, Owner = _user, Language = language, Genre = genre, Time = DateTime.Now, MinChar = min, MaxChar = max, IsLast = true }; _context.Articles.Add(newArticle); _user.UserPoint = _user.UserPoint + Constant.CreatePoint; _context.SaveChanges(); string newIdentifier = newArticle.ArticleInitId == -1 ? newArticle.ArticleId.ToString() : identifier + "-" + newArticle.Parallel; newArticle.Identifier = newIdentifier; newArticle.TopArticleInitId = Int32.Parse(newArticle.Identifier.Split('-')[0]); _context.SaveChanges(); CurrentArticle = newArticle; } public void EditArticle(int articleId, ref HttpPostedFileBase blob, string title, string text, int min, int max, int languageId, int genreId) { Article article = _context.Articles.First(p => p.ArticleId == articleId); Guid guid = Guid.NewGuid(); string uniqueString = guid.ToString(); var fullPath = blob == null ? article.PictureUrl : "/Images/StoryImage/" + uniqueString + ".png"; Language language = _context.Languages.First(p => p.LanguageId == languageId); Genre genre = _context.Genres.First(p => p.GenreId == genreId); article.Title = title; article.Text = text; article.PictureUrl = fullPath; article.Language = language; article.Genre = genre; article.MinChar = min; article.MaxChar = max; if (article.ArticleInitId == -1) { var childArticles = _context.Articles.Where(p => p.TopArticleInitId == articleId); foreach (Article childArticle in childArticles) { childArticle.Title = title; childArticle.Language = language; childArticle.Genre = genre; childArticle.MinChar = min; childArticle.MaxChar = max; } } _context.SaveChanges(); CurrentArticle = article; } public string[] SplitFirstId_PopulateNewIdentifier(string articleIdOrIdentifier) { string articleId; string identifier = ""; if (articleIdOrIdentifier.Contains("-")) { List<int> tempList = articleIdOrIdentifier.Split('-').Select(Int32.Parse).ToList(); int tempId = tempList[0]; articleId = tempId.ToString(); tempList.RemoveAt(0); foreach (int parallel in tempList) { tempId = _context.Articles.First(p => p.ArticleInitId == tempId && p.Parallel == parallel).ArticleId; } identifier = articleIdOrIdentifier; var tempArticles = _context.Articles.Where(p => p.ArticleInitId == tempId).OrderByDescending(p => p.Point).ToList(); while (tempArticles.Count != 0) { Article tempArticle = tempArticles[0]; tempId = tempArticle.ArticleId; identifier = identifier + "-" + tempArticle.Parallel; tempArticles = _context.Articles.Where(p => p.ArticleInitId == tempId).OrderByDescending(p => p.Point).ToList(); } } else { articleId = articleIdOrIdentifier; int tempId = Int32.Parse(articleId); var tempArticles = _context.Articles.Where(p => p.ArticleInitId == tempId).OrderByDescending(p => p.Point).ToList(); while (tempArticles.Count != 0) { Article tempArticle = tempArticles[0]; tempId = tempArticle.ArticleId; identifier = identifier + "-" + tempArticle.Parallel; tempArticles = _context.Articles.Where(p => p.ArticleInitId == tempId).OrderByDescending(p => p.Point).ToList(); } identifier = articleId + identifier; } return new[] { articleId, identifier }; } public void AddNotificationRecord(string state) { int articleId = CurrentArticle.ArticleId; switch (state) { case Constant.CreateState: Notification newCreateNotif = new Notification { User = _user, Article = CurrentArticle, Visited = false, Seen = false, CreateState = true, Time = DateTime.Now, ForkedArticleIds = "", Content = "", Identifier = CurrentArticle.Identifier }; _context.Notifications.Add(newCreateNotif); break; case Constant.CommentState: if (_context.Notifications.Any(p => p.User.UserId == _userId && p.Article.ArticleId == articleId && (p.CreateState || p.CommentState))) { return; } var favoriteNotifs = _context.Notifications.Where( p => p.User.UserId == _userId && p.Article.ArticleId == articleId && p.FavoriteState); if (favoriteNotifs.Any()) { foreach (Notification favoriteNotif in favoriteNotifs) { favoriteNotif.CommentState = true; } } else { Notification newCommentNotif = new Notification { User = _user, Article = CurrentArticle, Visited = false, Seen = false, CommentState = true, Time = DateTime.Now, ForkedArticleIds = "", Content = "", Identifier = CurrentArticle.Identifier }; _context.Notifications.Add(newCommentNotif); } break; case Constant.FavoriteState: if (_context.Notifications.Any(p => p.User.UserId == _userId && p.Article.ArticleId == articleId && (p.CreateState||p.FavoriteState))) { return; } var commentNotifs = _context.Notifications.Where( p => p.User.UserId == _userId && p.Article.ArticleId == articleId && p.CommentState); if (commentNotifs.Any()) { foreach (Notification commentNotif in commentNotifs) { commentNotif.FavoriteState = true; } } else { Notification newFavoriteNotif = new Notification { User = _user, Article = CurrentArticle, Visited = false, Seen = false, FavoriteState = true, Time = DateTime.Now, ForkedArticleIds = "", Content = "", Identifier = CurrentArticle.Identifier }; _context.Notifications.Add(newFavoriteNotif); } break; } _context.SaveChanges(); } public void RemoveNotificationRecord(string state) { int articleId = CurrentArticle.ArticleId; switch (state) { case Constant.FavoriteState: var favoriteNotifs = _context.Notifications.Where( p => p.User.UserId == _userId && p.Article.ArticleId == articleId && p.FavoriteState); if (favoriteNotifs.Any()) { if (favoriteNotifs.First().CommentState) { foreach (Notification favoriteNotif in favoriteNotifs) { favoriteNotif.FavoriteState = false; } } else { _context.Notifications.RemoveRange(favoriteNotifs); } _context.SaveChanges(); } else { return; } break; case Constant.CommentState: return; break; case Constant.CreateState: return; break; } } public void SubscribeForkNotificationForEarlierArticles(string identifier) { if (identifier == Constant.New) return; string newArticleId = CurrentArticle.ArticleId.ToString(); List<int> s = identifier.Split('-').Select(Int32.Parse).ToList(); int articleId = s[0]; Article firstArticle = _context.Articles.Include(p=>p.Owner).First(p => p.ArticleInitId == -1 && p.ArticleId==articleId); List<Article> articleTail = new List<Article> {firstArticle}; s.RemoveAt(0); int articleIntId = articleId; foreach (int parallel in s) { var nextArticle = _context.Articles.Include(p=>p.Owner).First(p => p.ArticleInitId == articleIntId && p.Parallel == parallel); articleIntId = nextArticle.ArticleId; articleTail.Add(nextArticle); } List<int> articleIdsFiltered = articleTail.Where(p => p.Owner.UserId != _userId) .GroupBy(p => p.Owner.UserId) .Select(p => p.Last()) .Select(p => p.ArticleId) .ToList(); foreach (int id in articleIdsFiltered) { _context.Notifications.Where( p => p.Article.ArticleId == id && p.User.UserId != _userId && !p.Seen && (p.CreateState || p.FavoriteState)).ForEach(p => { p.Forked++; p.Time = DateTime.Now; p.ForkedArticleIds = p.ForkedArticleIds=="" ? newArticleId : p.ForkedArticleIds + "|" + newArticleId; }); } _context.SaveChanges(); } public void SubscribeNotification(string action) { int articleId = CurrentArticle.ArticleId; //UserProfile articleOwner = _context.Articles.Include(p=>p.Owner).First(p => p.ArticleId == articleId).Owner; switch (action) { case Constant.CommentAction: _context.Notifications.Where(p => p.Article.ArticleId == articleId && p.User.UserId != _userId && !p.Seen).ForEach(p => { p.Commented++; p.Time = DateTime.Now; }); break; case Constant.LikeAction: _context.Notifications.Where(p => p.Article.ArticleId == articleId && p.User.UserId != _userId && p.CreateState && !p.Seen) .ForEach(p => { p.Liked++; p.Time = DateTime.Now; }); break; case Constant.UnLikeAction: _context.Notifications.Where(p => p.Article.ArticleId == articleId && p.User.UserId != _userId && p.CreateState && !p.Seen) .ForEach(p => { p.Liked--; p.Time = DateTime.Now; }); break; case Constant.FavoriteAction: _context.Notifications.Where(p => p.Article.ArticleId == articleId && p.User.UserId != _userId && p.CreateState && !p.Seen) .ForEach(p => { p.Favorited++; p.Time = DateTime.Now; }); break; case Constant.UnFavoriteAction: _context.Notifications.Where(p => p.Article.ArticleId == articleId && p.User.UserId != _userId && p.CreateState && !p.Seen) .ForEach(p => { p.Favorited--; p.Time = DateTime.Now; }); break; } _context.SaveChanges(); } public Tuple<int, NotificationShow[]> GetNotification() { if (_userId < 0) { return new Tuple<int, NotificationShow[]>(0, new NotificationShow[] { }); } // removed (DbFunctions.DiffDays(DateTime.Now, p.Time) < 30) Notification[] notifications = _context.Notifications.Where( p => p.User.UserId == _userId && (p.Commented > 0 || p.Favorited > 0 || p.Forked > 0 || p.Liked > 0)).Include(p => p.Article).ToArray(); notifications = notifications.OrderByDescending(p => p.Time).Select(p => p.Seen ? p : new ClassHelper().CreateContent(p)).ToArray(); int unseen = notifications.Count(p => !p.Seen); _context.SaveChanges(); return new Tuple<int, NotificationShow[]>(unseen, notifications.ToNotificationShows().ToArray()); } public bool SeeNotification() { var unseenNotification = _context.Notifications.Include(p => p.Article).Include(p => p.User).Where(p => p.User.UserId == _userId && p.Seen == false && p.Content != ""); foreach (Notification notification in unseenNotification) { notification.Seen = true; Notification newNotification = new Notification { User = notification.User, Article = notification.Article, Identifier = notification.Identifier, Time = DateTime.Now, Favorited = 0, Commented = 0, Forked = 0, Liked = 0, Seen = false, Visited = false, ForkedArticleIds = "", CreateState = notification.CreateState, CommentState = notification.CommentState, FavoriteState = notification.FavoriteState, Content = "" }; _context.Notifications.Add(newNotification); } _context.SaveChanges(); return true; } public ArticleUserBase GetArticleUserBaseById(int articleId) { List<int> userComments = _context.Comments.Where(p => p.User.UserId == _userId).Select(p => p.Article.ArticleId).ToList(); List<int> userPoints = _context.ArticlePoints.Where(p => p.User.UserId == _userId).Select(p => p.Article.ArticleId).ToList(); List<int> userFavorites = _context.ArticleFavorites.Where(p => p.User.UserId == _userId).Select(p => p.Article.ArticleId).ToList(); ArticleUserBase output = _context.Articles.Include("Owner").Include("Language").First(p => p.ArticleId == articleId).ArticleToArticleUser(userPoints, userFavorites, userComments, _userId); return output; } public List<List<ArticleUserBase>> GetTailArticleUserBaseByIdentifier(string identifier) { List<int> userComments = _context.Comments.Where(p => p.User.UserId == _userId).Select(p => p.Article.ArticleId).ToList(); List<int> userPoints = _context.ArticlePoints.Where(p => p.User.UserId == _userId).Select(p => p.Article.ArticleId).ToList(); List<int> userFavorites = _context.ArticleFavorites.Where(p => p.User.UserId == _userId).Select(p => p.Article.ArticleId).ToList(); List<List<ArticleUserBase>> output = new List<List<ArticleUserBase>>(); List<int> parallelList = identifier.Split('-').Select(Int32.Parse).ToList(); int sourceId = parallelList[0]; parallelList.RemoveAt(0); foreach (int i in parallelList) { List<ArticleUserBase> tempArticles = _context.Articles.Include("Owner").Where(p => p.ArticleInitId == sourceId).ArticlesToArticleUsers(userPoints, userFavorites, userComments,_userId).OrderByDescending(p => p.Parallel == i).ThenByDescending(p => p.Point).ToList(); sourceId = tempArticles[0].ArticleId; output.Add(tempArticles); } return output; } public List<CommentTime> GetCommentsByArticleId(string articleId) { int articleIdInt = Int32.Parse(articleId); return _context.Comments.Include("User").Where(p => p.Article.ArticleId == articleIdInt).ToList().ChangeTime().ToList(); } public void SaveComment(int articleId, string content) { Article article = _context.Articles.First(p => p.ArticleId == articleId); CurrentArticle = article; Comment comment = new Comment { Article = article, Content = content, User = _user, Time = DateTime.Now }; _context.Comments.Add(comment); _context.Articles.First(p => p.ArticleId == articleId).Comment++; _context.SaveChanges(); } public bool Like(int articleId) { try { CurrentArticle = _context.Articles.Include(p=>p.Owner).First(p => p.ArticleId == articleId); if (CurrentArticle.Owner.UserId == _userId) { return false; } ArticlePoint articlePoint = new ArticlePoint() { Article = CurrentArticle, User = _user }; _context.ArticlePoints.Add(articlePoint); CurrentArticle.Point++; _context.SaveChanges(); return true; } catch(Exception) { return false; } } public bool UnLike(int articleId) { try{ CurrentArticle = _context.Articles.Include(p => p.Owner).First(p => p.ArticleId == articleId); if (CurrentArticle.Owner.UserId == _userId) { return false; } ArticlePoint articlePoint = _context.ArticlePoints.First(p => p.Article.ArticleId == articleId && p.User.UserId == _userId); _context.ArticlePoints.Remove(articlePoint); CurrentArticle.Point--; _context.SaveChanges(); return true; } catch (Exception) { return false; } } public bool Star(int articleId) { try{ CurrentArticle = _context.Articles.Include(p => p.Owner).First(p => p.ArticleId == articleId); if (CurrentArticle.Owner.UserId == _userId) { return false; } ArticleFavorite articleFavorite = new ArticleFavorite() { Article = CurrentArticle, User = _user }; _context.ArticleFavorites.Add(articleFavorite); CurrentArticle.Favorite++; _context.SaveChanges(); return true; } catch (Exception) { return false; } } public bool UnStar(int articleId) { try{ CurrentArticle = _context.Articles.Include(p => p.Owner).First(p => p.ArticleId == articleId); if (CurrentArticle.Owner.UserId == _userId) { return false; } ArticleFavorite articleFavorite = _context.ArticleFavorites.First(p => p.Article.ArticleId == articleId && p.User.UserId == _userId); _context.ArticleFavorites.Remove(articleFavorite); CurrentArticle.Favorite--; _context.SaveChanges(); return true; } catch (Exception) { return false; } } public List<Article> GetFavoriteArticle() { if (_userId < 0) { return null; } var queryFavoriteIds = _context.ArticleFavorites.Where(p => p.User.UserId == _userId) .Include(p => p.Article) .Select(p => p.Article.ArticleId); List<int> favoriteIds = queryFavoriteIds.ToList(); favoriteIds.Reverse(); return favoriteIds.Select(p => _context.Articles.First(q => q.ArticleId == p)).ToList(); } public Tuple<Article[], int> GetFirstNFavoriteArticle(int take) { if (_userId < 0) { return new Tuple<Article[], int>(new Article[] { }, 0); } var queryFavoriteIds = _context.ArticleFavorites.Where(p => p.User.UserId == _userId) .Include(p => p.Article) .Select(p => p.Article.ArticleId); int count = queryFavoriteIds.Count(); List<int> favoriteIds = queryFavoriteIds.TakeLast(take).ToList(); favoriteIds.Reverse(); return new Tuple<Article[], int>(favoriteIds.Select(p => _context.Articles.First(q => q.ArticleId == p)).ToArray(),count); } public List<Article> GetScriptArticle() { if (_userId < 0) { return null; } var queryArticles = _context.Articles.Where(p => p.Owner.UserId == _userId); List<Article> articles = queryArticles.ToList(); articles.Reverse(); return articles; } public Tuple<Article[], int> GetFirstNScriptArticle(int take) { if (_userId < 0) { return new Tuple<Article[], int>(new Article[]{}, 0); } var queryArticles = _context.Articles.Where(p => p.Owner.UserId == _userId); int count = queryArticles.Count(); List<Article> articles = queryArticles.TakeLast(take).ToList(); articles.Reverse(); return new Tuple<Article[], int>(articles.ToArray(), count); } public List<Genre> GetGenreIdsWithMoreThan3() { return _context.Articles.GroupBy(p => p.Genre).Select(group => new { Genre = group.Key, Count = group.Count() }).Where(p => p.Count > 3).Select(p => p.Genre).ToList(); } // key:{Genre, User, Search, Best} public List<Article> GetArticles(string key, string value, bool increasing, int from, int take) { int valueId = 0; List<Article> articles = new List<Article>(); switch (key) { case "Genre": valueId = Int32.Parse(value); articles = _context.Articles.Where(p => p.ArticleInitId == -1 && p.Genre.GenreId == valueId) .OrderByDescending(p => p.Point) .Skip(from) .Take(take) .Include(p => p.Owner) .Include(p => p.Genre) .Include(p => p.Language) .ToList(); break; case "User": valueId = Int32.Parse(value); articles = _context.Articles.Where(p => p.ArticleInitId == -1 && p.Owner.UserId == valueId) .OrderByDescending(p => p.Point) .Skip(from) .Take(take) .Include(p => p.Owner) .Include(p => p.Genre) .Include(p => p.Language) .ToList(); break; case "Search": articles = _context.Articles.Where(p => p.ArticleInitId == -1 && (p.Title.ToLower().Contains(value.ToLower()) || p.Text.ToLower().Contains(value.ToLower()))) .OrderByDescending(p => p.Point) .Skip(from) .Take(take) .Include(p => p.Owner) .Include(p => p.Genre) .Include(p => p.Language) .ToList(); break; case "Best": articles = _context.Articles.Where(p=>p.ArticleInitId == -1) .OrderByDescending(p => p.Point) .Skip(from) .Take(take) .Include(p => p.Owner) .Include(p => p.Genre) .Include(p => p.Language) .ToList(); break; case "Language": valueId = Int32.Parse(value); articles = _context.Articles.Where(p => p.ArticleInitId == -1 && p.Language.LanguageId == valueId) .OrderByDescending(p => p.Point) .Skip(from) .Take(take) .Include(p => p.Owner) .Include(p => p.Genre) .Include(p => p.Language) .ToList(); break; case "ArticleId": valueId = Int32.Parse(value); articles = _context.Articles.Where(p => p.ArticleId == valueId) .Include(p => p.Owner) .Include(p => p.Genre) .Include(p => p.Language) .ToList(); break; } return articles; } // key:{Genre, User, Me} public int NumberOfArticles(string key, string value) { int valueId = 0; int articleNumber = 0; switch (key) { case "Genre": valueId = Int32.Parse(value); articleNumber = _context.Articles.Count(p => p.ArticleInitId == -1 && p.Genre.GenreId == valueId); break; case "User": valueId = Int32.Parse(value); articleNumber = _context.Articles.Count(p => p.ArticleInitId == -1 && p.Owner.UserId == valueId); break; case "Me": articleNumber = _context.Articles.Count(p => p.ArticleInitId == -1 && p.Owner.UserId == _userId); break; } return articleNumber; } public bool IsInformedUser() { if (_context.Articles.Count(p => p.Owner.UserId == _userId) > 2) { return true; } if (_context.ArticleFavorites.Count(p => p.User.UserId == _userId) > 2) { return true; } if (_context.ArticlePoints.Count(p => p.User.UserId == _userId) > 2) { return true; } return false; } public Language[] GetLanguages() { return _context.Languages.ToArray(); } public bool RemoveArticle(int articleId) { Article article = _context.Articles.Include("Owner").First(p => p.ArticleId == articleId); if (!article.IsLast || article.Owner.UserId != _userId) return false; //take care of parallel issue List <Article> sameLevelArticles = _context.Articles.Where(p => p.ArticleInitId == article.ArticleInitId).ToList(); if (sameLevelArticles.Count == 1) { _context.Articles.First(p => p.ArticleId == article.ArticleInitId).IsLast = true; } else { foreach (Article sameLevelArticle in sameLevelArticles) { if (sameLevelArticle.Parallel > article.Parallel) { sameLevelArticle.Parallel--; } } } _context.Notifications.RemoveRange(_context.Notifications.Where(p => p.Article.ArticleId == articleId)); _context.ArticleFavorites.RemoveRange(_context.ArticleFavorites.Where(p => p.Article.ArticleId == articleId)); _context.ArticlePoints.RemoveRange(_context.ArticlePoints.Where(p => p.Article.ArticleId == articleId)); _context.Comments.RemoveRange(_context.Comments.Where(p => p.Article.ArticleId == articleId)); _context.SaveChanges(); _context.Articles.Remove(article); _context.SaveChanges(); return true; } } }
//Dice Rolling public void DiceRolling(List<string> readInList) { foreach (string s in readInList) { helperMethodDiceRolling(s); } } public void helperMethodDiceRolling(string valueFromList) { double tempVal = 0; double.TryParse(valueFromList, out tempVal); Random rnd = new Random(); int random1To6 = rnd.Next(1, 7); double multiplyBy = 0; multiplyBy = tempVal * random1To6; double flooredValue = Math.Floor(multiplyBy); double finalAnswer = 0; finalAnswer = flooredValue + 1; Console.WriteLine(finalAnswer); }
using MyShop.Core.Contracts; using MyShop.Core.Model; using MyShop.Core.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyShop.Services { public class OrderService: IOrderService { IRepository<Order> _orderContext; public OrderService(IRepository<Order> repository) { _orderContext = repository; } public void CreateOrder(Order order, List<BasketItemViewModel> basketItems) { //list of basket item-> basketItems foreach(var item in basketItems) { order.OrderItems.Add(new OrderItem { ProductId=item.Id, ProductName=item.ProductName, Price=item.Price, Image=item.Image, Quanity=item.Quantity }); } _orderContext.Insert(order); _orderContext.Commit(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ATeamFitness.Data; using ATeamFitness.Models; using System.Security.Claims; namespace ATeamFitness.Controllers { public class CustomersController : Controller { private readonly ApplicationDbContext _context; public CustomersController(ApplicationDbContext context) { _context = context; } // GET: Customers public async Task<IActionResult> Index() { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); var customer = _context.Customers.Where(c => c.IdentityUserId == userId).SingleOrDefault(); if (customer == null) { return RedirectToAction("Create"); } return View(customer); } // GET: Customers/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var PersonalTrainers = await _context.PersonalTrainers .Include(c => c.IdentityUser) .FirstOrDefaultAsync(m => m.PersonalTrainerId == id); if (PersonalTrainers== null) { return NotFound(); } return View(PersonalTrainers); } // GET: Customers/Create public IActionResult Create() { ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id"); return View(); } // POST: Customers/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("CustomerId,Name,FitnessGoal,FitnessPlan,DietPlan,PictureUrl,IdentityUserId")] Customer customer) { if (ModelState.IsValid) { var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); customer.IdentityUserId = userId; customer.TimeBlockId = GenerateRandomAlphanumericString(); _context.Add(customer); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", customer.IdentityUserId); return View(customer); } // GET: Customers/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var customer = await _context.Customers.FindAsync(id); if (customer == null) { return NotFound(); } ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", customer.IdentityUserId); return View(customer); } // POST: Customers/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("CustomerId,Name,FitnessGoal,FitnessPlan,DietPlan,IdentityUserId")] Customer customer) { if (id != customer.CustomerId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(customer); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CustomerExists(customer.CustomerId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", customer.IdentityUserId); return View(customer); } // GET: Customers/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var customer = await _context.Customers .Include(c => c.IdentityUser) .FirstOrDefaultAsync(m => m.CustomerId == id); if (customer == null) { return NotFound(); } return View(customer); } // POST: Customers/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var customer = await _context.Customers.FindAsync(id); _context.Customers.Remove(customer); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool CustomerExists(int id) { return _context.Customers.Any(e => e.CustomerId == id); } public async Task<IActionResult> PersonalTrainersList() { var personalTrainersList = _context.PersonalTrainers.ToList(); return View(personalTrainersList); } public async Task<IActionResult> ViewTimeBlocks() { var personalTrainerTimeBlocks = _context.TimeBlocks.ToList(); return View(personalTrainerTimeBlocks); } public async Task<IActionResult> Select(string TimeBlockKey) { var SelectedTimeBlock = _context.TimeBlocks.Where(c => c.TimeBlockKey == TimeBlockKey).FirstOrDefault(); return View(SelectedTimeBlock); } [HttpPost] public async Task<IActionResult> Select(int CustomerId, string TimeBlockKey) { var SelectedTimeBlock = _context.TimeBlocks.Where(c => c.TimeBlockKey == TimeBlockKey).FirstOrDefault(); return View(SelectedTimeBlock); } public string GenerateRandomAlphanumericString() { var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var stringChars = new char[50]; var random = new Random(); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } var finalString = new String(stringChars); return finalString; } public async Task<IActionResult> Confirmation() { return View(); } public async Task<IActionResult> ThumbsUp(int? id) { var PersonalTrainer = _context.PersonalTrainers.Where(p => p.PersonalTrainerId == id).FirstOrDefault(); PersonalTrainer.ThumbsUp++; _context.SaveChanges(); return RedirectToAction(nameof(Index)); } public async Task<IActionResult> ThumbsDown(int? id) { var PersonalTrainer = _context.PersonalTrainers.Where(p => p.PersonalTrainerId == id).FirstOrDefault(); PersonalTrainer.ThumbsDown++; _context.SaveChanges(); return RedirectToAction(nameof(Index)); } } }
using System; namespace ApiTemplate.Core.Entities.Base { public abstract class BaseEntity <TKey>:IEntity { public TKey Id { get; set; } public DateTime CreateDate { get; set; } } public abstract class BaseEntity : BaseEntity<long> { } }
using System; namespace ConditionalBranch { class Program { static void Main(string[] args) { #region IF STATEMENT int number = 30; // The condition must be met to run the code inside the if statement if (number == 30) { Console.WriteLine("Number is 30"); } #endregion #region CONDITIONAL OPERATOR /* EQUALITY OPERATOR */ int age = 20; // If equal if (age == 17) { Console.WriteLine("You have the rights to vote"); } string pass = "password"; // If not equal if (pass != "password") { Console.WriteLine("Access denied!"); } /* RELATIONAL OPERATOR */ int mark; mark = 80; if (mark < 50) { Console.WriteLine("Your mark is below 50"); } if (mark > 50) { Console.WriteLine("Your mark is above 50"); } if (mark <= 50) { Console.WriteLine("Your mark is less than or equal to 50"); } if (mark >= 50) { Console.WriteLine("Your mark is more than or equal to 50"); } #endregion #region IF-ELSE STATEMENT AND TERNARY OPERATOR mark = 50; if (mark >= 60) { Console.WriteLine("You passed!"); } else { Console.WriteLine("You failed!"); } // The code above can be refactored using ternary operator // [condition] ? [first expression] : [second expression] Console.WriteLine(mark >= 60 ? "You passed!" : "You failed"); #endregion #region LOGICAL OPERATOR /* LOGICAL OPERATOR */ string user = "username"; string pwd = "password"; // Operator & (Logical AND) if (user == "username" & pwd == "password") { Console.WriteLine("You are logged in"); } else { Console.WriteLine("Access denied!"); } // Operator && (Short circuit logical AND) if (user == "username" && pwd == "password") { Console.WriteLine("You are logged in"); } else { Console.WriteLine("Access denied!"); } // Difference between using & and && // note: The method SeconCondition() is defined below the main method // Run the code, analyse the output, find the difference! bool a = false & SecondCondition(); Console.WriteLine("Value of a: {0}", a); Console.WriteLine("========================"); bool b = true & SecondCondition(); Console.WriteLine("Value of b: {0}", b); Console.WriteLine("========================"); bool c = false && SecondCondition(); Console.WriteLine("Value of c: {0}", c); Console.WriteLine("========================"); bool d = true && SecondCondition(); Console.WriteLine("Value of d: {0}", d); age = 3; int height = 110; // Operator | (Logical OR) if (age >= 3 | height >= 100) { Console.WriteLine("You are allowed to play"); } else { Console.WriteLine("You are not allowed to play"); } // Operator || (Short circuit logical OR) if (age >= 3 || height >= 100) { Console.WriteLine("You are allowed to play"); } else { Console.WriteLine("You are not allowed to play"); } // Difference between usin | and || bool f = false | SecondCondition(); Console.WriteLine("value of f: {0}", f); Console.WriteLine("========================"); bool g = true | SecondCondition(); Console.WriteLine("value of g: {0}", g); Console.WriteLine("========================"); bool h = false || SecondCondition(); Console.WriteLine("value of h: {0}", h); Console.WriteLine("========================"); bool i = true || SecondCondition(); Console.WriteLine("value of i: {0}", i); // Operator ^ (XOR) Console.WriteLine("'true' XOR 'true' is: {0}", true ^ true); // output: False Console.WriteLine("'true' XOR 'false' is: {0}", true ^ false); // output: True Console.WriteLine("'false' XOR 'true' is: {0}", false ^ true); // output: True Console.WriteLine("'false' XOR 'false' is: {0}", false ^ false); // output: False // Operator ! (NOT) age = 20; // Using realational operator to assigned a value to boolean variable bool isAdult = age >= 17; if (!isAdult) { Console.WriteLine("You are not old enough!"); } #endregion #region IF-ELSE IF STATEMENT mark = 79; if (mark >= 0 && mark < 20) { Console.WriteLine("Your grade: E"); } else if (mark >= 20 && mark < 40) { Console.WriteLine("Your grade: D"); } else if (mark >= 40 && mark < 60) { Console.WriteLine("Your grade: C"); } else if (mark >= 60 && mark < 80) { Console.WriteLine("Your grade: B"); } else if (mark >= 80 && mark <= 100) { Console.WriteLine("Your grade: A"); } else { Console.WriteLine("The given grade is outside the possible value"); } #endregion #region SWITCH STATEMENT // Constant Pattern Console.Write("Choose your favorite fruit (apel/orange/banana): "); string pilihan = Console.ReadLine().ToLower(); if (pilihan == "apel") Console.WriteLine("You choosed apel"); else if (pilihan == "orange") Console.WriteLine("You choosed orange"); else if (pilihan == "banana") Console.WriteLine("You choosed banana"); else Console.WriteLine("You choosed another fruit"); switch (pilihan) { case "apel": Console.WriteLine("You choosed apel"); break; case "orange": Console.WriteLine("You choosed orange"); break; case "banana": Console.WriteLine("You choosed banana"); break; default: Console.WriteLine("You choose another fruit"); break; } // Type Pattern Console.WriteLine("1 [Integer (5)], 2 [Double (2.5)], 3 [String (\"Hi\")]"); Console.Write("Insert your choice: "); string userInput = Console.ReadLine(); object userChoice; switch (userInput) { case "1": userChoice = 5; break; case "2": userChoice = 2.5; break; case "3": userChoice = "Hi"; break; default: userChoice = 5; break; } switch (userChoice) { case int varInt: Console.WriteLine("You choosed integer with value of: {0}", varInt); break; case double varDouble: Console.WriteLine("You choosed double with value of: {0}", varDouble); break; case string varStr: Console.WriteLine("You choosed string with value of: {0}", varStr); break; default: Console.WriteLine("You choosed different thing"); break; } // Using when clause Console.Write("Insert a number: "); string inputValue = Console.ReadLine(); mark = int.TryParse(inputValue, out int n) ? n : -1; switch (mark) { // Eror! "The switch case has already been handled by a previous case." // case int i: // // do something // break; case int x when x >= 0 & x < 20: Console.WriteLine("Your grade: E"); break; case int x when x >= 20 & x < 40: Console.WriteLine("Your grade: D"); break; case int x when x >= 40 & x < 60: Console.WriteLine("Your grade: C"); break; case int x when x >= 60 & x < 80: Console.WriteLine("Your grade: B"); break; case int x when x >= 80 & x <= 100: Console.WriteLine("Your grade: A"); break; default: Console.WriteLine("The value can't be converted into valid grade"); break; } #endregion } static bool SecondCondition() { Console.WriteLine("This condition is also being evaluated"); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Loops_Training { class Program { static void Main(string[] args) { uint num = uint.Parse(Console.ReadLine()); ulong factorial = 1; while (num > 1) { factorial *= num; num--; } Console.WriteLine(factorial); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NahodnePole { class Program { static void Main(string[] args) { int[] pole = new int[10]; Random random = new Random(); int pocetSkoku = 0; for (int i = 0; i < pole.Length; i++) { pole[i] = random.Next(1, 7); if (i == pole.Length - 1) Console.WriteLine(pole[i]); else Console.Write(pole[i] + ", "); } for (int i = 0; i < pole.Length; i++) { i += pole[i] - 1; pocetSkoku++; } Console.WriteLine(pocetSkoku); Console.ReadKey(true); } } }
namespace WinminePainter { struct Vector { private int x; private int y; public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public Vector(int x, int y) { this.x = x; this.y = y; } public static bool operator ==(Vector v1, Vector v2) { if (v1.X == v2.X && v1.Y == v2.Y) { return true; } return false; } public static bool operator !=(Vector v1, Vector v2) { if (v1.X == v2.X && v1.Y == v2.Y) { return false; } return true; } public static Vector operator +(Vector v1, Vector v2) { return new Vector(v1.x + v2.x, v1.y + v2.y); } public static Vector operator -(Vector v1, Vector v2) { return new Vector(v1.x - v2.x, v1.y - v2.y); } public override bool Equals(object obj) { if (!(obj is Vector)) { return false; } if (((Vector)obj).X == X && ((Vector)obj).Y == Y) { return true; } return false; } public override int GetHashCode() { return ToString().GetHashCode(); } public override string ToString() { return (x.ToString() + ";" + Y.ToString()); } } }
using System; using System.Collections.Generic; using System.Text; namespace Manager.Interface { public interface IUserRoleManager { public object Create(string userName); public object Update(long userId, string fristName, string lastName); public object ActiveOrDeactive(long userId); public object GetAllUserRole(); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using PopCinema.Models; namespace PopCinema.Controllers { public class FilmesController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: Filmes public ActionResult Index() { return View(db.Filmes.ToList()); } // GET: Filmes/Details/5 /// <summary> /// Mostra os dados de um Filme /// </summary> /// <param name="id">identifica um filme</param> /// <returns>devolve a View com os dados</returns> public ActionResult Details(int? id) { if (id == null) { //caso não seja devolvido nenhum id, o utilizador //retorna para a página Index return RedirectToAction("Index"); } Filmes filme = db.Filmes.Find(id); if (filme == null) { //o filme não foi encontrado (não existe) return RedirectToAction("Index"); } //enviar para a View os dados do Filme que foi procurado e encontrado return View(filme); } // GET: Filmes/Create [Authorize(Roles = "Admin")] public ActionResult Create() { return View(); } // POST: Filmes/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,Titulo,Ano,Sinopse,Capa,Trailer")] Filmes filme, HttpPostedFileBase UploadImag) { string path = ""; bool PictureExist=false; if (UploadImag == null) { filme.Capa = "noPoster.jpg"; } else { if (UploadImag.ContentType == "image/jpg" || UploadImag.ContentType == "image/png") { string extensao = Path.GetExtension(UploadImag.FileName).ToLower(); Guid g; g = Guid.NewGuid(); string nome = g.ToString() + extensao; path= Path.Combine(Server.MapPath("~/Imagens/CapasFilmes"), nome); filme.Capa = nome; PictureExist = true; } } if (ModelState.IsValid) { try { db.Filmes.Add(filme); db.SaveChanges(); if (PictureExist) UploadImag.SaveAs(path); return RedirectToAction("Index"); } catch (Exception) { ModelState.AddModelError("", "Ocorreu um erro com a escrita " + "dos dados do novo Agente"); } } return View(filme); } // GET: Filmes/Edit/5 [Authorize(Roles = "Admin")] public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Filmes filme = db.Filmes.Find(id); if (filme == null) { return HttpNotFound(); } return View(filme); } // POST: Filmes/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,Titulo,Ano,Sinopse,Capa,Trailer")] Filmes filme) { if (ModelState.IsValid) { db.Entry(filme).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(filme); } // GET: Filmes/Delete/5 [Authorize(Roles = "Admin")] public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Filmes filme = db.Filmes.Find(id); if (filme == null) { return HttpNotFound(); } return View(filme); } // POST: Filmes/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Filmes filme = db.Filmes.Find(id); db.Filmes.Remove(filme); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SettingLanguage : MonoBehaviour { [SerializeField] public Toggle Rus; [SerializeField] public Toggle Eng; [SerializeField] public Toggle Dutch; [SerializeField] public GameObject TextRus; [SerializeField] public GameObject TextEng; [SerializeField] public GameObject TextDutch; public int Language = 0; //1 - русский 2 - английский 3 - нидерландский void Start () { Language = PlayerPrefs.GetInt("Language"); if (Language == 1) { Rus.isOn = true; Eng.isOn = false; } else if (Language == 2) { Rus.isOn = false; Eng.isOn = true; } } void Update () { if (Rus.isOn) { Language = 1; TextRus.SetActive(true); TextEng.SetActive(false); TextDutch.SetActive(false); } else if (Eng.isOn) { Language = 2; TextRus.SetActive(false); TextEng.SetActive(true); TextDutch.SetActive(false); } else { Language = 3; TextRus.SetActive(false); TextEng.SetActive(false); TextDutch.SetActive(true); } } public void SaveSetting() { PlayerPrefs.SetInt("Language", Language); } }
using GraphicalEditorServer.DTO; using Model.Manager; namespace GraphicalEditorServer.Mappers { public class DrugMapper { public static DrugDTO DrugToDrugDTO(Drug drug) { DrugDTO drugDTO = new DrugDTO(); drugDTO.Name = drug.Name; drugDTO.Quantity = drug.Quantity; drugDTO.ExpirationDate = drug.ExpirationDate; drugDTO.Producer = drug.Producer; drugDTO.DrugTypeDTO = DrugTypeMapper.DrugTypeTODrugTypeDTO(drug.DrugType); return drugDTO; } public static Drug DrugDTOToDrug(DrugDTO drugDTO) { return new Drug(DrugTypeMapper.DrugTypeDTOToDrugType(drugDTO.DrugTypeDTO), drugDTO.Name, drugDTO.Quantity, drugDTO.ExpirationDate, drugDTO.Producer); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GameGrabber.Models { public class Employee { public int EmployeeID { get; set; } public string EmployeeFirstName { get; set; } public string EmployeeLastName { get; set; } public DateTime DateHired { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DocumentDBRFMConsoleApp { class RfmDoc { [JsonProperty("eid")] public int Eid { get; set; } [JsonProperty("cid")] public string Cid { get; set; } [JsonProperty("uid")] public string Uid { get; set; } [JsonProperty("time")] public int Time { get; set; } [JsonProperty("src_evt")] public string SourceEvent { get; set; } [JsonProperty("cat")] public string Cat { get; set; } [JsonProperty("obj")] public string Obj { get; set; } } }
using ISE.Framework.Common.CommonBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ISE.SM.Common.DTO { public partial class UserToGroupDto:BaseDto { public UserToGroupDto() { this.PrimaryKeyName = "UgId"; } } }
using ShapesGraphics.Models.Common; namespace ShapesGraphics.Models.ConstructionArgs { public abstract class BaseConstructionArgs { public Point CenterOfMass { get; set; } } }
using System; using Terraria; using Terraria.ModLoader; using Microsoft.Xna.Framework; namespace DuckingAround.NPCs { public class DuckingAI : GlobalNPC { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleAppSpace_Objects { class Asteroide : Dinamico { int _speed; bool direzioneDestra = true; int posY, posX; string[,] _matBackground; public Asteroide(string shape, int x, int y, string[,] matSfondo, int velocita) : base (shape, x, y, matSfondo) { posY = Y; posX = X; _matBackground = matSfondo; _speed = velocita; _matBackground[x, y] = " "; } /// <summary> /// Metodo step che serve a muovere l'oggetto /// </summary> public override void Step() { if (posY < _matBackground.GetLength(1) && posY >= 0 && posX >= 0 && posX < _matBackground.GetLength(0)) { if (posY == _matBackground.GetLength(1) - 1) _speed = -_speed; else if (posY == 0) direzioneDestra = true; if (posX == _matBackground.GetLength(0) - 2) { direzioneDestra = false; _speed = -_speed; } else if (posX == 0) { direzioneDestra = true; _speed = -_speed; } Muovi(direzioneDestra); } } private void Muovi(bool direzione) { if (direzione) { _matBackground[posX+=2, posY += _speed] = base._immagine; _matBackground[posX - 2, posY - _speed] = " "; } else { _matBackground[posX-=2, posY -= _speed] = base._immagine; _matBackground[posX + 2, posY + _speed] = " "; } StampaMatrice(ref _matBackground); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrabalhoemGrupo_Armas { class Arma { string nome; string tipo; float calibre; int qtdMunicao; public int QtdMunicao { get { return qtdMunicao; } set { qtdMunicao = value; } } public float Calibre { get { return calibre; } set { calibre = value; } } public string Tipo { get { return tipo; } set { tipo = value; } } public string Nome { get { return nome; } set { nome = value; } } public Arma() { } //para não ter problema com a herança } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace TYNMU.User.Success { public partial class SuccessCaseItem : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string ID = Request.QueryString["SuccID"].ToString(); string sSql = "select * from T_success where ID='" + ID + "'"; DataSet ds = new DataSet(); ds = Data.DAO.Query(sSql); div_success.InnerHtml = ds.Tables[0].Rows[0][3].ToString(); LbName.Text = "成功案例——"+ds.Tables[0].Rows[0][2].ToString() ; LbTime.Text = "[ " + ds.Tables[0].Rows[0][4].ToString().Substring(0, ds.Tables[0].Rows[0][4].ToString().Length - 7) + " ]"; } } }
using CoinMarketCap.Helpers; using CoinMarketCap.Models; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CoinMarketCap.Api { public static class PublicApi { public static async Task<IList<TickerModel>> GetTickersAsync(string ticker = null, string currency = null, int limit = 0) { var url = $"https://api.coinmarketcap.com/v1/ticker/"; var filters = new List<string>(); if (!string.IsNullOrEmpty(currency)) { filters.Add($"convert={currency}"); } if (limit > 0) { filters.Add($"limit={limit}"); } if (!string.IsNullOrEmpty(ticker)) { url = $"{url}{ticker}/"; } if (filters.Count > 0) { url = $"{url}?{string.Join("&", filters.ToArray())}"; } string responseStr = await HttpUtilities.GetHttpResponseAsync(url); var result = JsonConvert.DeserializeObject<IEnumerable<TickerModel>>(responseStr); return result.ToList(); } public static async Task<GlobalDataModel> GetGlobalDataAsync(string currency = null) { var url = $"https://api.coinmarketcap.com/v1/global/"; var filters = new List<string>(); if (!string.IsNullOrEmpty(currency)) { url = $"{url}?convert={currency}"; } string responseStr = await HttpUtilities.GetHttpResponseAsync(url); return JsonConvert.DeserializeObject<GlobalDataModel>(responseStr); } } }
using System.Collections.Generic; using Simulator.Utils; namespace Simulator.Instructions { internal class MicroInstructionManager { internal MicroInstructionManager(IEnumerable<MicroInstruction> mi) { Instructions = new Dictionary<string, MicroInstruction>(); foreach (var microInstruction in mi) { if (Instructions.ContainsKey(microInstruction.Name)) throw new MicroInstructionNameDuplicationException(); Instructions.Add(microInstruction.Name, microInstruction); } } private Dictionary<string, MicroInstruction> Instructions { get; } internal MicroInstruction GetInstruction(string name) { if (Instructions.ContainsKey(name)) return Instructions[name]; throw new IncorrectMicroInstructionCallException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMovementController: MonoBehaviour { public GameObject player; private Vector3 startPos; // Use this for initialization void Start () { startPos = transform.position; } // Update is called once per frame void Update () { var playerPos = player.transform.position; if (Vector3.Distance (playerPos, transform.position) < 1) { transform.Translate ((playerPos - transform.position) * Time.deltaTime * .5f); } else { transform.Translate ((startPos - transform.position) * Time.deltaTime * .5f); } } }
using System; using System.Globalization; using Xamarin.Forms; namespace surfnsail.Code { public class ResourcesPathConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return BuildResourcePath(value as string); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } public static string BuildResourcePath(string value) { if (Device.OS == TargetPlatform.WinPhone) return @"Assets/" + value; else if (Device.OS == TargetPlatform.Android) return @"Resources/Drawable/" + value; else if (Device.OS == TargetPlatform.iOS) return @"Resources/" + value; throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Forms; namespace SoundServant { public class SSWindow : Window { public SSWindow() : base() { this.WindowStartupLocation = WindowStartupLocation.CenterOwner; if (SS.FullScreenMode) { this.WindowState = WindowState.Maximized; this.Topmost = true; this.WindowStyle = WindowStyle.None; this.AllowsTransparency = true; } else { this.WindowState = WindowState.Normal; this.WindowStyle = WindowStyle.SingleBorderWindow; this.Topmost = false; this.SizeToContent = SizeToContent.WidthAndHeight; this.WindowStartupLocation = WindowStartupLocation.CenterScreen; } if (Options.Default.TouchScreenMode) { this.Cursor = System.Windows.Input.Cursors.None; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShowingObjectiveTorusEvents : MonoBehaviour { public void DestroyMyself() { Destroy(transform.parent.gameObject); } }
 namespace Sfa.Poc.ResultsAndCertification.Functions.Application.Entities { public class DataResponse { public string EnvironmentName { get; set; } public string ServiceName { get; set; } public string Version { get; set; } public string Message { get; set; } public string AdditionalData { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Patterns.Pattern.Ef6; namespace Welic.Dominio.Models.Marketplaces.Entityes { public partial class StripeTransaction : Entity { public int ID { get; set; } public int OrderID { get; set; } public string ChargeID { get; set; } public string StripeToken { get; set; } public string StripeEmail { get; set; } public bool IsCaptured { get; set; } public string FailureCode { get; set; } public string FailureMessage { get; set; } public System.DateTime Created { get; set; } public System.DateTime LastUpdated { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DropDowny.Models { public class Czlowiek { public int Id { get; set; } public string Imie { get; set; } public string Nazwisko { get; set; } public Wyksztalcenie Wyksztalcenie { get; set; } //TODO: TO delte? public IEnumerable<Wyksztalcenie> Wyszktalcenies { get; set; } public Zatrudnienie Zatrudnienie { get; set; } //TODO: TO delte? public IEnumerable<Zatrudnienie> Zatrudnienies { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; using System.Windows.Forms; using Restuarnt.DAL; namespace Restuarnt.BL { class Delivery { internal void AddDeleiveryInformation(string name, string address, string phone) { DataAccessLayer da = new DataAccessLayer(); da.open(); SqlParameter[] param = new SqlParameter[3]; param[0] = new SqlParameter("@name", SqlDbType.NVarChar, 250); param[0].Value = name; param[1] = new SqlParameter("@address", SqlDbType.NVarChar, 250); param[1].Value = address; param[2] = new SqlParameter("@phone", SqlDbType.VarChar, 50); param[2].Value = phone; da.excutequery("AddDeleiveryInformation", param); da.close(); } internal DataTable SelectDeliveryInformation() { DataTable dt = new DataTable(); DataAccessLayer da = new DataAccessLayer(); da.open(); dt = da.selected("SelectDeliveryInformation", null); da.close(); return dt; } internal void DeleteDelivery(int id) { DataAccessLayer da = new DataAccessLayer(); da.open(); SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@id", SqlDbType.Int); param[0].Value = id; da.excutequery("DeleteDelivery", param); da.close(); } internal void UpdateDeleiveryInformation(string name, string address, string phone, int id) { DataAccessLayer da = new DataAccessLayer(); da.open(); SqlParameter[] param = new SqlParameter[4]; param[0] = new SqlParameter("@name", SqlDbType.NVarChar, 250); param[0].Value = name; param[1] = new SqlParameter("@address", SqlDbType.NVarChar, 250); param[1].Value = address; param[2] = new SqlParameter("@phone", SqlDbType.VarChar, 50); param[2].Value = phone; param[3] = new SqlParameter("@idDelivery", SqlDbType.Int); param[3].Value = id; da.excutequery("UpdateDeleiveryInformation", param); da.close(); } internal DataTable SelectDeliverycomp() { DataTable dt = new DataTable(); DataAccessLayer da = new DataAccessLayer(); da.open(); dt = da.selected("SelectDeliverycomp", null); da.close(); return dt; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lines { class Game { enum Status { init, //начало wait, //ожидание выбора шарика для перемещения ball_selected, //шарик выбран/отмечен (специальное отображение выбранного шарика), ожидание выбора точки назначения для выбранного шарика path_show, //отображение кратчайшего пути следования шарика к точке назначения ball_move, //процесс перемещения шарика next_balls, //отображение мест для следующих шариков line_strip, //удаление составленных линий stop, //игровое поле полностью заполнено refresh //пользователь нажал кнопку "Начать заново" } int[,] map; // Карта значений от 1 до 6, определяющая шарик какого цвета стоит в этой клетке. int[,] fmap; // Матрица нахождения пути перемещения шарика Ball[] path; // Массив шариков(вообще клеток поля) пути перемещения выбранного шарика Ball[] line; // Массив шариков для удаления при составлении линии. private int numberOfCells; // Размер поля. ShowItem show; ShowStat stat; SendInfo send; Status status; // Текущий статус игры. Ball[] balls = new Ball[3]; //Массив шариков, новых шариков, которые появляются каждый ход (если не составлена линия). Random rand = new Random(); Ball selectedBall; //Выбранный для перемещения шарик Ball destinationPlaceBall; //Место назначения, куда именно игрок хочет выбранный шарик переместить int changedBall; //Служебная переменная для определения анимации выбранного шарика(0 - большой, 1 - обычный средний) public Game(int numberOfCells, ShowItem show, ShowStat stat, SendInfo send) { this.numberOfCells = numberOfCells; this.show = show; this.stat = stat; this.send = send; map = new int[numberOfCells, numberOfCells]; fmap = new int[numberOfCells, numberOfCells]; path = new Ball[numberOfCells * numberOfCells]; line = new Ball[99]; status = Status.init; } private void InitMap() //Метод очищает поле игры. { Ball none; none.color = 0; for (int x = 0; x < numberOfCells; x++) { for (int y = 0; y < numberOfCells; y++) { map[x, y] = 0; none.x = x; none.y = y; show(none, Item.none); } } } public void Step() // Основная функция программы. Следит за этапами работы программы. { switch (status) { case Status.init: InitMap(); SelectNextBalls(); ShowNextBalls(); SelectNextBalls(); status = Status.wait; break; case Status.wait: break; case Status.ball_selected: BallSelected(); break; case Status.path_show: ShowPath(); break; case Status.ball_move: MoveBall(); break; case Status.next_balls: ShowNextBalls(); SelectNextBalls(); break; case Status.line_strip: DeleteReadyLines(); break; case Status.stop: send(true); status = Status.init; break; case Status.refresh: status = Status.init; break; default: break; } } public void ClickBox(int x, int y) //Метод срабатывает при клики на какой-либо ячейке игрового поля { if (status == Status.wait || status == Status.ball_selected) { if (map[x, y] > 0) { if (status == Status.ball_selected) { show(selectedBall, Item.aver); } selectedBall.x = x; selectedBall.y = y; selectedBall.color = map[x, y]; status = Status.ball_selected; } } if (status == Status.ball_selected) { if (map[x, y] <= 0) { destinationPlaceBall.x = x; destinationPlaceBall.y = y; destinationPlaceBall.color = selectedBall.color; if (FindPath()) { status = Status.path_show; } return; } } /*if (status == Status.stop) { status = Status.init; }*/ } private void ShowHiddenBalls() { for (int i = 0; i < 3; i++) { ShowHiddenBall(balls[i]); } } private void ShowHiddenBall(Ball next) { if (next.x < 0) { return; } show(next, Item.small); } private void SelectNextBalls() //Выбирает места появления будущих шариков. Отображает маленькие шарики. { for (int i = 0; i < balls.Length; i++) { balls[i] = SelectOneBall(); } } private Ball SelectOneBall() { return SelectOneBall(rand.Next(1, 7)); } private Ball SelectOneBall(int color) //Выбирает место появления будущего шарика { Ball nextBall; nextBall.color = color; int loop = 100; do { nextBall.x = rand.Next(0, numberOfCells); nextBall.y = rand.Next(0, numberOfCells); if (--loop < 0) { nextBall.x = -1; return nextBall; } } while (map[nextBall.x, nextBall.y] != 0); map[nextBall.x, nextBall.y] = -1; show(nextBall, Item.small); return nextBall; } private void ShowNextBalls() //Отображает обычные, средние шарики. { for (int i = 0; i < balls.Length; i++) { ShowOneBall(balls[i]); } if (FindReadyLines()) { status = Status.line_strip; } else { if (IsMapFull()) { status = Status.stop; } else { status = Status.wait; } } } private void ShowOneBall(Ball ball) //Отображает 1 средний шарик. { if (ball.x < 0) { return; } if (map[ball.x, ball.y] > 0) { ball = SelectOneBall(ball.color); if (ball.x < 0) { return; } } map[ball.x, ball.y] = ball.color; show(ball, Item.aver); } private void BallSelected() //Отображает анимацию выбранного шарика (изменение размера шарика со среднего на большого) { if (changedBall == 0) { show(selectedBall, Item.big); } else { show(selectedBall, Item.aver); } changedBall = 1 - changedBall; } int pathLenght; //Длина найденного пути перемещения шарика private bool FindPath() //Ищет путь для перемещение шарика { if (!(map[selectedBall.x, selectedBall.y] > 0 && map[destinationPlaceBall.x, destinationPlaceBall.y] <= 0)) { return false; } for (int x = 0; x < numberOfCells; x++) { for (int y = 0; y < numberOfCells; y++) { fmap[x, y] = 0; } } bool added; bool found = false; fmap[selectedBall.x, selectedBall.y] = 1; int numberOfMove = 1; do { added = false; for (int x = 0; x < numberOfCells; x++) { for (int y = 0; y < numberOfCells; y++) { if (fmap[x, y] == numberOfMove) { MarkPath(x + 1, y, numberOfMove + 1); MarkPath(x - 1, y, numberOfMove + 1); MarkPath(x, y + 1, numberOfMove + 1); MarkPath(x, y - 1, numberOfMove + 1); added = true; } } } if (fmap[destinationPlaceBall.x, destinationPlaceBall.y] > 0) { found = true; break; } numberOfMove++; } while (added); if (!found) { return false; } int pathX = destinationPlaceBall.x; int pathY = destinationPlaceBall.y; pathLenght = numberOfMove; while (numberOfMove >= 0) { path[numberOfMove].x = pathX; path[numberOfMove].y = pathY; if (IsPathDesired(pathX + 1, pathY, numberOfMove)) //Здесь может быть ошибка - может (numberOfMove - 1) { pathX++; } if (IsPathDesired(pathX - 1, pathY, numberOfMove)) //Здесь может быть ошибка - может (numberOfMove - 1) { pathX--; } if (IsPathDesired(pathX, pathY + 1, numberOfMove)) //Здесь может быть ошибка - может (numberOfMove - 1) { pathY++; } if (IsPathDesired(pathX, pathY - 1, numberOfMove)) //Здесь может быть ошибка - может (numberOfMove - 1) { pathY--; } numberOfMove--; } stepShowPath = 0; return true; } private void MarkPath(int x, int y, int nOM) //Служебный метод для метода FinfPath() { if (x < 0 || x >= numberOfCells || y < 0 || y >= numberOfCells) { return; } if (map[x, y] > 0) { return; } if (fmap[x, y] > 0) { return; } fmap[x, y] = nOM; } private bool IsPathDesired(int x, int y, int nOM) //Служебный метод для метода FinfPath() { if (x < 0 || x >= numberOfCells || y < 0 || y >= numberOfCells) { return false; } return fmap[x, y] == nOM; } int stepShowPath; //Этап отображение найденного пути для перемещения шарика private void ShowPath()//Отображает найденный путь для перемещения шарика. { if (stepShowPath == 0) { for (int i = 1; i <= pathLenght; i++) { show(path[i], Item.path); } stepShowPath++; return; } Ball movingBall; movingBall = path[stepShowPath - 1]; show(movingBall, Item.none); movingBall = path[stepShowPath]; movingBall.color = selectedBall.color; show(movingBall, Item.aver); stepShowPath++; if (stepShowPath > pathLenght) { ShowHiddenBalls(); status = Status.ball_move; } } private void MoveBall() //Перемещает выбранный шарик к выбранному пустому месту { if (status != Status.ball_move) { return; } if (map[selectedBall.x, selectedBall.y] > 0 && map[destinationPlaceBall.x, destinationPlaceBall.y] <= 0) { map[selectedBall.x, selectedBall.y] = 0; map[destinationPlaceBall.x, destinationPlaceBall.y] = selectedBall.color; show(selectedBall, Item.none); show(destinationPlaceBall, Item.aver); if (FindReadyLines()) { status = Status.line_strip; } else { status = Status.next_balls; } } } int lines; //Длина линии из шариков - сколько шариков составляют линию int lineStep; //Определяет этап анимации процесса удаления шарика private bool FindReadyLines() //Проверяет составление линий из 5-ти больше шариков одного цвета { lines = 0; for (int x = 0; x < numberOfCells; x++) { for (int y = 0; y < numberOfCells; y++) { CheckLine(x, y, 1, 0); CheckLine(x, y, 1, 1); CheckLine(x, y, 0, 1); CheckLine(x, y, -1, 1); } } if (lines == 0) { return false; } lineStep = 4; return true; } private void CheckLine(int x, int y, int sx, int sy) //Служебный метод для метода FindReadyLines() { int lenght = 4; if (x < 0 || x >= numberOfCells || y < 0 || y >= numberOfCells) { return; } if (x + lenght * sx < 0 || x + lenght * sx >= numberOfCells || y + lenght * sy < 0 || y + lenght * sy >= numberOfCells) { return; } int color = map[x, y]; if (color <= 0) { return; } for (int i = 1; i <= lenght; i++) { if (map[x + i * sx, y + i * sy] != color) { return; } } Ball checkingBall; for (int i = 0; i <= lenght; i++) { checkingBall.x = x + i * sx; checkingBall.y = y + i * sy; checkingBall.color = color; if (!(line.Contains(checkingBall))) { line[lines] = checkingBall; lines++; } /*line[lines].x = x + i * sx; line[lines].y = y + i * sy; line[lines].color = color; lines++;*/ } } private void DeleteReadyLines() //Производит анимацию удаления линии шариков { if (lineStep <= 0) { for (int i = 0; i < lines; i++) { map[line[i].x, line[i].y] = 0; ShowHiddenBalls(); } stat(lines); status = Status.wait; return; } lineStep--; for (int i = 0; i < lines; i++) { switch (lineStep) { case 3: show(line[i], Item.big); break; case 2: show(line[i], Item.aver); break; case 1: show(line[i], Item.small); break; case 0: show(line[i], Item.none); break; default: break; } } } private bool IsMapFull() //Метод проверяет заполненность поля. { for (int x = 0; x < numberOfCells; x++) { for (int y = 0; y < numberOfCells; y++) { if (map[x, y] <= 0) { return false; } } } return true; } public void ClickRefresh() { status = Status.refresh; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace BattleShots { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Game : ContentPage { BluetoothMag bluetooth; GameSettings settings; public Game(BluetoothMag bluetooth, GameSettings gameSettings) { InitializeComponent(); BGStuff.game = this; BGStuff.InGame = true; Labels.Add(txtNumOfShots); Labels.Add(txtStatus); imageShotGlass.Source = FileManager.SRCShotGlass; ApplyTheme(); this.bluetooth = bluetooth; this.settings = gameSettings; settings.YourTurn = false; settings.EnemyShots = settings.NumOfShots; txtNumOfShots.Text = settings.NumOfShots.ToString(); GameGrid grid = new GameGrid(this, MainStack, SecStack, settings); // check for who goes first if(settings.Master) { Random random = new Random(); int ranNum = random.Next(0, 1); if(ranNum == 1) { bluetooth.SendMessage(ranNum.ToString()); txtStatus.Text = settings.EnemyName + "'s Goes First"; } else { settings.YourTurn = true; bluetooth.SendMessage(ranNum.ToString()); txtStatus.Text = "You Go First"; } } } ImageButton btn; public void GridButton_Clicked(object sender, EventArgs e) { if (settings.YourTurn) { btn = (ImageButton)sender; settings.YourTurn = false; ToastManager.Show(btn.ClassId); settings.AllReadySelected.Add(btn.ClassId); bluetooth.SendMessage(btn.ClassId); } else { ToastManager.Show("Not Your Turn"); Task.Run(async () => { uint timeout = 50; await MainStack.TranslateTo(-15, 0, timeout); await MainStack.TranslateTo(15, 0, timeout); await MainStack.TranslateTo(-9, 0, timeout); await MainStack.TranslateTo(9, 0, timeout); await MainStack.TranslateTo(-5, 0, timeout); await MainStack.TranslateTo(5, 0, timeout); await MainStack.TranslateTo(-2, 0, timeout); await MainStack.TranslateTo(2, 0, timeout); MainStack.TranslationX = 0; }); } } public void ReceiveCheck(string coordenates) { string[] split = coordenates.Split(','); if (settings.YourShotCoodinates.Contains(coordenates)) { settings.YourGrid[int.Parse(split[0]), int.Parse(split[1])].Source = FileManager.SRCGridButtonShotGlassCross; settings.YourShotCoodinates.Remove(coordenates); settings.NumOfShots -= 1; txtNumOfShots.Text = settings.NumOfShots.ToString(); bluetooth.SendMessage("hit"); ToastManager.Show("Drink Up!"); } else { bluetooth.SendMessage("miss"); } } public void ReceiveHit(bool value) { if (value) { btn.Source = FileManager.SRCGridButtonShotGlassCross; settings.EnemyShots -= 1; if (settings.EnemyShots == 0) { ToastManager.Show("You Win"); bluetooth.SendMessage("endgame"); EndGame(true); } else { ToastManager.Show("Hit!"); bluetooth.SendMessage("ready"); txtStatus.Text = settings.EnemyName + "'s Turn"; } } else { btn.Source = FileManager.SRCGridButtonCross; ToastManager.Show("Miss!"); bluetooth.SendMessage("ready"); txtStatus.Text = settings.EnemyName + "'s Turn"; } } public void Ready() { settings.YourTurn = true; txtStatus.Text = "Your Turn"; } public void EndGame(bool value) { if (!value) { ToastManager.Show("You Lose! Drink The Rest Of Your Shots!"); } Button btn = new Button { Text = "Exit Game", TextColor = Theme.ButtonTextColour, BackgroundColor = Theme.ButtonBgColour, BorderColor = Theme.ButtonBorderColour }; btn.Clicked += EndGame_Clicked; PageStack.Children.Add(btn); } public void EndGame_Clicked(object sender, EventArgs e) { Navigation.PopToRootAsync(); } public void GoesFirst(int value) { if (value == 1) { txtStatus.Text = "You Go First"; } else { txtStatus.Text = settings.EnemyName + "'s Goes First"; } } #region OnBack protected override bool OnBackButtonPressed() { Back(); return true; } private async void Back() { var result = await DisplayAlert("Alert!", "Are You Sure You Want To Exit Game?", "Yes", "No"); if (result) { Application.Current.Quit(); } } #endregion #region Theme Stuff public List<Button> Buttons = new List<Button>(); public List<Label> Labels = new List<Label>(); public List<Entry> Entries = new List<Entry>(); public List<Picker> Pickers = new List<Picker>(); public void ApplyTheme() { this.BackgroundColor = Theme.BgColour; if (Labels.Count > 0) { for (int i = 0; i < Labels.Count; i++) { Labels[i].TextColor = Theme.LabelTextColour; } } if (Buttons.Count > 0) { for (int i = 0; i < Buttons.Count; i++) { Buttons[i].TextColor = Theme.ButtonTextColour; Buttons[i].BackgroundColor = Theme.ButtonBgColour; Buttons[i].BorderColor = Theme.ButtonBorderColour; } } if (Entries.Count > 0) { for (int i = 0; i < Entries.Count; i++) { Entries[i].TextColor = Theme.EntryTextColour; Entries[i].PlaceholderColor = Theme.EntryPlaceholderColour; } } if (Pickers.Count > 0) { for (int i = 0; i < Pickers.Count; i++) { Pickers[i].TextColor = Theme.PickerTextColour; Pickers[i].TitleColor = Theme.PickerTitleColour; Pickers[i].BackgroundColor = Theme.PickerBgColour; } } } #endregion public void Reconnect() { Navigation.PushAsync(new ReconnectionPage(bluetooth)); } } }
using Microsoft.AspNetCore.Mvc; using userService.Model; using userService.Repository; using System; using System.Transactions; using Microsoft.Extensions.Configuration; using userService.Service; namespace userService.Controllers { [Route("perime-user-ms/[controller]")] [ApiController] public class SessionwController : ControllerBase { private readonly IUserRepository _userRepository; private readonly ISessionwRepository _sessionRepository; private IConfiguration _config; public SessionwController (IUserRepository userRepository, ISessionwRepository sessionwRepository, IConfiguration config) { _userRepository = userRepository; _sessionRepository = sessionwRepository; _config = config; } [HttpGet] public IActionResult Get() { try { var sessions = _sessionRepository.GetSessions(); return new OkObjectResult(sessions); } catch(Exception) { return new StatusCodeResult(500); } } [HttpPost] public IActionResult Post([FromBody] Login login) { try { var userGot =_userRepository.GetUserByEmail(login.email); if (userGot != null) { if (_userRepository.CheckMatch(userGot.passhash_user, login.password) && _userRepository.CheckLDAP(login.email, login.password)) { var jwt = new JwtService(_config); var token = jwt.GenerateSecurityToken(userGot); Sessionw newSession = new Sessionw(); newSession.id_session = userGot.id_user; newSession.token_session = token; using (var scope = new TransactionScope()) { var alreadySession = _sessionRepository.GetSessionById(userGot.id_user); if (alreadySession != null) { _sessionRepository.DeleteSession(userGot.id_user); } _sessionRepository.InsertSession(newSession); scope.Complete(); } return new OkObjectResult(newSession); } else { return new NotFoundResult(); } } else { return new NotFoundResult(); } } catch(Exception) { return new StatusCodeResult(500); } } [HttpDelete("{id}")] public IActionResult Delete(int id) { try { var sessionDeleted = _sessionRepository.GetSessionById(id); if (sessionDeleted != null) { _sessionRepository.DeleteSession(id); return new OkObjectResult(sessionDeleted); } else { return new BadRequestResult(); } } catch(Exception) { return new StatusCodeResult(500); } } } }
using AppStore.Application.Services.Apps; using AppStore.Application.Services.Authentication; using AppStore.Application.Services.Payment; using AppStore.Application.Services.Users; using AppStore.Domain.Apps; using AppStore.Domain.Common; using AppStore.Domain.Notifications; using AppStore.Domain.Orders; using AppStore.Domain.Users; using AppStore.Infra.CrossCutting.Notification; using AppStore.Infra.CrossCutting.Notifications; using AppStore.Infra.Data.Integration; using AppStore.Infra.Data.Persistence.EF.Contexts; using AppStore.Infra.Data.Persistence.Repositories; using AppStore.Streaming.Producer; using SimpleInjector; using System.Data.Entity; namespace AppStore.Infra.IoC { public class DependencyConfig { public static void InitializeContainer(Container container) { // Repositories container.Register<DbContext, AppStoreContext>(Lifestyle.Scoped); container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped); container.Register<IUserRepository, UserRepository>(Lifestyle.Scoped); container.Register<IAuthenticationService, AuthenticationService>(Lifestyle.Scoped); container.Register<IAppRepository, AppRepository>(Lifestyle.Scoped); container.Register<IOrderRepository, OrderRepository>(Lifestyle.Scoped); // Domain Services container.Register<IMessageService, MailService>(Lifestyle.Scoped); container.Register<INotificationService, NotificationService>(Lifestyle.Scoped); container.Register<IPaymentService, PaymentProvider>(Lifestyle.Scoped); // Application Services container.Register<IAuthenticationAppService, AuthenticationAppService>(Lifestyle.Scoped); container.Register<IUserAppService, UserAppService>(Lifestyle.Scoped); container.Register<IAppAppService, AppAppService>(Lifestyle.Scoped); container.Register<IOrderAppService, OrderAppService>(Lifestyle.Scoped); container.Register<IPaymentAppService, PaymentAppService>(Lifestyle.Scoped); // Streaming container.Register<IPaymentProducer, PaymentProducer>(Lifestyle.Singleton); } } }
using Genesys.WebServicesClient.Resources; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; namespace Genesys.WebServicesClient.Components { public class GenesysCall : GenesysInteraction { public GenesysCall(GenesysInteractionManager interactionManager, CallResource callResource) : base(interactionManager, callResource) { } public override bool Finished { get { return State == "Released"; } } void DoCallOperation(object parameters) { interactionManager.User.Connection.InternalClient.CreateRequest("POST", "/api/v2/me/calls/" + Id, parameters).SendAsync(); } void DoCallOperation(string operationName) { DoCallOperation(new { operationName = operationName }); } protected override string[] GetCapabilityNames() { return new[] { "Answer", "Hangup", "InitiateTransfer", "CompleteTransfer", "AttachUserData", "UpdateUserData", }; } public void Answer() { DoCallOperation("Answer"); } public bool AnswerCapable { get; private set; } public void Hangup() { DoCallOperation("Hangup"); } public bool HangupCapable { get; private set; } public void InitiateTransfer(string phoneNumber) { DoCallOperation(new { operationName = "InitiateTransfer", destination = new { phoneNumber = phoneNumber } }); } public bool InitiateTransferCapable { get; private set; } public void CompleteTransfer() { DoCallOperation("CompleteTransfer"); } public bool CompleteTransferCapable { get; private set; } public void AttachUserData(object obj) { DoCallOperation(new { operationName = "AttachUserData", userData = obj }); } public bool AttachUserDataCapable { get; private set; } public void UpdateUserData(object obj) { DoCallOperation(new { operationName = "UpdateUserData", userData = obj }); } public bool UpdateUserDataCapable { get; private set; } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. namespace FiiiCoin.DTO { public class UnspentOM { /// <summary> /// The TXID of the transaction containing the output, encoded as hex in RPC byte order /// </summary> public string TXID { get; set; } /// <summary> /// The output index number (vout) of the output within its containing transaction /// </summary> public long Vout { get; set; } /// <summary> /// The P2PKH or P2SH address the output paid. Only returned for P2PKH or P2SH output scripts /// </summary> public string Address { get; set; } /// <summary> /// If the address returned belongs to an account, this is the account. Otherwise not returned /// </summary> public string Account { get; set; } /// <summary> /// The output script paid, encoded as hex /// </summary> public string ScriptPubKey { get; set; } /// <summary> /// If the output is a P2SH whose script belongs to this wallet, this is the redeem script /// </summary> public string RedeemScript { get; set; } /// <summary> /// The amount paid to the output in fiiicoins /// </summary> public long Amount { get; set; } /// <summary> /// The number of confirmations received for the transaction containing this output /// </summary> public long Confirmations { get; set; } /// <summary> /// Set to true if the private key or keys needed to spend this output are part of the wallet. /// Set to false if not (such as for watch-only addresses) /// </summary> public bool Spendable { get; set; } /// <summary> /// Set to true if the wallet knows how to spend this output. /// Set to false if the wallet does not know how to spend the output. /// It is ignored if the private keysare available /// </summary> public bool Solvable { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using SbdProjekto.Models; namespace SbdProjekto.Controllers { public class PrzesylkaController : Controller { private readonly ApplicationDbContext _context; public PrzesylkaController(ApplicationDbContext context) { _context = context; } // GET: Przesylka public async Task<IActionResult> Index() { var applicationDbContext = _context.Przesylki.Include(p => p.Magazyn).Include(p => p.RodzajPrzesylki).Include(p => p.Zamowienie); return View(await applicationDbContext.ToListAsync()); } // GET: Przesylka/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var przesylka = await _context.Przesylki .Include(p => p.Magazyn) .Include(p => p.RodzajPrzesylki) .Include(p => p.Zamowienie) .FirstOrDefaultAsync(m => m.PrzesylkaId == id); if (przesylka == null) { return NotFound(); } return View(przesylka); } // GET: Przesylka/Create public IActionResult Create() { IEnumerable<SelectListItem> magazyny = _context.Magazyny.Select(x => new SelectListItem { Value = x.MagazynId.ToString(), Text = x.Nazwa }); IEnumerable<SelectListItem> rodzajePrzesylek = _context.RodzajePrzesylek.Select(x => new SelectListItem { Value = x.RodzajPrzesylkiId.ToString(), Text = x.Typ }); ViewData["MagazynId"] = new SelectList(magazyny, "Value", "Text"); ViewData["RodzajPrzesylkiId"] = new SelectList(rodzajePrzesylek, "Value", "Text"); ViewData["ZamowienieId"] = new SelectList(_context.Zamowienia, "ZamowienieId", "ZamowienieId"); return View(); } // POST: Przesylka/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("PrzesylkaId,Waga,Szerokosc,Wysokosc,Dlugosc,MagazynId,RodzajPrzesylkiId,ZamowienieId")] Przesylka przesylka) { if (ModelState.IsValid) { _context.Add(przesylka); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } IEnumerable<SelectListItem> magazyny = _context.Magazyny.Select(x => new SelectListItem { Value = x.MagazynId.ToString(), Text = x.Nazwa }); IEnumerable<SelectListItem> rodzajePrzesylek = _context.RodzajePrzesylek.Select(x => new SelectListItem { Value = x.RodzajPrzesylkiId.ToString(), Text = x.Typ }); ViewData["MagazynId"] = new SelectList(magazyny, "Value", "Text"); ViewData["RodzajPrzesylkiId"] = new SelectList(rodzajePrzesylek, "Value", "Text"); ViewData["ZamowienieId"] = new SelectList(_context.Zamowienia, "ZamowienieId", "ZamowienieId", przesylka.ZamowienieId); return View(przesylka); } // GET: Przesylka/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var przesylka = await _context.Przesylki.FindAsync(id); if (przesylka == null) { return NotFound(); } IEnumerable<SelectListItem> magazyny = _context.Magazyny.Select(x => new SelectListItem { Value = x.MagazynId.ToString(), Text = x.Nazwa }); IEnumerable<SelectListItem> rodzajePrzesylek = _context.RodzajePrzesylek.Select(x => new SelectListItem { Value = x.RodzajPrzesylkiId.ToString(), Text = x.Typ }); ViewData["MagazynId"] = new SelectList(magazyny, "Value", "Text"); ViewData["RodzajPrzesylkiId"] = new SelectList(rodzajePrzesylek, "Value", "Text"); ViewData["ZamowienieId"] = new SelectList(_context.Zamowienia, "ZamowienieId", "ZamowienieId", przesylka.ZamowienieId); return View(przesylka); } // POST: Przesylka/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("PrzesylkaId,Waga,Szerokosc,Wysokosc,Dlugosc,MagazynId,RodzajPrzesylkiId,ZamowienieId")] Przesylka przesylka) { if (id != przesylka.PrzesylkaId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(przesylka); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PrzesylkaExists(przesylka.PrzesylkaId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } IEnumerable<SelectListItem> magazyny = _context.Magazyny.Select(x => new SelectListItem { Value = x.MagazynId.ToString(), Text = x.Nazwa }); IEnumerable<SelectListItem> rodzajePrzesylek = _context.RodzajePrzesylek.Select(x => new SelectListItem { Value = x.RodzajPrzesylkiId.ToString(), Text = x.Typ }); ViewData["MagazynId"] = new SelectList(magazyny, "Value", "Text"); ViewData["RodzajPrzesylkiId"] = new SelectList(rodzajePrzesylek, "Value", "Text"); ViewData["ZamowienieId"] = new SelectList(_context.Zamowienia, "ZamowienieId", "ZamowienieId", przesylka.ZamowienieId); return View(przesylka); } // GET: Przesylka/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var przesylka = await _context.Przesylki .Include(p => p.Magazyn) .Include(p => p.RodzajPrzesylki) .Include(p => p.Zamowienie) .FirstOrDefaultAsync(m => m.PrzesylkaId == id); if (przesylka == null) { return NotFound(); } return View(przesylka); } // POST: Przesylka/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var przesylka = await _context.Przesylki.FindAsync(id); _context.Przesylki.Remove(przesylka); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool PrzesylkaExists(int id) { return _context.Przesylki.Any(e => e.PrzesylkaId == id); } } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Framework.Core.Enums.Enum { /// <summary> /// 银行类型 /// </summary> [ClassProperty(Name = "银行类型")] public enum BankType { /// <summary> /// 中国银行 /// </summary> [Display(Name = "中国银行")] [LabelCssClass(BadgeColorCalss.Danger)] BankOfChina = 1, /// <summary> /// 工商银行 /// </summary> [Display(Name = "工商银行")] [LabelCssClass(BadgeColorCalss.Danger)] Icbc = 2, /// <summary> /// 农业银行 /// </summary> [Display(Name = "农业银行")] [LabelCssClass(BadgeColorCalss.Danger)] AgriculturalBank = 3, /// <summary> /// 建设银行 /// </summary> [Display(Name = "建设银行")] [LabelCssClass(BadgeColorCalss.Danger)] Ccb = 4, /// <summary> /// 交通银行 /// </summary> [Display(Name = "交通银行")] [LabelCssClass(BadgeColorCalss.Danger)] BankOfCommunications = 5, /// <summary> /// 招商银行 /// </summary> [Display(Name = "民生银行")] [LabelCssClass(BadgeColorCalss.Danger)] Cmbc = 6, /// <summary> /// 其他银行 /// </summary> [Display(Name = "其他银行")] [LabelCssClass(BadgeColorCalss.Danger)] OtherBank = 999 } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using WebsiteQuanLyPhatHanhSach.Models; namespace WebsiteQuanLyPhatHanhSach.Areas.Agency.Models { public class OrderVM { public int AgencyID { get; set; } public int AdminID { get; set; } public System.DateTime Date { get; set; } public int Status { get; set; } public decimal Total { get; set; } public List<OrderDetail> Details { get; set; } } }
using DependencyInjection; using Microsoft.Extensions.DependencyInjection; namespace MyPlugin1 { public class PluginConfiguration : IPluginFactory { public void Configure(IServiceCollection services) { services.AddSingleton<IFruitProducer, MyFruitProducer>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BSMU_Schedule.Common.ActionResults { public class ActionResult { public IList<ActionError> Errors { get; set; } public bool Succeeded => Errors == null || !Errors.Any(); public void AddError(ActionError actionError) { if (Errors == null) { Errors = new List<ActionError>(); } Errors.Add(actionError); } } }
using Abp.MultiTenancy; using Dg.fifth.Authorization.Users; namespace Dg.fifth.MultiTenancy { public class Tenant : AbpTenant<User> { public Tenant() { } public Tenant(string tenancyName, string name) : base(tenancyName, name) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Jogging.Model.Models { public class Temperature { public int Id { get; set; } public float Temp { get; set; } public DateTime Date { get; set; } public Session Session { get; set; } public Temperature() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using IRAP.OPC.Entity; using IRAP.Interface.OPC; using IRAP.OPC.Library; using IRAP.BL.OPCGateway.Global; using IRAP.BL.OPCGateway.Global.Entities; namespace IRAP.BL.OPCGateway.Actions { internal class TGetDeviceTags : Interfaces.IWebAPIAction { private TGetDeviceTagsContent content = new TGetDeviceTagsContent(); public TGetDeviceTags(string xmlContent) { try { content.ResolveRequest(xmlContent); } catch (Exception error) { foreach (DictionaryEntry de in error.Data) { if (de.Key.ToString().ToUpper() == "ERRCODE") content.Response.ErrCode = de.Value.ToString(); if (de.Key.ToString().ToUpper() == "ERRTEXT") content.Response.ErrText = de.Value.ToString(); } } } public string DoAction() { if (!string.IsNullOrEmpty(content.Response.ErrCode) && content.Response.ErrCode != "0") { return content.GenerateResponseContent(); } if (content.Request != null) { content.Response.ErrCode = "999999"; content.Response.ErrText = "功能正在开发中......"; try { if (content.Request.ExCode == "GetDeviceTags") { TKepwareServer server = TKepwareServers.Instance.Servers.ByAddress( content.Request.KepServAddr); if (server != null) { TKepwareDevice device = server.Devices.Get( content.Request.KepServChannel, content.Request.KepServDevice); if (device != null) { content.Response.KepServAddr = server.Address; content.Response.KepServName = server.Name; content.Response.KepServChannel = device.KepServChannel; content.Response.KepServDevice = device.KepServDevice; for (int i = 0; i < device.Tags.Count; i++) { content.Response.Details.Add( new TGetDeviceTagsRspDetail() { Ordinal = i + 1, TagName = device.Tags[i].TagName, }); } content.Response.ErrCode = "0"; content.Response.ErrText = "设备标签清单获取完成"; } else { content.Response.ErrCode = "903321"; content.Response.ErrText = $"DeviceName[{content.Request.KepServChannel}." + $"{content.Request.KepServDevice}]不存在"; } } else { content.Response.ErrCode = "900103"; content.Response.ErrText = $"KepServer[{content.Request.KepServName}" + $"({content.Request.KepServAddr})]连接失败"; } } else { content.Response.ErrCode = "900000"; content.Response.ErrText = "报文体中的交易代码和报文头中的交易代码不一致"; } } catch (Exception error) { content.Response.ErrText = string.Format("系统抛出的错误:[{0}]", error.Message); foreach (DictionaryEntry de in error.Data) { if (de.Key.ToString().ToUpper() == "ERRCODE") content.Response.ErrCode = de.Value.ToString(); if (de.Key.ToString().ToUpper() == "ERRTEXT") content.Response.ErrText = de.Value.ToString(); } } } return content.GenerateResponseContent(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FakePlayerMove : MonoBehaviour { public float Initspeed = 2; public float PushConstant = 0; // Start is called before the first frame update void Start() { this.gameObject.GetComponent<Rigidbody>().AddForce(Initspeed, 0, 0); } // Update is called once per frame void Update() { this.gameObject.GetComponent<Rigidbody>().AddForce(PushConstant, 0, 0); //this.gameObject.transform.Translate(speed*Time.fixedDeltaTime, 0, 0); } }
using SelectionCommittee.BLL.Interfaces; using SelectionCommittee.DAL.Interfaces; using SelectionCommittee.DAL.Repositories; namespace SelectionCommittee.BLL.Services { public class ServiceCreator : IServiceCreator { private IUnitOfWork _database; public ServiceCreator(string strConnection) { _database = new UnitOfWork(strConnection); } public ICityService CreateCityService() { return new CityService(_database); } public IEducationalInstitutionService CreateEducationalInstitutionService() { return new EducationalInstitutionService(_database); } public IEnrolleeService CreateEnrolleService() { return new EnrolleeService(_database); } public IRegionService CreateRegionService() { return new RegionService(_database); } public ISubjectService CreateSubjectService() { return new SubjectService(_database); } public IFacultyService CreateFacultyService() { return new FacultyService(_database); } public ISpecialtyService CreateSpecialtyService() { return new SpecialtyService(_database); } public IStatementService CreateStatementService() { return new StatementService(_database); } public IMarkSubjectService CreateMarkSubjectService() { return new MarkSubjectService(_database); } } }
using System; namespace AspNetAngular.Model { public partial class Branches { public string Code { get; set; } public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; namespace Storyblok.Sdk.Content.Types { public class Image { [JsonProperty(PropertyName = "name")] public string NameOrDescription { get; set; } public Uri FileName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnalizaDanychApka { class Class1 { } } // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0. /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public partial class root { private rootREUTERS[] rEUTERSField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("REUTERS")] public rootREUTERS[] REUTERS { get { return this.rEUTERSField; } set { this.rEUTERSField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class rootREUTERS { private string dATEField; private string mKNOTEField; private string[] tOPICSField; private string[] pLACESField; private string[] pEOPLEField; private string[] oRGSField; private string[] eXCHANGESField; private object cOMPANIESField; private string uNKNOWNField; private rootREUTERSTEXT tEXTField; private string tOPICS1Field; private string lEWISSPLITField; private string cGISPLITField; private ushort oLDIDField; private ushort nEWIDField; private uint cSECSField; private bool cSECSFieldSpecified; /// <remarks/> public string DATE { get { return this.dATEField; } set { this.dATEField = value; } } /// <remarks/> public string MKNOTE { get { return this.mKNOTEField; } set { this.mKNOTEField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("D", IsNullable = false)] public string[] TOPICS { get { return this.tOPICSField; } set { this.tOPICSField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("D", IsNullable = false)] public string[] PLACES { get { return this.pLACESField; } set { this.pLACESField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("D", IsNullable = false)] public string[] PEOPLE { get { return this.pEOPLEField; } set { this.pEOPLEField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("D", IsNullable = false)] public string[] ORGS { get { return this.oRGSField; } set { this.oRGSField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("D", IsNullable = false)] public string[] EXCHANGES { get { return this.eXCHANGESField; } set { this.eXCHANGESField = value; } } /// <remarks/> public object COMPANIES { get { return this.cOMPANIESField; } set { this.cOMPANIESField = value; } } /// <remarks/> public string UNKNOWN { get { return this.uNKNOWNField; } set { this.uNKNOWNField = value; } } /// <remarks/> public rootREUTERSTEXT TEXT { get { return this.tEXTField; } set { this.tEXTField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("TOPICS")] public string TOPICS1 { get { return this.tOPICS1Field; } set { this.tOPICS1Field = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string LEWISSPLIT { get { return this.lEWISSPLITField; } set { this.lEWISSPLITField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string CGISPLIT { get { return this.cGISPLITField; } set { this.cGISPLITField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public ushort OLDID { get { return this.oLDIDField; } set { this.oLDIDField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public ushort NEWID { get { return this.nEWIDField; } set { this.nEWIDField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public uint CSECS { get { return this.cSECSField; } set { this.cSECSField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool CSECSSpecified { get { return this.cSECSFieldSpecified; } set { this.cSECSFieldSpecified = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class rootREUTERSTEXT { private string tITLEField; private string aUTHORField; private string dATELINEField; private string bODYField; private string[] textField; private string tYPEField; /// <remarks/> public string TITLE { get { return this.tITLEField; } set { this.tITLEField = value; } } /// <remarks/> public string AUTHOR { get { return this.aUTHORField; } set { this.aUTHORField = value; } } /// <remarks/> public string DATELINE { get { return this.dATELINEField; } set { this.dATELINEField = value; } } /// <remarks/> public string BODY { get { return this.bODYField; } set { this.bODYField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string[] Text { get { return this.textField; } set { this.textField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string TYPE { get { return this.tYPEField; } set { this.tYPEField = value; } } }
using UnityEngine; using System.Collections; public class WallTest : MonoBehaviour { public float speed = 20; public GameObject Player; public Rigidbody PlayerRB; void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Ground") { Debug.Log("trump"); PlayerRB.AddForce(Vector3.right * speed); } } }
using System.Web.Mvc; using Model; namespace BelerofontePortfolio.Controllers { public class HomeController : Controller { // localhost8086/home public ActionResult Index() { // ViewBag.Alumnos = Alumno.Listar(); return View(); } public ActionResult Ver() { return View(Alumno.Obtener()); } public ActionResult Guardar(Alumno a, int[] algo) { return Redirect("~/home/index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.IO; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; namespace 药店报账工具 { public class ExcelHelper { public class x2003 { /// <summary> /// 将DataTable数据导出到Excel文件中(xls) /// </summary> /// <param name="dt"></param> /// <param name="file"></param> /// <param name="month"></param> /// <param name="index"></param> public static void TableToExcelForXLS(DataTable dt, string file, string month,int index) { month = "total"; try { HSSFWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet(month); // 当且仅当第一次交易时创建表头 if (index == 1) { //表头 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } ICell cells = row.CreateCell(10); cells.SetCellValue("月份"); } FileStream fout = new FileStream(file, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); //row = sheet.CreateRow((sheet.LastRowNum + 1));//在工作表中添加一行 // 在最后一行插入数据 IRow row1 = sheet.CreateRow(sheet.LastRowNum + 1); ICell cell1 = row1.CreateCell(0); cell1.SetCellValue(rows[0].ToString()); for (int j = 1; j < 7; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue((double)rows[j]); } for (int j = 7; j < 10; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(rows[j].ToString()); } ICell cellmon = row1.CreateCell(10); cellmon.SetCellValue(DateTime.Now.Year.ToString() + "年" + DateTime.Now.Month.ToString() + "月"); //cell.SetCellValue() fout.Flush(); workbook.Write(fout);//写入文件 workbook = null; fout.Close(); } catch (Exception e) { } } } /// <summary> /// 获取单元格类型(xls) /// </summary> /// <param name="cell"></param> /// <returns></returns> private static object GetValueTypeForXLS(HSSFCell cell) { if (cell == null) return null; switch (cell.CellType) { case CellType.Blank: //BLANK: return null; case CellType.Boolean: //BOOLEAN: return cell.BooleanCellValue; case CellType.Numeric: //NUMERIC: return cell.NumericCellValue; case CellType.String: //STRING: return cell.StringCellValue; case CellType.Error: //ERROR: return cell.ErrorCellValue; case CellType.Formula: //FORMULA: default: return "=" + cell.CellFormula; } } } public class x2007 { #region Excel2007 /// <summary> /// 将Excel文件中的数据读出到DataTable中(xlsx) /// </summary> /// <param name="file"></param> /// <returns></returns> public static DataTable ExcelToTableForXLSX(string file) { DataTable dt = new DataTable(); using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs); ISheet sheet = xssfworkbook.GetSheetAt(0); //表头 IRow header = sheet.GetRow(sheet.FirstRowNum); List<int> columns = new List<int>(); for (int i = 0; i < header.LastCellNum; i++) { object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell); if (obj == null || obj.ToString() == string.Empty) { dt.Columns.Add(new DataColumn("Columns" + i.ToString())); //continue; } else dt.Columns.Add(new DataColumn(obj.ToString())); columns.Add(i); } //数据 for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++) { DataRow dr = dt.NewRow(); bool hasValue = false; foreach (int j in columns) { dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell); if (dr[j] != null && dr[j].ToString() != string.Empty) { hasValue = true; } } if (hasValue) { dt.Rows.Add(dr); } } } return dt; } /// <summary> /// 将DataTable数据导出到Excel文件中(xlsx) /// </summary> /// <param name="dt"></param> /// <param name="file"></param> public static void TableToExcelForXLSX(DataTable dt, string file) { XSSFWorkbook xssfworkbook = new XSSFWorkbook(); ISheet sheet = xssfworkbook.CreateSheet("Test"); //表头 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } //数据 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } //转为字节数组 MemoryStream stream = new MemoryStream(); xssfworkbook.Write(stream); var buf = stream.ToArray(); //保存为Excel文件 using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)) { fs.Write(buf, 0, buf.Length); fs.Flush(); } } /// <summary> /// 获取单元格类型(xlsx) /// </summary> /// <param name="cell"></param> /// <returns></returns> private static object GetValueTypeForXLSX(XSSFCell cell) { if (cell == null) return null; switch (cell.CellType) { case CellType.Blank: //BLANK: return null; case CellType.Boolean: //BOOLEAN: return cell.BooleanCellValue; case CellType.Numeric: //NUMERIC: return cell.NumericCellValue; case CellType.String: //STRING: return cell.StringCellValue; case CellType.Error: //ERROR: return cell.ErrorCellValue; case CellType.Formula: //FORMULA: default: return "=" + cell.CellFormula; } } #endregion } class DataTableRenderToExcel { public static Stream RenderDataTableToExcel(DataTable SourceTable) { HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = new MemoryStream(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); // handling header. foreach (DataColumn column in SourceTable.Columns) headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); // handling value. int rowIndex = 1; foreach (DataRow row in SourceTable.Rows) { HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); foreach (DataColumn column in SourceTable.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet = null; headerRow = null; workbook = null; return ms; } public static void RenderDataTableToExcel(DataTable SourceTable, string FileName) { MemoryStream ms = RenderDataTableToExcel(SourceTable) as MemoryStream; FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write); byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); data = null; ms = null; fs = null; } public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex) { HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream); HSSFSheet sheet = (HSSFSheet)workbook.GetSheet(SheetName); DataTable table = new DataTable(); HSSFRow headerRow = (HSSFRow)sheet.GetRow(HeaderRowIndex); int cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } int rowCount = sheet.LastRowNum; for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum; i++) { HSSFRow row = (HSSFRow)sheet.GetRow(i); DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) dataRow[j] = row.GetCell(j).ToString(); } ExcelFileStream.Close(); workbook = null; sheet = null; return table; } public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex) { HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream); HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(SheetIndex); DataTable table = new DataTable(); HSSFRow headerRow = (HSSFRow)sheet.GetRow(HeaderRowIndex); int cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } int rowCount = sheet.LastRowNum; for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum; i++) { HSSFRow row = (HSSFRow)sheet.GetRow(i); DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } table.Rows.Add(dataRow); } ExcelFileStream.Close(); workbook = null; sheet = null; return table; } } }
using Microsoft.JSInterop; using GoogleMapsComponents.Maps; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace GoogleMapsComponents { public class MapFunctionJsInterop { private IJSRuntime _jsRuntime; public MapFunctionJsInterop(IJSRuntime jsRuntime) { _jsRuntime = jsRuntime; } public Task Init(string id, MapOptions options) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.init", id, options); } public Task Dispose(string id) { return _jsRuntime.InvokeAsync<bool>( "googleMapJsFunctions.dispose", id); } public Task FitBounds(string id, LatLngBoundsLiteral bounds) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.fitBounds", id, bounds); } public Task PanBy(string id, int x, int y) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.panBy", id, x, y); } public Task PanTo(string id, LatLngLiteral latLng) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.panTo", id, latLng); } public Task PanToBounds(string id, LatLngBoundsLiteral latLngBounds) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.panToBounds", id, latLngBounds); } public Task<LatLngBoundsLiteral> GetBounds(string id) { return _jsRuntime.JsonNetInvokeAsync<LatLngBoundsLiteral>( "googleMapJsFunctions.getBounds", id); } public Task<LatLngLiteral> GetCenter(string id) { return _jsRuntime.JsonNetInvokeAsync<LatLngLiteral>( "googleMapJsFunctions.getCenter", id); } public Task SetCenter(string id, LatLngLiteral latLng) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.setCenter", id, latLng); } public Task<bool> GetClickableIcons(string id) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.getClickableIcons", id); } public Task SetClickableIcons(string id, bool value) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.setClickableIcons", id, value); } public Task<int> GetHeading(string id) { return _jsRuntime.JsonNetInvokeAsync<int>( "googleMapJsFunctions.getHeading", id); } public Task SetHeading(string id, int heading) { return _jsRuntime.JsonNetInvokeAsync<int>( "googleMapJsFunctions.setHeading", id, heading); } public async Task<MapTypeId> GetMapTypeId(string id) { var str = await _jsRuntime.JsonNetInvokeAsync<string>( "googleMapJsFunctions.getMapTypeId", id); Debug.WriteLine($"Get map type {str}"); return Helper.ToEnum<MapTypeId>(str); } public Task SetMapTypeId(string id, MapTypeId mapTypeId) { return _jsRuntime.JsonNetInvokeAsync<int>( "googleMapJsFunctions.setMapTypeId", id, mapTypeId); } public Task<int> GetTilt(string id) { return _jsRuntime.JsonNetInvokeAsync<int>( "googleMapJsFunctions.getTilt", id); } public Task SetTilt(string id, int tilt) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.setTilt", id, tilt); } public Task<int> GetZoom(string id) { return _jsRuntime.JsonNetInvokeAsync<int>( "googleMapJsFunctions.getZoom", id); } public Task SetZoom(string id, int zoom) { return _jsRuntime.JsonNetInvokeAsync<bool>( "googleMapJsFunctions.setZoom", id, zoom); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TurningtoMoney : MonoBehaviour { public Sprite birTl; public Sprite elliKurus; public Sprite yirmibesKurus; public Sprite onKurus; public Sprite emptyMoney; public GameObject newBirTL; public GameObject newElliKurus; public GameObject newYirmiBesKurus; public GameObject newOnKurus; private void OnCollisionEnter2D(Collision2D other) { if (gameObject.GetComponent<SpriteRenderer>().sprite == emptyMoney && other.gameObject.GetComponent<SpriteRenderer>().sprite == birTl) { Instantiate(newBirTL, gameObject.transform.position, gameObject.transform.rotation); Destroy(gameObject); //gameObject.GetComponent<SpriteRenderer>().sprite = birTl; //AddComponent<Rigidbody2D>(); } if (gameObject.GetComponent<SpriteRenderer>().sprite == emptyMoney && other.gameObject.GetComponent<SpriteRenderer>().sprite == elliKurus) { Instantiate(newElliKurus, gameObject.transform.position, gameObject.transform.rotation); Destroy(gameObject); //gameObject.GetComponent<SpriteRenderer>().sprite = elliKurus; //gameObject.AddComponent<Rigidbody2D>(); } if (gameObject.GetComponent<SpriteRenderer>().sprite == emptyMoney && other.gameObject.GetComponent<SpriteRenderer>().sprite == yirmibesKurus) { Instantiate(newYirmiBesKurus, gameObject.transform.position, gameObject.transform.rotation); Destroy(gameObject); //gameObject.GetComponent<SpriteRenderer>().sprite = yirmibesKurus; //gameObject.AddComponent<Rigidbody2D>(); } if (gameObject.GetComponent<SpriteRenderer>().sprite == emptyMoney && other.gameObject.GetComponent<SpriteRenderer>().sprite == onKurus) { Instantiate(newOnKurus, gameObject.transform.position, gameObject.transform.rotation); Destroy(gameObject); //gameObject.GetComponent<SpriteRenderer>().sprite = onKurus; //gameObject.AddComponent<Rigidbody2D>(); } } }
namespace CustomDate { public class CustomDATE { private int year; private int month; private int day; public CustomDATE(int year, int month , int day) { this.year = year; this.month = month; this.day = day ; } public override string ToString() { return $"DD/MM/YYYY : {day:d2}/{month:d2}/{year:d2}"; } public void Add(int days) { this.day = this.day + days; Normalize(); } public void Add(int months, int days) { this.month += months; this.day += days ; Normalize(); } public void Add(CustomDATE other) { Add(other.month , other.day); Normalize(); } private void Normalize() { /* * a.If the days field is more than the number of days in a month, then it subtracts the number of days * in the month from the day field and increases the month field by one. b.If the month field is more than 12 then, 12 is subtracted from the month field and the year field is increased by 1 */ while (this.day > 31) { this.day -= 31; this.month += 1; } while (this.month > 12) { this.month -= 12; this.year += 1; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Markup; using System.Windows.Media; using System.Xml; namespace CODE.Framework.Wpf.Documents { /// <summary> /// Document paginator class (used for print output) /// </summary> public class DocumentPaginatorEx : DocumentPaginator { private readonly DocumentPaginator _flowDocumentPaginator; /// <summary> /// Initializes a new instance of the <see cref="DocumentPaginatorEx" /> class. /// </summary> /// <param name="document">The document.</param> /// <param name="printableArea">The printable area size.</param> /// <param name="range">The print page range.</param> public DocumentPaginatorEx(FlowDocument document, Size printableArea, PageRange range) { // Clone the source document's content into a new FlowDocument. // This is because the pagination for the printer needs to be // done differently than the pagination for the displayed page. // We print the copy, rather that the original FlowDocument. var stream = new MemoryStream(); var source = new TextRange(document.ContentStart, document.ContentEnd); source.Save(stream, DataFormats.Xaml); var documentCopy = new FlowDocument(); var dest = new TextRange(documentCopy.ContentStart, documentCopy.ContentEnd); dest.Load(stream, DataFormats.Xaml); // Ready to go on the copy of the document var paginatorSource = documentCopy as IDocumentPaginatorSource; _flowDocumentPaginator = paginatorSource.DocumentPaginator; CurrentPage = 0; TotalPrintableArea = printableArea; var height = printableArea.Height; var width = printableArea.Width; var docEx = document as FlowDocumentEx; if (docEx != null) { width -= (docEx.PrintMargin.Left + docEx.PrintMargin.Right); height -= (docEx.PrintMargin.Top + docEx.PrintMargin.Bottom); DocumentPrintMargin = docEx.PrintMargin; OriginalPrintMargin = docEx.PrintMargin; Watermark = docEx.PrintWatermark; if (Watermark != null) { Watermark.Resources = document.Resources; Watermark.DataContext = document.DataContext; Watermark.Measure(printableArea); Watermark.Arrange(new Rect(0,0, Watermark.DesiredSize.Width, Watermark.DesiredSize.Height)); } Header = docEx.PageHeader; if (Header != null) { Header.Resources = document.Resources; Header.DataContext = document.DataContext; Header.Width = width; Header.Measure(new Size(width, double.PositiveInfinity)); Header.Height = Header.DesiredSize.Height; // These two lines attempt to fix the size as desired and make sure it is properly measured at that Header.Measure(new Size(width, Header.DesiredSize.Height)); Header.Arrange(new Rect(0,0, Header.DesiredSize.Width, Header.DesiredSize.Height)); height -= Header.DesiredSize.Height; DocumentPrintMargin = new Thickness(DocumentPrintMargin.Left, DocumentPrintMargin.Top + Header.DesiredSize.Height, DocumentPrintMargin.Right, DocumentPrintMargin.Bottom); } Footer = docEx.PageFooter; if (Footer != null) { Footer.Resources = document.Resources; Footer.DataContext = document.DataContext; Footer.Width = width; Footer.Measure(new Size(width, double.PositiveInfinity)); Footer.Height = Footer.DesiredSize.Height; // These two lines attempt to fix the size as desired and make sure it is properly measured at that Footer.Measure(new Size(width, Footer.DesiredSize.Height)); Footer.Arrange(new Rect(0, 0, Footer.DesiredSize.Width, Footer.DesiredSize.Height)); height -= Footer.DesiredSize.Height; DocumentPrintMargin = new Thickness(DocumentPrintMargin.Left, DocumentPrintMargin.Top, DocumentPrintMargin.Right, DocumentPrintMargin.Bottom + Footer.DesiredSize.Height); } } else DocumentPrintMargin = new Thickness(); _flowDocumentPaginator.PageSize = new Size(width, height); _flowDocumentPaginator.ComputePageCount(); TotalPages = _flowDocumentPaginator.PageCount; Range = range; } /// <summary>Defines the area within the total printable area that can be used to print page content</summary> private Thickness DocumentPrintMargin { get; set; } /// <summary>Defines the area within the total printable area that can be used for any content (including headers and footers)</summary> private Thickness OriginalPrintMargin { get; set; } /// <summary>Printable page size (without margins)</summary> private Size TotalPrintableArea { get; set; } /// <summary>Watermark</summary> private FrameworkElement Watermark { get; set; } /// <summary>Header</summary> private FrameworkElement Header { get; set; } /// <summary>Footer</summary> private FrameworkElement Footer { get; set; } /// <summary>Page currently printing</summary> private int CurrentPage { get; set; } /// <summary>Total pages printing</summary> private int TotalPages { get; set; } /// <summary>Page range to print</summary> private PageRange Range { get; set; } /// <summary> /// When overridden in a derived class, gets a value indicating whether <see cref="P:System.Windows.Documents.DocumentPaginator.PageCount" /> is the total number of pages. /// </summary> /// <value><c>true</c> if this instance is page count valid; otherwise, <c>false</c>.</value> /// <returns>true if pagination is complete and <see cref="P:System.Windows.Documents.DocumentPaginator.PageCount" /> is the total number of pages; otherwise, false, if pagination is in process and <see cref="P:System.Windows.Documents.DocumentPaginator.PageCount" /> is the number of pages currently formatted (not the total).This value may revert to false, after being true, if <see cref="P:System.Windows.Documents.DocumentPaginator.PageSize" /> or content changes; because those events would force a repagination.</returns> public override bool IsPageCountValid { get { return _flowDocumentPaginator != null && _flowDocumentPaginator.IsPageCountValid; } } /// <summary> /// When overridden in a derived class, gets a count of the number of pages currently formatted /// </summary> /// <value>The page count.</value> /// <returns>A count of the number of pages that have been formatted.</returns> public override int PageCount { get { if (_flowDocumentPaginator == null) return 0; if (Range.PageFrom < 2 && Range.PageTo == 0) return TotalPages; var from = Range.PageFrom; var to = Math.Min(Range.PageTo, TotalPages); var total = to - from; return total + 1; } } /// <summary>Translates the index of the printed page to the actual page</summary> /// <param name="nativePageNumber">Native page number</param> /// <returns>Translated page</returns> /// <remarks> /// Example: If only pages 3-5 are printed, then whenever the system requests /// page number 0, that is really the 3rd page (first in the printed range) /// and thus page index 2 has to be returned /// </remarks> private int GetTranslatedPageNumber(int nativePageNumber) { if (Range.PageFrom < 2 && Range.PageTo == 0) return nativePageNumber; var translatedPageNumber = nativePageNumber + Range.PageFrom - 1; return translatedPageNumber; } /// <summary> /// When overridden in a derived class, gets or sets the suggested width and height of each page. /// </summary> /// <value>The size of the page.</value> /// <returns>A <see cref="T:System.Windows.Size" /> representing the width and height of each page.</returns> public override Size PageSize { get { return _flowDocumentPaginator.PageSize; } set { _flowDocumentPaginator.PageSize = value; } } /// <summary> /// When overridden in a derived class, returns the element being paginated. /// </summary> /// <value>The source.</value> /// <returns>An <see cref="T:System.Windows.Documents.IDocumentPaginatorSource" /> representing the element being paginated.</returns> public override IDocumentPaginatorSource Source { get { return _flowDocumentPaginator == null ? null : _flowDocumentPaginator.Source; } } /// <summary> /// When overridden in a derived class, gets the <see cref="T:System.Windows.Documents.DocumentPage" /> for the specified page number. /// </summary> /// <param name="pageNumber">The zero-based page number of the document page that is needed.</param> /// <returns>The <see cref="T:System.Windows.Documents.DocumentPage" /> for the specified <paramref name="pageNumber" />, or <see cref="F:System.Windows.Documents.DocumentPage.Missing" /> if the page does not exist.</returns> public override DocumentPage GetPage(int pageNumber) { var realPageNumber = GetTranslatedPageNumber(pageNumber); // Needed if only certain pages are to be printed CurrentPage = realPageNumber + 1; var printPage = new ContainerVisual(); RenderElement(printPage, Watermark, PrintElementType.Watermark); RenderElement(printPage, Header, PrintElementType.Header); var page = _flowDocumentPaginator.GetPage(realPageNumber); if (DocumentPrintMargin.Top > 0 || DocumentPrintMargin.Left > 0) printPage.Transform = new TranslateTransform(DocumentPrintMargin.Left, DocumentPrintMargin.Top); printPage.Children.Add(page.Visual); RenderElement(printPage, Footer, PrintElementType.Footer); return new DocumentPage(printPage); } /// <summary> /// Renders the element to the provided page (container). /// </summary> /// <param name="container">The container.</param> /// <param name="visual">The visual.</param> /// <param name="alignment">The alignment.</param> private void RenderElement(ContainerVisual container, FrameworkElement visual, PrintElementType alignment) { if (visual == null) return; var drawingVisual = new DrawingVisual(); using (var dc = drawingVisual.RenderOpen()) { var visualX = 0d; var visualY = 0d; var visualHeight = visual.DesiredSize.Height; var visualWidth = visual.DesiredSize.Width; switch (alignment) { case PrintElementType.Header: visualY = OriginalPrintMargin.Top; visualX = OriginalPrintMargin.Left; break; case PrintElementType.Footer: visualY = TotalPrintableArea.Height - OriginalPrintMargin.Bottom - visual.DesiredSize.Height; visualX = OriginalPrintMargin.Left; break; case PrintElementType.Watermark: var totalWidth = TotalPrintableArea.Width - OriginalPrintMargin.Left - OriginalPrintMargin.Right; var totalHeight = TotalPrintableArea.Height - OriginalPrintMargin.Top - OriginalPrintMargin.Bottom; visualX = ((totalWidth - visualWidth)/2) + OriginalPrintMargin.Left; visualY = ((totalHeight - visualHeight)/2) + OriginalPrintMargin.Right; break; } if (visual.Margin.Top > 0.0001 || visual.Margin.Left > 0.0001 || visual.Margin.Right > 0.0001 || visual.Margin.Bottom > 0.0001) { visualX += visual.Margin.Left; visualY += visual.Margin.Top; visualHeight -= (visual.Margin.Top + visual.Margin.Bottom); visualWidth -= (visual.Margin.Left + visual.Margin.Right); } // We need to clone the visual, so we can change the same visual individually on each page if need be var xaml = XamlWriter.Save(visual); var stringReader = new StringReader(xaml); var xmlReader = XmlReader.Create(stringReader); var newVisual = (FrameworkElement) XamlReader.Load(xmlReader); newVisual.DataContext = visual.DataContext; newVisual.Resources = visual.Resources; CheckVisualForSpecialRuns(newVisual); var brush = new VisualBrush(newVisual) {Stretch = Stretch.None}; var renderRect = new Rect(visualX, visualY, visualWidth, visualHeight); if (DocumentPrintMargin.Top > 0 || DocumentPrintMargin.Left > 0) dc.PushTransform(new TranslateTransform(DocumentPrintMargin.Left * -1, DocumentPrintMargin.Top * -1)); dc.DrawRectangle(brush, new Pen(Brushes.Transparent, 0d), renderRect); if (DocumentPrintMargin.Top > 0 || DocumentPrintMargin.Left > 0) dc.Pop(); } container.Children.Add(drawingVisual); } private void CheckVisualForSpecialRuns(FrameworkElement root) { var currentPages = new List<CurrentPage>(); var pageCounts = new List<PageCount>(); var text = root as TextBlock; if (text != null) { foreach (var run in text.Inlines) { var pageCount = run as PageCount; if (pageCount != null) pageCounts.Add(pageCount); var currentPage = run as CurrentPage; if (currentPage != null) currentPages.Add(currentPage); } foreach (var pageCount in pageCounts) pageCount.Text = TotalPages.ToString(CultureInfo.InvariantCulture); foreach (var currentPage in currentPages) currentPage.Text = CurrentPage.ToString(CultureInfo.InvariantCulture); return; } var items = root as ItemsControl; if (items != null) foreach (var item in items.Items) { var childElement = item as FrameworkElement; if (childElement != null) CheckVisualForSpecialRuns(childElement); } else { var panel = root as Panel; if (panel != null) foreach (var item in panel.Children) { var childElement = item as FrameworkElement; if (childElement != null) CheckVisualForSpecialRuns(childElement); } } } private enum PrintElementType { Header, Footer, Watermark } } }
// <copyright file="GlyphMapDictionary.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> using System; using System.Collections; using System.Collections.Generic; namespace WaterTrans.GlyphLoader.Internal.SFNT { /// <summary> /// The glyph map dictionary. /// </summary> internal class GlyphMapDictionary : IDictionary<ushort, ushort> { private readonly Dictionary<ushort, ushort> _internalDictionary; /// <summary> /// Initializes a new instance of the <see cref="GlyphMapDictionary"/> class. /// </summary> /// <param name="internalDictionary">The internal dictionary.</param> internal GlyphMapDictionary(Dictionary<ushort, ushort> internalDictionary) { _internalDictionary = internalDictionary; } /// <inheritdoc /> public ICollection<ushort> Keys { get { return _internalDictionary.Keys; } } /// <inheritdoc /> public ICollection<ushort> Values { get { return _internalDictionary.Values; } } /// <inheritdoc /> public int Count { get { return _internalDictionary.Count; } } /// <inheritdoc /> public bool IsReadOnly { get { return true; } } /// <inheritdoc /> public ushort this[ushort key] { get { return _internalDictionary[key]; } set { throw new NotSupportedException(); } } /// <inheritdoc /> public void Add(ushort key, ushort value) { throw new NotSupportedException(); } /// <inheritdoc /> public bool ContainsKey(ushort key) { return _internalDictionary.ContainsKey(key); } /// <inheritdoc /> public bool Remove(ushort key) { throw new NotSupportedException(); } /// <inheritdoc /> public bool TryGetValue(ushort key, out ushort value) { if (ContainsKey(key)) { value = this[key]; return true; } else { value = default; return false; } } /// <inheritdoc /> public void Add(KeyValuePair<ushort, ushort> item) { throw new NotSupportedException(); } /// <inheritdoc /> public void Clear() { throw new NotSupportedException(); } /// <inheritdoc /> public bool Contains(KeyValuePair<ushort, ushort> item) { return ContainsKey(item.Key); } /// <inheritdoc /> public void CopyTo(KeyValuePair<ushort, ushort>[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(nameof(array)); } if (arrayIndex < 0 || arrayIndex >= array.Length || (arrayIndex + Count) > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex)); } for (ushort i = 0; i < Count; ++i) { array[arrayIndex + i] = new KeyValuePair<ushort, ushort>(i, this[i]); } } /// <inheritdoc /> public bool Remove(KeyValuePair<ushort, ushort> item) { throw new NotSupportedException(); } /// <inheritdoc /> public IEnumerator<KeyValuePair<ushort, ushort>> GetEnumerator() { for (ushort i = 0; i < Count; ++i) { yield return new KeyValuePair<ushort, ushort>(i, this[i]); } } /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<KeyValuePair<ushort, ushort>>)this).GetEnumerator(); } } }
using System; using System.Collections.Generic; using Hl7.Fhir.Support; using System.Xml.Linq; /* Copyright (c) 2011-2012, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // // Generated on Mon, Apr 15, 2013 13:14+1000 for FHIR v0.08 // namespace Hl7.Fhir.Model { /// <summary> /// A document that contains resources /// </summary> [FhirResource("Document")] public partial class Document : Resource { /// <summary> /// The way in which a person authenticated a document /// </summary> public enum DocumentAttestationMode { Personal, // The person authenticated the document in their personal capacity Professional, // The person authenticated the document in their professional capacity Legal, // The person authenticated the document and accepted legal responsibility for its content Official, // The organization authenticated the document as consistent with their policies and procedures } /// <summary> /// Conversion of DocumentAttestationModefrom and into string /// <summary> public static class DocumentAttestationModeHandling { public static bool TryParse(string value, out DocumentAttestationMode result) { result = default(DocumentAttestationMode); if( value=="personal") result = DocumentAttestationMode.Personal; else if( value=="professional") result = DocumentAttestationMode.Professional; else if( value=="legal") result = DocumentAttestationMode.Legal; else if( value=="official") result = DocumentAttestationMode.Official; else return false; return true; } public static string ToString(DocumentAttestationMode value) { if( value==DocumentAttestationMode.Personal ) return "personal"; else if( value==DocumentAttestationMode.Professional ) return "professional"; else if( value==DocumentAttestationMode.Legal ) return "legal"; else if( value==DocumentAttestationMode.Official ) return "official"; else throw new ArgumentException("Unrecognized DocumentAttestationMode value: " + value.ToString()); } } /// <summary> /// null /// </summary> [FhirComposite("SectionComponent")] public partial class SectionComponent : Element { /// <summary> /// Classification of section (recommended) /// </summary> public CodeableConcept Code { get; set; } /// <summary> /// If section different to document /// </summary> public ResourceReference Subject { get; set; } /// <summary> /// The actual data for the section /// </summary> public ResourceReference Content { get; set; } /// <summary> /// Nested Section /// </summary> public List<SectionComponent> Section { get; set; } } /// <summary> /// null /// </summary> [FhirComposite("DocumentAttesterComponent")] public partial class DocumentAttesterComponent : Element { /// <summary> /// personal | professional | legal | official /// </summary> public Code<Document.DocumentAttestationMode> Mode { get; set; } /// <summary> /// When document attested /// </summary> public FhirDateTime Time { get; set; } /// <summary> /// Who attested the document /// </summary> public ResourceReference Party { get; set; } } /// <summary> /// null /// </summary> [FhirComposite("DocumentEventComponent")] public partial class DocumentEventComponent : Element { /// <summary> /// Code(s) that apply to the event being documented /// </summary> public List<CodeableConcept> Code { get; set; } /// <summary> /// The period covered by the document /// </summary> public Period Period { get; set; } /// <summary> /// Full details for the event(s) the document concents /// </summary> public List<ResourceReference> Detail { get; set; } } /// <summary> /// Logical identifier for document (version-independent) /// </summary> public Identifier Id { get; set; } /// <summary> /// Version-specific identifier for document /// </summary> public Identifier VersionId { get; set; } /// <summary> /// Document creation time /// </summary> public Instant Created { get; set; } /// <summary> /// Particular kind of document /// </summary> public Coding Class { get; set; } /// <summary> /// Kind of document (LOINC if possible) /// </summary> public CodeableConcept Type { get; set; } /// <summary> /// Document title /// </summary> public FhirString Title { get; set; } /// <summary> /// As defined by affinity domain /// </summary> public Coding Confidentiality { get; set; } /// <summary> /// Who/what the document is about /// </summary> public ResourceReference Subject { get; set; } /// <summary> /// Who/what authored the final document /// </summary> public List<ResourceReference> Author { get; set; } /// <summary> /// Attests to accuracy of document /// </summary> public List<DocumentAttesterComponent> Attester { get; set; } /// <summary> /// Org which maintains the document /// </summary> public ResourceReference Custodian { get; set; } /// <summary> /// The clinical event/act/item being documented /// </summary> public DocumentEventComponent Event { get; set; } /// <summary> /// Context of the document /// </summary> public ResourceReference Visit { get; set; } /// <summary> /// If this document replaces another /// </summary> public Id Replaces { get; set; } /// <summary> /// Additional provenance about the document and it's parts /// </summary> public List<ResourceReference> Provenance { get; set; } /// <summary> /// Stylesheet to use when rendering the document /// </summary> public Attachment Stylesheet { get; set; } /// <summary> /// Alternative representation of the document /// </summary> public Attachment Representation { get; set; } /// <summary> /// Document is broken into sections /// </summary> public List<SectionComponent> Section { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Domain.Entity { /// <summary> /// 商品规格选项 /// </summary> public class ProductSpecificationOption:BaseEntity { public int ProductSpecificationId { get; set; } public string Value { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnimalClinic { class Program { static void Main(string[] args) { string[] command = Console.ReadLine().Split(); List<Animal> animals = new List<Animal>(); while (command[0] != "End") { animals.Add(new Animal(command[0], command[1], AnimalClinic.patientId)); switch (command[2]) { case "heal": AnimalClinic.Heal(); break; case "rehab": AnimalClinic.Rehabilitate(); break; } command = Console.ReadLine().Split(); } foreach (Animal animal in animals) { Console.WriteLine($"Patient {animal.Id}: [{animal.Name} ({animal.Breed})] has been healed!"); } Console.WriteLine($"Total healed animals: {AnimalClinic.healedAnimalsCount}"); Console.WriteLine($"Total rehabilitated animals: {AnimalClinic.rehabilitatedAnimalsCount}"); foreach (Animal animal in animals) { Console.WriteLine($"{animal.Name} {animal.Breed}"); } Console.ReadKey(); } } }
using Microsoft.EntityFrameworkCore; using System; namespace PlayNGoCoffee { /// <summary> /// Db representation model /// </summary> public class ApplicationDbContext : DbContext { #region Public Properties /// <summary> /// Setup table models /// </summary> public DbSet<LocationDataModel> Locations { get; set; } public DbSet<IngredientDataModel> Ingredients { get; set; } public DbSet<StockDataModel> Stocks { get; set; } public DbSet<RecipeIngredientDataModel> RecipeIngredients { get; set; } public DbSet<RecipeDataModel> Recipes { get; set; } public DbSet<OrderHistoryDataModel> OrderHistories { get; set; } #endregion #region Constructor public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } #endregion protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<RecipeIngredientDataModel>() .HasKey(o => new { o.IngredientId, o.RecipeId }); #region Data Seeding modelBuilder.Entity<RecipeDataModel>().HasData( new RecipeDataModel { Id = 1, Name = "Double Americano", Description = "Will use 3 Coffee Beans" }, new RecipeDataModel { Id = 2, Name = "Sweet Latte", Description = "Will use 2 Coffee Beans, 5 Sugar and 3 Milk" }, new RecipeDataModel { Id = 3, Name = "Flat White", Description = "Will use 2 Coffee Beans, 1 Sugar and 4 Milk" }); modelBuilder.Entity<IngredientDataModel>().HasData( new IngredientDataModel { Id = 1, IngredientName = "Coffee Bean" }, new IngredientDataModel { Id = 2, IngredientName = "Sugar" }, new IngredientDataModel { Id = 3, IngredientName = "Milk" }); modelBuilder.Entity<StockDataModel>().HasData( new StockDataModel { Id = 1, IngredientId = 1, Unit = 45, LocationId = 1 }, new StockDataModel { Id = 2, IngredientId = 2, Unit = 45, LocationId = 1 }, new StockDataModel { Id = 3, IngredientId = 3, Unit = 45, LocationId = 1 }, new StockDataModel { Id = 4, IngredientId = 1, Unit = 1, LocationId = 2 }, new StockDataModel { Id = 5, IngredientId = 2, Unit = 5, LocationId = 2 }, new StockDataModel { Id = 6, IngredientId = 3, Unit = 2, LocationId = 2 }); modelBuilder.Entity<LocationDataModel>().HasData( new LocationDataModel { Id = 1, LocationName = "Pantry 1", Description = "First Location" }, new LocationDataModel { Id = 2, LocationName = "Pantry 2", Description = "Second Location" }); modelBuilder.Entity<RecipeIngredientDataModel>().HasData( new RecipeIngredientDataModel { RecipeId = 1, IngredientId = 1, Unit = 3 }, new RecipeIngredientDataModel { RecipeId = 2, IngredientId = 1, Unit = 2 }, new RecipeIngredientDataModel { RecipeId = 2, IngredientId = 2, Unit = 5 }, new RecipeIngredientDataModel { RecipeId = 2, IngredientId = 3, Unit = 3 }, new RecipeIngredientDataModel { RecipeId = 3, IngredientId = 1, Unit = 2 }, new RecipeIngredientDataModel { RecipeId = 3, IngredientId = 2, Unit = 1 }, new RecipeIngredientDataModel { RecipeId = 3, IngredientId = 3, Unit = 4 }); modelBuilder.Entity<OrderHistoryDataModel>().HasData( new OrderHistoryDataModel { Id = 1, RecipeId = 1, DateOrdered = DateTime.Now, Quantity = 1 }, new OrderHistoryDataModel { Id = 2, RecipeId = 3, DateOrdered = DateTime.Now, Quantity = 1 }); #endregion } } }
using System.Threading.Tasks; using ZKCloud.Applications; using ZKCloud.Datas.Queries; using ZKCloud.Domains.Repositories; using ZKCloud.Domains.Services; using ZKCloud.Extensions; namespace ZKCloud.Test.Samples { /// <summary> /// 增删改查服务样例 /// </summary> public interface ICrudServiceSample : ICrudService<DtoSample, QueryParameterSample> { } /// <summary> /// 工作单元样例 /// </summary> public class UnitOfWorkSample : ZKCloud.Datas.UnitOfWorks.IUnitOfWork { public void Dispose() { } public int Commit() { return 1; } public Task<int> CommitAsync() { return Task.FromResult( 1 ); } } /// <summary> /// 增删改查服务样例 /// </summary> public class CrudServiceSample : CrudServiceBase<EntitySample, DtoSample, QueryParameterSample> ,ICrudServiceSample { public CrudServiceSample( ZKCloud.Datas.UnitOfWorks.IUnitOfWork unitOfWork, IRepositorySample repository ) : base( unitOfWork, repository ) { } /// <summary> /// 转换为实体 /// </summary> /// <param name="dto">数据传输对象</param> protected override EntitySample ToEntity( DtoSample dto ) { return ZKCloud.Maps.Extensions.MapTo(dto, new EntitySample(dto.Id.ToGuid() ) ); } /// <summary> /// 创建查询对象 /// </summary> /// <param name="parameter">查询参数</param> protected override IQueryBase<EntitySample> CreateQuery( QueryParameterSample parameter ) { return new Query<EntitySample>( parameter ); } } }
namespace ProjectBueno.Engine { /// <summary> /// The interface for the handler classes. <para/> /// The game can have 1 active <see cref="IHandler"/>, which is stored in <see cref="Main.Handler"/> /// </summary> public interface IHandler { /// <summary> /// Called on update. <para/> /// Should call all the update logic of its contents. /// </summary> void Update(); /// <summary> /// Called on draw. <para/> /// Should call all the draw logic of its contents. /// </summary> void Draw(); /// <summary> /// Called on window resize. Might be called with no resize having ocurred (for instance on change of current handler or when window size is maxed out). <para/> /// Should change all values dependent on screen size to their correct new values. <para/> /// Use <see cref="Main.Viewport"/> to get current screen size. /// </summary> void WindowResize(); /// <summary> /// Called when the handler becomes the active handler (unless intentionally bypassed). <para/> /// See also: <seealso cref="Main.Handler"/> /// </summary> void Initialize(); /// <summary> /// Called when the handler is no longer the active handler (unless intentionally bypassed). <para/> /// See also: <seealso cref="Main.Handler"/> /// </summary> void Deinitialize(); } }
using IBLLService; using MODEL; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BLLService { public partial class Buyer_userManager : BaseBLLService<buyer_user>, IBuyer_userManager { public override int Add(buyer_user model) { base.Add(model); return model.buid; } } }
using System; using System.Web.UI; namespace MadamRozikaPanel.CrossCuttingLayer { public class BasePage : Page { private int _PageCache = 600; public int PageCache { get { return _PageCache; } set { _PageCache = value; } } public Seo PageSeo; public BasePage() { PageSeo = GetDefaultSiteSeoSettings(Page); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); Response.Cache.SetMaxAge(new TimeSpan(0, 0, PageCache)); Response.CacheControl = "Public"; Response.Cache.VaryByParams.IgnoreParams = true; Response.Cache.SetSlidingExpiration(true); } protected override void Render(HtmlTextWriter writer) { PageSeo.RenderSeo(); using (HtmlTextWriter HtmlWriter = new HtmlTextWriter(new System.IO.StringWriter())) { base.Render(HtmlWriter); if (Request.QueryString["MinifyHtml"] == null) //Test For Html { writer.Write(HtmlWriter.InnerWriter.ToString().MinifyHtml()); } else { writer.Write(HtmlWriter.InnerWriter); } } } protected virtual Seo GetDefaultSiteSeoSettings(Page page) { Seo PageSeo = new Seo(page); PageSeo.Title = "Haber"; return PageSeo; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; using UnityEngine.EventSystems; public class console : MonoBehaviour { bool isInConsoleMode = false; [SerializeField] InputField consoleLine; [SerializeField] GameObject skeleton; [SerializeField] GameObject spider; private void Update() { if (Input.GetKeyDown(KeyCode.BackQuote)) { ChangeConsoleState(); } if (isInConsoleMode) { EventSystem.current.SetSelectedGameObject(consoleLine.gameObject, null); consoleLine.OnPointerClick(new PointerEventData(EventSystem.current)); if (Input.GetKeyDown(KeyCode.Return)) { var command = consoleLine.GetComponent<InputField>().text; consoleLine.GetComponent<InputField>().text = ""; switch (command) { case "killall": foreach(Enemy enm in FindObjectsOfType<Enemy>()) { enm.Health = 0; } break; case "godmode": GameObject.Find("Hero").GetComponent<Player>().SetGodMode(!GameObject.Find("Hero").GetComponent<Player>().godMode); break; case "kill": Enemy nearestEnemy = new Enemy(); float minDistance = float.MaxValue; foreach (Enemy enemy in FindObjectsOfType<Enemy>()) { if(Vector2.Distance(enemy.gameObject.transform.position, GameObject.Find("Hero").transform.position) < minDistance && enemy.Health > 0) { minDistance = Vector2.Distance(enemy.gameObject.transform.position, GameObject.Find("Hero").transform.position); nearestEnemy = enemy; } } nearestEnemy.Health = 0; break; case "resurrect": break; case "spawn skeleton": Instantiate(skeleton, (Vector2)GameObject.Find("Hero").transform.position + new Vector2(3, 0), Quaternion.identity); break; } ChangeConsoleState(); } } } void ChangeConsoleState() { Time.timeScale = Time.timeScale == 0 ? 1f : 0f; isInConsoleMode = !isInConsoleMode; Info.IsGameOn = !isInConsoleMode; consoleLine.gameObject.SetActive(isInConsoleMode); } }
namespace Junfine.Debuger { using System; using UnityEngine; public class Debuger { public static bool enableLog = true; public static void Log(string str, params object[] args) { if (enableLog) { str = string.Format(str, args); Debug.Log(str); } } public static void Log(string str) { if (enableLog) { Debug.Log(str); } } public static void LogWarning(string str) { if (enableLog) { Debug.LogWarning(str); } } public static void LogWarning(string str, params object[] args) { if (enableLog) { str = string.Format(str, args); Debug.LogWarning(str); } } public static void LogError(string str) { if (enableLog) { Debug.LogError(str); } } public static void LogError(string str, params object[] args) { if (enableLog) { str = string.Format(str, args); Debug.LogError(str); } } } }
using System.Collections.Generic; namespace DevExpress.Web.Demos { public static class CountriesProvider { public static IList<Country> GetCountries() { return new List<Country>(){ new Country("Russia", 17.0752), new Country("Canada", 9.98467), new Country("USA", 9.63142), new Country("China", 9.59696), new Country("Brazil", 8.511965), new Country("Australia", 7.68685), new Country("India", 3.28759), new Country("Others", 81.2) }; } } public class Country { string name; double area; public string Name { get { return name; } } public double Area { get { return area; } } public Country(string name, double area) { this.name = name; this.area = area; } } }
using System; using System.Linq; using System.Collections.Generic; using UIKit; using Foundation; using Aquamonix.Mobile.IOS.Views; using Aquamonix.Mobile.Lib.ViewModels; using Aquamonix.Mobile.IOS.UI; using Aquamonix.Mobile.Lib.Utilities; using Aquamonix.Mobile.Lib.Domain; namespace Aquamonix.Mobile.IOS.ViewControllers { public partial class CircuitsTimerViewController : TopLevelViewControllerBase { private static CircuitsTimerViewController _instance; //private DeviceDetailViewModel _device; private Action<int> _testSelectedCircuits; protected override nfloat ReconBarVerticalLocation { get { var output = (_headerTextView.IsDisposed) ? 0 : _headerTextView.Frame.Bottom; if (output == 0) output = base.ReconBarVerticalLocation + 6; return output; } } private CircuitsTimerViewController(DeviceDetailViewModel device, Action<int> testSelectedCircuits) : base() { ExceptionUtility.Try(() => { //this._device = device; this.Initialize(); if (testSelectedCircuits != null) this._testSelectedCircuits = WeakReferenceUtility.MakeWeakAction(testSelectedCircuits); }); } public static CircuitsTimerViewController CreateInstance(DeviceDetailViewModel device, Action<int> testSelectedCircuits) { ExceptionUtility.Try(() => { if (_instance != null) { _instance.Dispose(); _instance = null; } _instance = new CircuitsTimerViewController(device, testSelectedCircuits); }); return _instance; } protected override void InitializeViewController() { ExceptionUtility.Try(() => { base.InitializeViewController(); this._navBarView.OnCancel = () => { this.NavigationController.PopViewController(true); }; this.NavigationBarView = this._navBarView; this.NavigationItem.HidesBackButton = true; this._intervalPickerView.Value = TimeSpan.FromMinutes(120); this._startButton.TouchUpInside += (o, e) => { this.SubmitChanges(); }; }); } private void SubmitChanges() { ExceptionUtility.Try(() => { this.NavigationController.PopViewController(true); if (this._testSelectedCircuits != null) this._testSelectedCircuits((int)this._intervalPickerView.Value.TotalMinutes); }); } private class NavBarView : NavigationBarView { public const int Margin = 16; private readonly UIButton _cancelButton = new UIButton(); private readonly AquamonixLabel _titleLabel = new AquamonixLabel(); private Action _onCancel; public Action OnCancel { get { return this._onCancel; } set { this._onCancel = WeakReferenceUtility.MakeWeakAction(value); } } public NavBarView() : base(fullWidth: true) { ExceptionUtility.Try(() => { //cancel button this._cancelButton.SetTitle(StringLiterals.CancelButtonText, UIControlState.Normal); this._cancelButton.SetFontAndColor(new FontWithColor(Fonts.RegularFontName, Sizes.FontSize8, UIColor.White)); this._cancelButton.TouchUpInside += (o, e) => { if (this.OnCancel != null) this.OnCancel(); }; //selected label this._titleLabel.SetFontAndColor(new FontWithColor(Fonts.SemiboldFontName, Sizes.FontSize8, UIColor.White)); this._titleLabel.Text = StringLiterals.StartCircuits; this.BackgroundColor = Colors.AquamonixGreen; this.AddSubviews(_titleLabel, _cancelButton); }); } public override void LayoutSubviews() { ExceptionUtility.Try(() => { base.LayoutSubviews(); //cancel button this._cancelButton.SizeToFit(); this._cancelButton.SetFrameHeight(Height); this._cancelButton.SetFrameLocation(Margin, 0); //selection label this._titleLabel.SizeToFit(); this._titleLabel.SetFrameHeight(Height); this._titleLabel.SetFrameLocation(this.Frame.Width / 2 - this._titleLabel.Frame.Width / 2, 0); //this._titleLabel.EnforceMaxXCoordinate(this.Frame.Width - this._setButton.Frame.Left); }); } } } }
using System; using System.Collections; using UnityEngine; using UnityEngine.EventSystems; using UnityStandardAssets.CrossPlatformInput; public class Thumbstick : MonoBehaviour, IPointerUpHandler, IPointerDownHandler, IDragHandler { // Options for which axes to use public enum AxisOption { Both, // Use both OnlyHorizontal, // Only horizontal OnlyVertical // Only vertical } [SerializeField] private AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use [SerializeField] private string horizontalAxisName = "Horizontal"; [SerializeField] private string verticalAxisName = "Vertical"; [SerializeField] private float fadeInDuration = 0.1f; [SerializeField] private float fadeOutDuration = 0.1f; [SerializeField] private float backgroundAlpha = 0.25f; [SerializeField] private float foregroundAlpha = 0.5f; [SerializeField] private RectTransform grip; [SerializeField] private RectTransform limits; [SerializeField] private UnityEngine.UI.Image background; [SerializeField] private UnityEngine.UI.Image foreground; // References to the axes in the cross platform input private CrossPlatformInputManager.VirtualAxis horizontalVirtualAxis; private CrossPlatformInputManager.VirtualAxis verticalVirtualAxis; private bool useX { get { return (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal); } } private bool useY { get { return (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical); } } #region Monobehaviour void OnEnable() { // create new axes based on axes to use if (useX) { horizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName); CrossPlatformInputManager.RegisterVirtualAxis(horizontalVirtualAxis); } if (useY) { verticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName); CrossPlatformInputManager.RegisterVirtualAxis(verticalVirtualAxis); } } void OnDisable() { // remove the joysticks from the cross platform input if (useX) horizontalVirtualAxis.Remove(); if (useY) verticalVirtualAxis.Remove(); } void Awake() { background.CrossFadeAlpha(0, 0, false); } #endregion #region IPointerUpHandler public void OnPointerUp(PointerEventData data) { background.CrossFadeAlpha(0, fadeOutDuration, false); foreground.CrossFadeAlpha(1, fadeOutDuration, false); grip.anchoredPosition = Vector2.zero; if (useX) horizontalVirtualAxis.Update(0); if (useY) verticalVirtualAxis.Update(0); } #endregion #region IPointerDownHandler public void OnPointerDown(PointerEventData data) { background.CrossFadeAlpha(backgroundAlpha, fadeInDuration, false); foreground.CrossFadeAlpha(foregroundAlpha, fadeInDuration, false); UpdateGrip(data.position.x, data.position.y); } #endregion #region IPointerClickHandler public void OnPointerClick(PointerEventData data) { Debug.LogFormat("Click on: {0}", data.position); } #endregion #region IDragHandler public void OnDrag(PointerEventData data) { UpdateGrip(data.position.x, data.position.y); } #endregion private void UpdateGrip(float x, float y) { Vector2 size = Vector2.Scale(limits.rect.size, new Vector2(limits.lossyScale.x, limits.lossyScale.y)); Vector2 delta = Vector2.zero; if (useX) { delta.x = x - limits.position.x; horizontalVirtualAxis.Update(Mathf.Clamp(delta.x / size.x, -1, 1)); } if (useY) { delta.y = y - limits.position.y; verticalVirtualAxis.Update(Mathf.Clamp(delta.y / size.y, -1, 1)); } float w = limits.rect.width; float h = limits.rect.height; float radius = Mathf.Sqrt(w * w + h * h) / 2; grip.anchoredPosition = Vector2.ClampMagnitude( Vector2.Scale(delta, new Vector2(1 / limits.lossyScale.x, 1 / limits.lossyScale.y)), radius); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Draft_FF.Frontend.Helpers; using Draft_FF.Frontend.Entities; using System.Net.Http; using System.Net; using Serilog; using Draft_FF.Frontend.DTOs; using Draft_FF.Frontend.Service; using Draft_FF.Frontend.DataAccess; using Microsoft.AspNetCore.Authorization; using AutoMapper; using System.Security.Claims; namespace Draft_FF.Frontend.Controllers { [Authorize] [Route("api/[controller]")] [ApiController] public class DraftController : ControllerBase { private readonly DataContext _Context; private readonly ILogger _Logger; private readonly DraftHub _DraftHub; private readonly IMapper _Mapper; public Player ExtractPossible { get; private set; } public DraftController(DataContext context, ILogger argLogger, DraftHub argDraftHub, IMapper argMapper) { _Context = context; _Logger = argLogger; _DraftHub = argDraftHub; _Mapper = argMapper; } [HttpGet("DraftSlots")] public IEnumerable<DraftSlotDto> DraftSlots() { try { var draftSlots = _Context.DraftPickSlots; return _Mapper.Map<IList<DraftSlotDto>>(draftSlots); } catch (Exception ex) { _Logger.Error(ex, $"{nameof(OwnerController)}.{nameof(DraftSlots)}() failed"); return new List<DraftSlotDto>(); } } [HttpGet("GetState")] public DraftStateDto GetState() { try { var loggedInOwner = GetOwnerByUserAuthentication(); var availablePlayers = GetAvailablePlayerForOwner(loggedInOwner); var availablePlayerDtos = _Mapper.Map<List<PlayerDto>>(availablePlayers); var draftState = new DraftStateDto(); draftState.DraftSlots = _Mapper.Map<IList<DraftSlotDto>>( _Context .DraftPickSlots .Include(e => e.Owner) .Include(e => e.SelectedPlayer) .OrderBy(e => e.Overall)); draftState.Rosters = GetRosters(); draftState.AvailablePlayers = availablePlayerDtos.Select(e => { e.IsOwnedByLoggedInOwner = IsPlayerOwnedByOwnerId(e, loggedInOwner.Id); return e; }).ToList(); return draftState; } catch(Exception ex) { _Logger.Error(ex, $"GetState failed"); return null; } } private bool IsPlayerOwnedByOwnerId(PlayerDto argPlayer, int argOwnerId) { return argPlayer.OwnerId.HasValue && argPlayer.OwnerId == argOwnerId; } private IEnumerable<RosterDto> GetRosters() { var picks = _Context .Players .Include(e => e.SelectedInDraftSlot) .Where(e => e.SelectedInDraftSlot != null) .GroupBy(e => e.SelectedInDraftSlot.Owner) .ToDictionary(e => e.Key.Id, e => e.ToList()); var owners = _Context .Owners .OrderBy(e => e.Name); var result = new List<RosterDto>(); foreach(var owner in owners) { var roster = new RosterDto(); roster.Owner = _Mapper.Map<OwnerDto>(owner); if (picks.ContainsKey(owner.Id)) { var picksFromOwner = picks[owner.Id].OrderBy(e => e.SelectedInDraftSlot.Overall).ToList(); roster.Qb = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.QB)); roster.Rb1 = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.RB)); roster.Rb2 = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.RB)); roster.Wr1 = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.WR)); roster.Wr2 = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.WR)); roster.Wr3 = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.WR)); roster.Te = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.TE)); roster.Flex = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.TE, Enums.Position.RB, Enums.Position.WR)); roster.K = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.K)); roster.Dst = _Mapper.Map<PlayerDto>(ExtractPossiblePlayer(ref picksFromOwner, Enums.Position.DST)); roster.Bench = _Mapper.Map<IList<PlayerDto>>(picksFromOwner); } result.Add(roster); } return result; } private Player ExtractPossiblePlayer(ref List<Player> argPlayers, params Enums.Position[] argPositions) { var possiblePlayer = argPlayers.FirstOrDefault(e => argPositions.Contains(e.Position)); if (possiblePlayer != null) { argPlayers = argPlayers .Where(e => e.Id != possiblePlayer.Id) .ToList(); } return possiblePlayer; } private Owner GetOwnerByUserAuthentication() { var user = User.Identity.Name; return _Context.Owners.Single(e => string.Equals(e.Id.ToString(), user, StringComparison.InvariantCultureIgnoreCase)); } private IEnumerable<Player> GetAvailablePlayerForOwner(Owner argOwner) { var currentPickSlot = _Context .DraftPickSlots .Include(e => e.Owner) .OrderBy(e => e.Overall) .FirstOrDefault(e => e.SelectedPlayer == null); var unpickedPlayers = _Context.Players.Include(e => e.Team).Where(e => e.SelectedInDraftSlot == null); var filteredPlayers = unpickedPlayers; if (currentPickSlot == null || currentPickSlot.Round > 12) { filteredPlayers = unpickedPlayers; return filteredPlayers .OrderByDescending(e => (e.OwnerId.HasValue && e.OwnerId == argOwner.Id)) .ThenBy(e => e.Rank == null) .ThenBy(e => e.Rank) .ThenByDescending(e => e.ProjectedPoints); } else { if (argOwner.IsExpansionTeam) { var ownerToPickFrom = GetOwnerToPickFrom(); var playersPickedFromOwner = _Context.Players .Include(e => e.SelectedInDraftSlot) .Where(e => e.SelectedInDraftSlot != null) .Where(e => e.OwnerId == ownerToPickFrom.Id) .Where(e => e.SelectedInDraftSlot.Owner.IsExpansionTeam) .Count(); if (playersPickedFromOwner >= 2) { filteredPlayers = unpickedPlayers.Where(e => e.Owner == null); } else { filteredPlayers = unpickedPlayers.Where(e => e.Owner == null || e.Owner == ownerToPickFrom); } } else { filteredPlayers = unpickedPlayers.Where(e => e.Owner == null || e.OwnerId == argOwner.Id); } return filteredPlayers .OrderByDescending(e => (e.OwnerId.HasValue && e.OwnerId == argOwner.Id)) .ThenByDescending(e => e.OwnerId.HasValue) .ThenBy(e => e.Rank == null) .ThenBy(e => e.Rank) .ThenByDescending(e => e.ProjectedPoints); } } private Owner GetOwnerToPickFrom() { var owners = _Context .Owners .Where(e => e.IsExpansionTeam == false) .Select(e => new OwnerHelper { Owner = e, NumberPickedFrom = 0 }) .ToList(); for(var i = 0; i < owners.Count; i++) { var step1 = _Context.Players.Include(e => e.SelectedInDraftSlot).Where(e => e.SelectedInDraftSlot != null); var step2 = step1.Where(e => e.OwnerId == owners[i].Owner.Id); var step3 = step2.Where(e => e.SelectedInDraftSlot.Owner.IsExpansionTeam); owners[i].NumberPickedFrom = step3.Count(); } return owners .OrderBy(e => e.NumberPickedFrom) .ThenByDescending(e => e.Owner.DraftRank) .Select(e => e.Owner) .FirstOrDefault(); } private class OwnerHelper { public Owner Owner { get; set; } public int NumberPickedFrom { get; set; } } [HttpPost("Pick")] public IActionResult Pick([FromBody] PickDto argPick) { try { var selectedPlayer = _Context.Players.Find(argPick.PlayerId); var slots = _Context .DraftPickSlots .OrderBy(e => e.Overall) .ToList(); var currentPick = slots.FirstOrDefault(e => e.SelectedPlayerId.HasValue == false); if(currentPick.Id != argPick.PickSlotId) { throw new Exception($"invalid pick"); } currentPick.SelectedPlayer = selectedPlayer; currentPick.SelectedPlayerId = argPick.PlayerId; _Context.SaveChanges(); var info = new DraftPickInfoDto(); info.CurrentDraftSlot = _Mapper.Map<DraftSlotDto>(currentPick); info.PickedPlayer = _Mapper.Map<PlayerDto>(selectedPlayer); _DraftHub.NotifyOwners(info); } catch(Exception ex) { _Logger.Error(ex, $"Could not process pick."); } return NoContent(); } [HttpPost("MapPlaceholders")] public IActionResult MapPlaceholders() { try { var slots = _Context.DraftPickSlots; foreach(var slot in slots) { slot.OwnerId = slot.PlaceHolder + 1; } _Context.SaveChanges(); } catch (Exception ex) { _Logger.Error(ex, $"MapPlaceholders failed"); } return NoContent(); } [HttpPost("CreateDraft")] public async Task<IActionResult> CreateDraft() { try { var draftPickSlots = new List<DraftPickSlot>(); var numberOfTeams = 12; for (int placeholder = 0; placeholder < 10; placeholder++) { for (int round = 1; round <= 12; round++) { var overall = numberOfTeams * (round - 1) + (placeholder + 1); var slot = new DraftPickSlot() { Overall = overall, PlaceHolder = placeholder, Round = round, RankInRound = placeholder + 1 }; draftPickSlots.Add(slot); } } // specialTeam [11] draftPickSlots.Add(new DraftPickSlot() { Overall = 11, PlaceHolder = 10, Round = 1, RankInRound = 11 }); //12 draftPickSlots.Add(new DraftPickSlot() { Overall = 24, PlaceHolder = 10, Round = 2, RankInRound = 12 }); //24 draftPickSlots.Add(new DraftPickSlot() { Overall = 35, PlaceHolder = 10, Round = 3, RankInRound = 11 }); //36 draftPickSlots.Add(new DraftPickSlot() { Overall = 48, PlaceHolder = 10, Round = 4, RankInRound = 12 }); //48 draftPickSlots.Add(new DraftPickSlot() { Overall = 59, PlaceHolder = 10, Round = 5, RankInRound = 11 }); //60 draftPickSlots.Add(new DraftPickSlot() { Overall = 82, PlaceHolder = 10, Round = 6, RankInRound = 12 }); //72 draftPickSlots.Add(new DraftPickSlot() { Overall = 73, PlaceHolder = 10, Round = 7, RankInRound = 11 }); //84 draftPickSlots.Add(new DraftPickSlot() { Overall = 96, PlaceHolder = 10, Round = 8, RankInRound = 12 }); //96 draftPickSlots.Add(new DraftPickSlot() { Overall = 107, PlaceHolder = 10, Round = 9, RankInRound = 11 }); //108 draftPickSlots.Add(new DraftPickSlot() { Overall = 120, PlaceHolder = 10, Round = 10, RankInRound = 12 }); //120 draftPickSlots.Add(new DraftPickSlot() { Overall = 131, PlaceHolder = 10, Round = 11, RankInRound = 11 }); //132 draftPickSlots.Add(new DraftPickSlot() { Overall = 144, PlaceHolder = 10, Round = 12, RankInRound = 12 }); //144 // specialTeam [12] draftPickSlots.Add(new DraftPickSlot() { Overall = 12, PlaceHolder = 11, Round = 1, RankInRound = 12 }); //12 draftPickSlots.Add(new DraftPickSlot() { Overall = 23, PlaceHolder = 11, Round = 2, RankInRound = 11 }); //24 draftPickSlots.Add(new DraftPickSlot() { Overall = 36, PlaceHolder = 11, Round = 3, RankInRound = 12 }); //36 draftPickSlots.Add(new DraftPickSlot() { Overall = 47, PlaceHolder = 11, Round = 4, RankInRound = 11 }); //48 draftPickSlots.Add(new DraftPickSlot() { Overall = 60, PlaceHolder = 11, Round = 5, RankInRound = 12 }); //60 draftPickSlots.Add(new DraftPickSlot() { Overall = 71, PlaceHolder = 11, Round = 6, RankInRound = 11 }); //72 draftPickSlots.Add(new DraftPickSlot() { Overall = 84, PlaceHolder = 11, Round = 7, RankInRound = 12 }); //84 draftPickSlots.Add(new DraftPickSlot() { Overall = 95, PlaceHolder = 11, Round = 8, RankInRound = 11 }); //96 draftPickSlots.Add(new DraftPickSlot() { Overall = 108, PlaceHolder = 11, Round = 9, RankInRound = 12 }); //108 draftPickSlots.Add(new DraftPickSlot() { Overall = 119, PlaceHolder = 11, Round = 10, RankInRound = 11 }); //120 draftPickSlots.Add(new DraftPickSlot() { Overall = 132, PlaceHolder = 11, Round = 11, RankInRound = 12 }); //132 draftPickSlots.Add(new DraftPickSlot() { Overall = 143, PlaceHolder = 11, Round = 12, RankInRound = 11 }); //144 var placeholders = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 10 }; for(var round = 13; round <= 20; round++) { for (int i = 0; i < placeholders.Length; i++) { var overall = placeholders.Length * (round - 1) + (i + 1); var slot = new DraftPickSlot() { Overall = overall, PlaceHolder = placeholders[i], Round = round, RankInRound = i + 1 }; draftPickSlots.Add(slot); } Array.Reverse(placeholders); if (round % 2 == 0) { Array.Reverse(placeholders, 10, 2); } } var draft = new Draft() { DraftName = "Draft 2018", Slots = draftPickSlots }; await _Context.Drafts.AddAsync(draft); await _Context.SaveChangesAsync(); } catch(Exception ex) { _Logger.Error(ex, $"creating draft failed"); } return NoContent(); } } }
using System.Collections.Generic; using UnityEngine; namespace Zoo { class Spawner : MonoBehaviour { [SerializeField] private GameObject lion, hippo, pig, tiger, zebra, monkey, toucan; public List <Animal> animals; /// <summary> /// Instantiates every animal and adds them to the scene. /// </summary> private void Start() { Lion henk = Instantiate(lion, transform).GetComponent<Lion>(); Hippo elsa = Instantiate(hippo, transform).GetComponent<Hippo>(); Pig dora = Instantiate(pig, transform).GetComponent<Pig>(); Tiger wally = Instantiate(tiger, transform).GetComponent<Tiger>(); Zebra marty = Instantiate(zebra, transform).GetComponent<Zebra>(); Monkey ceaser = Instantiate(monkey, transform).GetComponent<Monkey>(); Toucan duif = Instantiate(toucan, transform).GetComponent<Toucan>(); animals.Add(henk); animals.Add(elsa); animals.Add(dora); animals.Add(wally); animals.Add(marty); animals.Add(ceaser); animals.Add(duif); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using JsonLibrary; using JsonLibrary.FromClient; using JsonLibrary.FromServer; using Microsoft.AspNetCore.SignalR; namespace SnakeMultiplayer.Services; /// <summary> /// Methods available for Server to call the Clients /// </summary> public interface IServerHub { Task SendArenaStatusUpdate(string looby, ArenaStatus status); Task SendEndGame(string lobby); Task ExitGame(string lobby, string reason); Task InitiateGameStart(string lobby, ArenaStatus report); Task SendSettingsUpdate(string lobby, Settings settings); Task SendPlayerStatusUpdate(string lobby, List<Player> players, string removedlayerName = null); } static class ClientMethod { public const string OnSettingsUpdate = "OnSettingsUpdate"; public const string OnPlayerStatusUpdate = "OnPlayerStatusUpdate"; public const string OnPing = "OnPing"; public const string OnGameEnd = "OnGameEnd"; public const string OnLobbyMessage = "OnLobbyMessage"; public const string OnGameStart = "OnGameStart"; public const string OnArenaStatusUpdate = "OnArenaStatusUpdate"; } public class ServerHub : IServerHub { public IHubContext<LobbyHub> HubContext { get; } public ServerHub(IHubContext<LobbyHub> hubContext) { HubContext = hubContext; } public Task SendPlayerStatusUpdate(string lobby, List<Player> players, string removedPlayerName = null) { var message = new Message("server", lobby, "Players", new { players, removed = removedPlayerName }); return HubContext.Clients.Group(lobby).SendAsync(ClientMethod.OnPlayerStatusUpdate, message); } public Task InitiateGameStart(string lobby, ArenaStatus report) { var message = new Message("server", lobby, "Start", new { Start = report }); return HubContext.Clients.Group(lobby).SendAsync(ClientMethod.OnGameStart, message); } public Task SendArenaStatusUpdate(string lobby, ArenaStatus status) { var message = new Message("server", lobby, "Update", new { status }); Console.WriteLine($"Sending: {Message.Serialize(message)}"); return HubContext.Clients.Group(lobby).SendAsync(ClientMethod.OnArenaStatusUpdate, message); } public Task SendSettingsUpdate(string lobby, Settings settings) { var message = new Message("server", lobby, "Settings", new { Settings = settings }); return HubContext.Clients.Group(lobby).SendAsync(ClientMethod.OnSettingsUpdate, message); } public Task SendEndGame(string lobby) { var message = new Message("server", lobby, "End", null); return HubContext.Clients.Group(lobby).SendAsync(ClientMethod.OnGameEnd, message); } public Task ExitGame(string lobby, string reason) { var message = new Message("server", lobby, "Exit", new { message = reason }); return HubContext.Clients.Group(lobby).SendAsync(ClientMethod.OnPlayerStatusUpdate, message); } }
using KingNetwork.Shared.Encryptation; using KingNetwork.Shared.Extensions; using System.Security.Cryptography; using Xunit; using XUnitPriorityOrderer; namespace KingNetwork.Shared.Tests { [Order(3)] public class SharedTests { #region constructors public SharedTests() { } #endregion #region tests implementations [Fact, Order(1)] public void Verify_XteaEncryptation_ShouldReturnTrue() { //Arrange var key = XteaEncryptation.GenerateKey(); var messageValue = "Test"; var messageWriter = KingBufferWriter.Create(); messageWriter.Write(messageValue); //Act var encryptedMessageWriter = XteaEncryptation.Encrypt(messageWriter, key); var encryptedMessageReader = encryptedMessageWriter.ToKingBufferReader(); var decryptedMessageReader = XteaEncryptation.Decrypt(encryptedMessageReader, key); var decryptedMessageValue = decryptedMessageReader.ReadString(); //Assert Assert.True(decryptedMessageValue.Equals(messageValue)); } [Fact, Order(2)] public void Verify_RsaEncryptation_ShouldReturnTrue() { //Arrange var provider = new RSACryptoServiceProvider(1024); var pubKey = provider.ExportParameters(false).ToRsaEncryptationParameters(); var privKey = provider.ExportParameters(true).ToRsaEncryptationParameters(); var messageValue = "Test"; var messageWriter = KingBufferWriter.Create(); messageWriter.Write(messageValue); //Act var encryptedMessageWriter = RsaEncryptation.Encrypt(messageWriter, pubKey); var encryptedMessageReader = encryptedMessageWriter.ToKingBufferReader(); var decryptedMessageReader = RsaEncryptation.Decrypt(encryptedMessageReader, privKey); var decryptedMessageValue = decryptedMessageReader.ReadString(); //Assert Assert.True(decryptedMessageValue.Equals(messageValue)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using IRAP.Global; namespace IRAP.Interface.OPC { public class TUpdateDeviceTagsReqDetail { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// KepServer 定义的标签名称 /// </summary> public string TagName { get; set; } /// <summary> /// KepServer 定义的标签数据类型 /// </summary> public string DataType { get; set; } /// <summary> /// KepServer 定义的标签描述 /// </summary> public string Description { get; set; } public TUpdateDeviceTagsReqDetail Clone() { return MemberwiseClone() as TUpdateDeviceTagsReqDetail; } public static TUpdateDeviceTagsReqDetail LoadFromXMLNode(XmlNode node) { if (node.Name != "Row") return null; TUpdateDeviceTagsReqDetail rlt = new TUpdateDeviceTagsReqDetail(); rlt = IRAPXMLUtils.LoadValueFromXMLNode(node, rlt) as TUpdateDeviceTagsReqDetail; return rlt; } public XmlNode GenerateXMLNode(XmlNode row) { return IRAPXMLUtils.GenerateXMLAttribute(row, this); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using System.Runtime.InteropServices; using System.IO; using System.ComponentModel; using Microsoft.VisualStudio.Shell.Interop; namespace MetaDslx.VisualStudio { public class MultipleFileItem<T> { public MultipleFileItem() { this.Properties = new Dictionary<string, string>(); } public T Info { get; set; } public string CustomTool { get; set; } public Dictionary<string,string> Properties { get; private set; } public bool EmbedResource { get; set; } public bool GeneratedExternally { get; set; } } public abstract class SingleFileGenerator { public SingleFileGenerator(string inputFilePath, string inputFileContents, string defaultNamespace) { this.InputFilePath = inputFilePath; if (inputFilePath != null) { this.InputFileName = Path.GetFileName(inputFilePath); this.InputDirectory = Path.GetDirectoryName(inputFilePath); } this.InputFileContents = inputFileContents; this.DefaultNamespace = defaultNamespace; } public string InputFileContents { get; private set; } public string InputFileName { get; private set; } public string InputDirectory { get; private set; } public string InputFilePath { get; private set; } public string DefaultNamespace { get; private set; } public virtual string GenerateStringContent() { return ""; } public virtual byte[] GenerateByteContent() { string stringContent = this.GenerateStringContent(); MemoryStream memory = new MemoryStream(); StreamWriter writer = new StreamWriter(memory, Encoding.UTF8); writer.Write(stringContent); writer.Flush(); memory.Flush(); byte[] contents = new byte[memory.Length]; memory.Position = 0; memory.Read(contents, 0, contents.Length); return contents; } } public abstract class MultipleFileGenerator<T> { public MultipleFileGenerator(string inputFilePath, string inputFileContents, string defaultNamespace) { if (inputFilePath != null) { this.InputFilePath = Path.GetFullPath(inputFilePath); this.InputFileName = Path.GetFileName(inputFilePath); this.InputDirectory = Path.GetDirectoryName(this.InputFilePath); } this.InputFileContents = inputFileContents; this.DefaultNamespace = defaultNamespace; } public string InputFileContents { get; private set; } public string InputFileName { get; private set; } public string InputFilePath { get; private set; } public string InputDirectory { get; private set; } public string DefaultNamespace { get; private set; } public abstract IEnumerable<MultipleFileItem<T>> GetFileItems(); public abstract string GetFileName(MultipleFileItem<T> element); public virtual string GenerateStringContent(MultipleFileItem<T> element) { return ""; } public virtual byte[] GenerateByteContent(MultipleFileItem<T> element) { string stringContent = this.GenerateStringContent(element); MemoryStream memory = new MemoryStream(); StreamWriter writer = new StreamWriter(memory, Encoding.UTF8); writer.Write(stringContent); writer.Flush(); memory.Flush(); byte[] contents = new byte[memory.Length]; memory.Position = 0; memory.Read(contents, 0, contents.Length); return contents; } } public abstract class VsSingleFileGenerator : IVsSingleFileGenerator, IObjectWithSite { private object site; protected abstract SingleFileGenerator CreateGenerator(string inputFilePath, string inputFileContents, string defaultNamespace); public abstract string GetDefaultFileExtension(); public int DefaultExtension(out string pbstrDefaultExtension) { pbstrDefaultExtension = this.GetDefaultFileExtension(); if (!string.IsNullOrWhiteSpace(pbstrDefaultExtension)) { return Microsoft.VisualStudio.VSConstants.S_OK; } else { return Microsoft.VisualStudio.VSConstants.S_FALSE; } } public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { rgbOutputFileContents[0] = IntPtr.Zero; pcbOutput = 0; try { SingleFileGenerator generator = this.CreateGenerator(wszInputFilePath, bstrInputFileContents, wszDefaultNamespace); byte[] contents = generator.GenerateByteContent(); rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(contents.Length); Marshal.Copy(contents, 0, rgbOutputFileContents[0], contents.Length); pcbOutput = (uint)contents.Length; return Microsoft.VisualStudio.VSConstants.S_OK; } catch (Exception ex) { pGenerateProgress.GeneratorError(0, 0, string.Format("[{2}] Could not process input file: {0}. Error: {1}", wszInputFilePath, ex.ToString(), this.GetType().Name), 0, 0); } return Microsoft.VisualStudio.VSConstants.E_FAIL; } #region IObjectWithSite Members public void GetSite(ref Guid riid, out IntPtr ppvSite) { if (this.site == null) { throw new Win32Exception(-2147467259); } IntPtr objectPointer = Marshal.GetIUnknownForObject(this.site); try { Marshal.QueryInterface(objectPointer, ref riid, out ppvSite); if (ppvSite == IntPtr.Zero) { throw new Win32Exception(-2147467262); } } finally { if (objectPointer != IntPtr.Zero) { Marshal.Release(objectPointer); objectPointer = IntPtr.Zero; } } } public void SetSite(object pUnkSite) { this.site = pUnkSite; } #endregion } public abstract class VsMultipleFileGenerator<T> : IVsSingleFileGenerator, IObjectWithSite { #region Visual Studio Specific Fields private object site; private ServiceProvider serviceProvider = null; #endregion #region Our Fields private EnvDTE.Project project; private List<string> newFileNames; #endregion protected EnvDTE.Project Project { get { return project; } } private ServiceProvider SiteServiceProvider { get { if (serviceProvider == null) { Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleServiceProvider = site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider; serviceProvider = new ServiceProvider(oleServiceProvider); } return serviceProvider; } } public VsMultipleFileGenerator() { newFileNames = new List<string>(); } protected abstract MultipleFileGenerator<T> CreateGenerator(string inputFilePath, string inputFileContents, string defaultNamespace); public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { rgbOutputFileContents[0] = IntPtr.Zero; pcbOutput = 0; string inputPath = Path.GetFullPath(wszInputFilePath); if (project == null) { EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE)); EnvDTE.Projects projects = dte.Solution.Projects; if (projects.Count > 0) { foreach (var prjObj in projects) { EnvDTE.Project prj = prjObj as EnvDTE.Project; if (prj != null) { string projectPath = Path.GetFullPath(Path.GetDirectoryName(prj.FullName)); if (inputPath.StartsWith(projectPath)) { project = prj; break; } } } } } if (project == null) return Microsoft.VisualStudio.VSConstants.S_FALSE; try { MultipleFileGenerator<T> generator = this.CreateGenerator(wszInputFilePath, bstrInputFileContents, wszDefaultNamespace); this.newFileNames.Clear(); int iFound = 0; uint itemId = 0; EnvDTE.ProjectItem item; Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY[] pdwPriority = new Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY[1]; // obtain a reference to the current project as an IVsProject type Microsoft.VisualStudio.Shell.Interop.IVsProject VsProject = VsHelper.ToVsProject(project); // this locates, and returns a handle to our source file, as a ProjectItem VsProject.IsDocumentInProject(wszInputFilePath, out iFound, pdwPriority, out itemId); // if our source file was found in the project (which it should have been) if (iFound != 0 && itemId != 0) { Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleSp = null; VsProject.GetItemContext(itemId, out oleSp); if (oleSp != null) { ServiceProvider sp = new ServiceProvider(oleSp); // convert our handle to a ProjectItem item = sp.GetService(typeof(EnvDTE.ProjectItem)) as EnvDTE.ProjectItem; } else throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem"); } else throw new ApplicationException("Unable to retrieve Visual Studio ProjectItem"); string defaultFileName = generator.InputFileName; string defaultExt = null; if (this.DefaultExtension(out defaultExt) == Microsoft.VisualStudio.VSConstants.S_OK) { defaultFileName = Path.ChangeExtension(defaultFileName, defaultExt); } else { defaultFileName = Path.GetFileNameWithoutExtension(defaultFileName); } // now we can start our work, iterate across all the 'elements' in our source file foreach (MultipleFileItem<T> element in generator.GetFileItems()) { try { // obtain a name for this target file string fileName = generator.GetFileName(element); // add it to the tracking cache newFileNames.Add(fileName); // fully qualify the file on the filesystem string strFile = Path.Combine(wszInputFilePath.Substring(0, wszInputFilePath.LastIndexOf(Path.DirectorySeparatorChar)), fileName); if (!element.GeneratedExternally) { if (fileName == defaultFileName) { // generate our target file content byte[] data = generator.GenerateByteContent(element); if (data == null) { rgbOutputFileContents[0] = IntPtr.Zero; pcbOutput = 0; } else { // return our summary data, so that Visual Studio may write it to disk. rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(data.Length); Marshal.Copy(data, 0, rgbOutputFileContents[0], data.Length); pcbOutput = (uint)data.Length; } } else { // create the file FileStream fs = File.Create(strFile); try { // generate our target file content byte[] data = generator.GenerateByteContent(element); // write it out to the stream fs.Write(data, 0, data.Length); fs.Close(); } catch (Exception ex) { fs.Close(); if (File.Exists(strFile)) { File.Delete(strFile); } throw ex; } } } // add the newly generated file to the solution, as a child of the source file... if (File.Exists(strFile) && fileName != defaultFileName) { EnvDTE.ProjectItem itm = item.ProjectItems.AddFromFile(strFile); // embed as a resource: if (element.EmbedResource) { itm.Properties.Item("BuildAction").Value = 3; } // set a custom tool: if (!string.IsNullOrEmpty(element.CustomTool)) { EnvDTE.Property prop = itm.Properties.Item("CustomTool"); if (string.IsNullOrEmpty((string)prop.Value) || !string.Equals((string)prop.Value, element.CustomTool)) { prop.Value = element.CustomTool; } } /*foreach (var key in element.Properties.Keys) { string value = element.Properties[key]; EnvDTE.Property prop = itm.Properties.Item(key); if (prop != null && string.IsNullOrEmpty((string)prop.Value) || !string.Equals((string)prop.Value, value)) { prop.Value = value; } }*/ } } catch (Exception ex) { throw ex; } } // perform some clean-up, making sure we delete any old (stale) target-files foreach (EnvDTE.ProjectItem childItem in item.ProjectItems) { if ((childItem.Name != defaultFileName) && !newFileNames.Contains(childItem.Name)) // then delete it childItem.Delete(); } } catch (Exception ex) { pGenerateProgress.GeneratorError(0, 0, string.Format("[{2}] Could not process input file: {0}. Error: {1}", wszInputFilePath, ex.ToString(), this.GetType().Name), 0, 0); } return Microsoft.VisualStudio.VSConstants.S_OK; } #region IObjectWithSite Members public void GetSite(ref Guid riid, out IntPtr ppvSite) { if (this.site == null) { throw new Win32Exception(-2147467259); } IntPtr objectPointer = Marshal.GetIUnknownForObject(this.site); try { Marshal.QueryInterface(objectPointer, ref riid, out ppvSite); if (ppvSite == IntPtr.Zero) { throw new Win32Exception(-2147467262); } } finally { if (objectPointer != IntPtr.Zero) { Marshal.Release(objectPointer); objectPointer = IntPtr.Zero; } } } public void SetSite(object pUnkSite) { this.site = pUnkSite; } #endregion public abstract string GetDefaultFileExtension(); public int DefaultExtension(out string pbstrDefaultExtension) { pbstrDefaultExtension = this.GetDefaultFileExtension(); if (!string.IsNullOrWhiteSpace(pbstrDefaultExtension)) { return Microsoft.VisualStudio.VSConstants.S_OK; } else { return Microsoft.VisualStudio.VSConstants.S_FALSE; } } } }
using System.Collections.Generic; using NHibernate; using Profiling2.Domain.Contracts.Queries; using Profiling2.Domain.Prf.Events; using SharpArch.NHibernate; namespace Profiling2.Infrastructure.Queries { public class EventQueries : NHibernateQuery, IEventQueries { public IList<Event> GetUnapprovedEvents() { return this.Session.QueryOver<Event>() .WhereRestrictionOn(x => x.EventApprovals).IsEmpty .List<Event>(); } public IList<Event> GetAllEvents(ISession session) { ISession thisSession = session == null ? Session : session; return thisSession.QueryOver<Event>().List(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Telephony { interface ISmartphone { public string Call(string number); public string BrowseWeb(string website); } }
namespace ListenerDemo { public class GetWeather { public string ConstructQuery(IWeatherBuilder weatherBuilder, string city, string unit) { return weatherBuilder.GetWeather(Properties.Resources.forecastCall, Properties.Resources.apiKey, city, unit); } } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace Office2007Renderer.ThemedControls { [System.Drawing.ToolboxBitmapAttribute(typeof(System.Windows.Forms.Button)), ToolboxItem(false)] public class ThemedButton : AC.StdControls.Toolkit.Buttons.CustomButton { public ThemedButton() { // Set the SystemEvents class to receive event notification when a user // preference changes, the palette changes, or when display settings change. SetStyle(ControlStyles.OptimizedDoubleBuffer, true); ToolStripManager.RendererChanged += new EventHandler(ToolStripManager_RendererChanged); InitColors(); ToolStripManager_RendererChanged(this, new EventArgs() ); } private void InitColors() { try //myCustom Renderer { Office2007Renderer renderer = (Office2007Renderer)ToolStripManager.Renderer; ProfessionalColorTable _colorTable = (ProfessionalColorTable)renderer.ColorTable; //Set Colors GradientTop = _colorTable.ToolStripGradientBegin; GradientBottom = _colorTable.ToolStripGradientMiddle; GradientBorderColor = _colorTable.ToolStripBorder; if (GradientBorderColor == Color.White) GradientBorderColor = Color.LightGray; this.ForeColor = _colorTable.MenuItemText; HotForeColor = _colorTable.MenuItemText; PressedForeColor = _colorTable.MenuItemText; } catch (Exception ex) { try { System.Windows.Forms.ToolStripProfessionalRenderer renderer = (System.Windows.Forms.ToolStripProfessionalRenderer)ToolStripManager.Renderer; System.Windows.Forms.ProfessionalColorTable _colorTable = (System.Windows.Forms.ProfessionalColorTable)renderer.ColorTable; //Set Colors GradientTop = _colorTable.ToolStripGradientBegin; GradientBottom = _colorTable.ToolStripGradientMiddle; GradientBorderColor = _colorTable.ToolStripBorder; if (GradientBorderColor == Color.White) GradientBorderColor = Color.LightGray; this.ForeColor = _colorTable.SeparatorDark; HotForeColor = _colorTable.SeparatorDark; PressedForeColor = _colorTable.SeparatorDark; } catch (Exception ex3) { Console.WriteLine(ex3.Message); } Console.WriteLine(ex.Message); } } protected override void OnCreateControl() { base.OnCreateControl(); try { InitColors(); } catch { } } void ToolStripManager_RendererChanged(object sender, EventArgs e) { InitColors(); this.Invalidate(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Автошкола { public partial class TheoryTeachersScheduleForm : Form { public TheoryTeachersScheduleForm() { InitializeComponent(); } public BusinessLogic BusinessLogic = new BusinessLogic(); AutoschoolDataSet dataSet, dataSetForTheoryTeachers; bool FormLoad = false; void ReloadTheoryTeachersSchedule(int TeacherID) { dataSet = BusinessLogic.GetTheoryTeacherSchedule(TeacherID); TheoryTeachersSchedule_dGV.DataSource = dataSet; TheoryTeachersSchedule_dGV.DataMember = "TheoryLessons"; TheoryTeachersSchedule_dGV.Columns["ID"].Visible = false; TheoryTeachersSchedule_dGV.Columns["Date"].Visible = false; TheoryTeachersSchedule_dGV.Columns["Time"].Visible = false; TheoryTeachersSchedule_dGV.Columns["Auditorium"].Visible = false; TheoryTeachersSchedule_dGV.Columns["Group"].Visible = false; IDColumn.DataPropertyName = "ID"; TheoryDateColumn.DataPropertyName = "Date"; TheoryTimeColumn.DataPropertyName = "Time"; AuditoriumColumn.DataSource = dataSet.Auditoriums; AuditoriumColumn.DisplayMember = "Name"; AuditoriumColumn.ValueMember = "ID"; AuditoriumColumn.DataPropertyName = "Auditorium"; GroupColumn.DataSource = dataSet.Groups; GroupColumn.DisplayMember = "Name"; GroupColumn.ValueMember = "ID"; GroupColumn.DataPropertyName = "Group"; } private void TheoryTeachersScheduleForm_FormClosing(object sender, FormClosingEventArgs e) { MainForm.Perem(MainForm.FormsNames[16], false); } private void SelectedTheoryTeacher_comboBox_SelectedIndexChanged(object sender, EventArgs e) { if (SelectedTheoryTeacher_comboBox.SelectedIndex != -1 && FormLoad) { int TeacherID = Convert.ToInt32(SelectedTheoryTeacher_comboBox.SelectedValue); ReloadTheoryTeachersSchedule(TeacherID); } } private void Close_button_Click(object sender, EventArgs e) { Close(); } private void ReloadTeachers_button_Click(object sender, EventArgs e) { FormLoad = false; string temp = ""; if (SelectedTheoryTeacher_comboBox.SelectedValue != null) temp = SelectedTheoryTeacher_comboBox.SelectedValue.ToString(); dataSetForTheoryTeachers = BusinessLogic.ReadTheoryTeachers(); SelectedTheoryTeacher_comboBox.DataSource = dataSetForTheoryTeachers.TheoryTeachers; SelectedTheoryTeacher_comboBox.DisplayMember = "FIO"; SelectedTheoryTeacher_comboBox.ValueMember = "ID"; SelectedTheoryTeacher_comboBox.AutoCompleteSource = AutoCompleteSource.ListItems; SelectedTheoryTeacher_comboBox.AutoCompleteMode = AutoCompleteMode.Append; FormLoad = true; if (temp != "") { try { SelectedTheoryTeacher_comboBox.SelectedValue = temp; } catch { SelectedTheoryTeacher_comboBox.SelectedIndex = -1; } } else { SelectedTheoryTeacher_comboBox.SelectedIndex = -1; } } private void TheoryTeachersScheduleForm_Load(object sender, EventArgs e) { dataSetForTheoryTeachers = BusinessLogic.ReadTheoryTeachers(); SelectedTheoryTeacher_comboBox.DataSource = dataSetForTheoryTeachers.TheoryTeachers; SelectedTheoryTeacher_comboBox.DisplayMember = "FIO"; SelectedTheoryTeacher_comboBox.ValueMember = "ID"; SelectedTheoryTeacher_comboBox.SelectedIndex = -1; SelectedTheoryTeacher_comboBox.AutoCompleteSource = AutoCompleteSource.ListItems; SelectedTheoryTeacher_comboBox.AutoCompleteMode = AutoCompleteMode.Append; FormLoad = true; } } }
using System.Collections.Generic; public interface ILineParser { void Parse(string line, out string name, out IDictionary<string, string> args); }
using PiwoBack.Data.DTOs; using PiwoBack.Data.Models; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace PiwoBack.Services.Interfaces { public interface IUserService { IEnumerable<UserDto> GetAll(); UserDto GetUser(int id); UserDto GetBy(Expression<Func<User, bool>> expression); } }
using BookStorage.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Entity; using System.Data; namespace BookStorage.Controllers { public class BooksController : Controller { BookContext dbBooks = new BookContext(); // GET: Books public ActionResult Index() { var books = dbBooks.Books.Include(a => a.Author); return View(books.ToList()); } // GET: Books/Details/5 public ActionResult Details(int? id) { if (id == null) { return HttpNotFound(); } Book bookDetails = dbBooks.Books.Include(a => a.Author).Where(a => a.AuthorId == id).Single(); return View(bookDetails); } // GET: Books/Create public ActionResult Create() { Book books = new Book(); return View(books); } // POST: Books/Create [HttpPost] public ActionResult Create(Book book) { try { if (ModelState.IsValid) { dbBooks.Books.Add(book); dbBooks.SaveChanges(); return RedirectToAction("Index"); } } catch (DataException) { //Log the error (add a variable name after DataException) ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(book); } // GET: Books/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return HttpNotFound(); } Book bookEdit = dbBooks.Books.Include(a => a.Author).Where(a => a.AuthorId == id).Single(); return View(bookEdit); } // POST: Books/Edit/5 [HttpPost] public ActionResult Edit(Book book) { try { if (ModelState.IsValid) { // TODO: Add update logic here dbBooks.Entry(book).State = EntityState.Modified; dbBooks.SaveChanges(); return RedirectToAction("Index"); } } catch (DataException) { //Log the error (add a variable name after DataException) ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(book); } // GET: Books/Delete/5 public ActionResult Delete(int id, bool? saveChangesError) { if (saveChangesError.GetValueOrDefault()) { ViewBag.ErrorMessage = "Unable to save changes. Try again, and if the problem persists see your system administrator."; } return View(dbBooks.Books.Include(a => a.Author).Where(a => a.AuthorId == id).Single()); } // POST: Books/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { try { Book book = dbBooks.Books.Find(id); dbBooks.Books.Remove(book); dbBooks.SaveChanges(); } catch (DataException) { //Log the error (add a variable name after DataException) return RedirectToAction("Delete", new System.Web.Routing.RouteValueDictionary { { "id", id }, { "saveChangesError", true } }); } return RedirectToAction("Index"); } } }
using System.Windows; namespace WpfAppParking.View { public partial class DetailPlaatsenWindow : Window { public DetailPlaatsenWindow() { InitializeComponent(); } } }
using CurriculumManagement.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Configuration; using System.Web.Mvc; namespace CurriculumManagement.Controllers { public class HomeController : Controller { //[CustomAuthorize(Roles = "Program Assistant,Admin,Curriculum Materials Coordinator")] public ActionResult Index() { // Get the Web application configuration. //System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/aspnetTest"); //// Get the external Authentication section. //AuthenticationSection authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication"); //// Get the external Forms section . //FormsAuthenticationConfiguration formsAuthentication = authenticationSection.Forms; //ViewBag.LoginURL = formsAuthentication.LoginUrl + "?TARGET=" + Server.HtmlEncode(Request.Url.AbsoluteUri); return View(); } public ActionResult Contact() { ViewBag.Message = "For assistance, please contact technical support below:"; return View(); } } }
using System; using NHibernate.Envers; using System.Threading; namespace Profiling2.Domain { [Serializable] public class RevinfoListener : IRevisionListener { public void NewRevision(object revisionEntity) { REVINFO revinfo = (REVINFO)revisionEntity; revinfo.UserName = Thread.CurrentPrincipal.Identity.Name; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIController : MonoBehaviour { private Text _timerText; private static float _timer; private GameController _gameController; // Start is called before the first frame update void Start() { _timerText = GameObject.Find("TimerTextObject").GetComponent<Text>(); _gameController = GameObject.Find("GameController").GetComponent<GameController>(); } // Update is called once per frame void Update() { if (!_gameController.startGame) return; _timer += Time.deltaTime; string minutes = Mathf.Floor(_timer / 60).ToString("00"); string seconds = (_timer % 60).ToString("00"); _timerText.text = string.Format("{0}:{1}", minutes, seconds); } }
using System; using System.Linq; using System.Text; using Boxofon.Web.Infrastructure; using Nancy.ViewEngines.Razor; namespace Boxofon.Web.Helpers { public static class HtmlHelperExtensions { public static IHtmlString AlertMessages<TModel>(this HtmlHelpers<TModel> htmlHelper) { const string message = @"<div class=""alert alert-{0}"">{1}</div>"; var alertsDynamicValue = htmlHelper.RenderContext.Context.ViewBag.Alerts; var alerts = (AlertMessageStore)(alertsDynamicValue.HasValue ? alertsDynamicValue.Value : null); if (alerts == null || !alerts.Messages.Any()) { return new NonEncodedHtmlString(String.Empty); } var builder = new StringBuilder(); foreach (var messageDetail in alerts.Messages) { builder.AppendFormat(message, messageDetail.Key, messageDetail.Value); } return new NonEncodedHtmlString(builder.ToString()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Mr_T; using ARPG.Charater; namespace ARPG.Skill { [SerializeField] /// <summary> /// 技能管理器 /// </summary> public class ChacracterSkillManager : MonoBehaviour { //技能列表 public SkillData[] skills; private void Start() { for (int i = 0; i < skills.Length; i++) InitSkill(skills[i]); } /// <summary> /// 技能初始化 /// </summary> /// <param name="data"></param> private void InitSkill(SkillData data) { /* * 资源映射表 * 资源名称----->资源完整路径 */ //data.prefab -->data.skillPrefab //根据资源名称获取资源预制件 data.skillPrefab = ResourceManager.Load<GameObject>(data.prefabName); data.owner = gameObject; } //技能释放条件:冷却、法力 public SkillData PrepareSkill(int id) { //根据ID查找技能数据 SkillData skillData = FindSkill(id); //获取当前角色法力 float sp = GetComponent<CharacterStatus>().SP; //判断条件返回数据---->技能不为空、技能冷却时间为0、蓝量够 if (skillData != null && skillData.coolRemain <= 0 && skillData.costSP <= sp) return skillData; else return null; } /// <summary> /// 根据编号查询技能 /// </summary> /// <param name="id"></param> /// <returns></returns> private SkillData FindSkill(int id) { for (int i = 0; i < skills.Length; i++) { if (skills[i].skillID == id) { return skills[i]; } } return null; } //生成技能 public void GenerateSkill(SkillData data) { //实例化一个技能 // GameObject skillGo = Instantiate(data.skillPrefab, transform.position, transform.rotation); GameObject skillGo = GameObjectPool.Instance.CreatObject(data.skillName, data.skillPrefab, transform.position, transform.rotation); //传递技能数据 SkillDeployer deployer = skillGo.GetComponent<SkillDeployer>(); deployer.SkillData = data; //根据技能持续时间然后销毁 // Destroy(skillGo, data.durationTime); GameObjectPool.Instance.CollectObject(skillGo, data.durationTime); //开启技能冷却 StartCoroutine(CoolTimeDown(data)); } /// <summary> /// 技能倒计时 /// </summary> private IEnumerator CoolTimeDown(SkillData data) { //技能冷却时间赋值给技能剩余冷却时间 data.coolRemain = data.coolTime; //当技能剩余冷却时间比1大的时候,每秒钟减少一秒冷却时间 while (data.coolRemain > 0) { yield return new WaitForSeconds(1); data.coolRemain--; } } } }
using IWorkFlow.DataBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IWorkFlow.ORM { [Serializable] [DataTableInfo("B_OA_Car", "workflowcaseid")] public class B_OA_Car : QueryInfo { #region Model /// <summary> /// 业务ID /// </summary> /// [DataField("workflowcaseid", "B_OA_Car")] public string workflowcaseid { set { _workflowcaseid = value; } get { return _workflowcaseid; } } private string _workflowcaseid; [DataField("applyDepartment", "B_OA_Car")] public string applyDepartment { set { _applyDepartment = value; } get { return _applyDepartment; } } private string _applyDepartment; [DataField("applyDepartmentId", "B_OA_Car")] public string applyDepartmentId { set { _applyDepartmentId = value; } get { return _applyDepartmentId; } } private string _applyDepartmentId; [DataField("strartTime", "B_OA_Car")] public string strartTime { set { _strartTime = value; } get { return _strartTime; } } private string _strartTime; [DataField("endTime", "B_OA_Car")] public string endTime { set { _endTime = value; } get { return _endTime; } } private string _endTime; [DataField("strarDestination", "B_OA_Car")] public string strarDestination { set { _strarDestination = value; } get { return _strarDestination; } } private string _strarDestination; [DataField("endDestination", "B_OA_Car")] public string endDestination { set { _endDestination = value; } get { return _endDestination; } } private string _endDestination; [DataField("travelReson", "B_OA_Car")] public string travelReson { set { _travelReson = value; } get { return _travelReson; } } private string _travelReson; [DataField("personList", "B_OA_Car")] public string personList { set { _personList = value; } get { return _personList; } } private string _personList; [DataField("personListId", "B_OA_Car")] public string personListId { set { _personListId = value; } get { return _personListId; } } private string _personListId; [DataField("useMan", "B_OA_Car")] public string useMan { set { _useMan = value; } get { return _useMan; } } private string _useMan; [DataField("useManId", "B_OA_Car")] public string useManId { set { _useManId = value; } get { return _useManId; } } private string _useManId; [DataField("useManPhone", "B_OA_Car")] public string useManPhone { set { _useManPhone = value; } get { return _useManPhone; } } private string _useManPhone; [DataField("diverMan", "B_OA_Car")] public string diverMan { set { _diverMan = value; } get { return _diverMan; } } private string _diverMan; [DataField("carName", "B_OA_Car")] public string carName { set { _carName = value; } get { return _carName; } } private string _carName; [DataField("useDepSign", "B_OA_Car")] public string useDepSign { set { _useDepSign = value; } get { return _useDepSign; } } private string _useDepSign; [DataField("remark", "B_OA_Car")] public string remark { set { _remark = value; } get { return _remark; } } private string _remark; [DataField("CreatTime", "B_OA_Car")] public DateTime? CreatTime { set { _CreatTime = value; } get { return _CreatTime; } } private DateTime? _CreatTime; [DataField("diverManId", "B_OA_Car")] public string diverManId { set { _diverManId = value; } get { return _diverManId; } } private string _diverManId; [DataField("carId", "B_OA_Car")] public string carId { set { _carId = value; } get { return _carId; } } private string _carId; #endregion Model } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; namespace NetOffice.ProjectWizard { public class LibraryProject : NetOfficeProject { #region Fields string _createClassicUIMethodCode; string _removeClassicUIMethodCode; string _createClassicUICallCode; string _removeClassicUICallCode; #endregion #region Properties public string CreateClassicUIMethodCode { get { if (null == _createClassicUIMethodCode) { if (TargetProgrammLanguage == TargetProgrammingLanguage.CSharp) _createClassicUIMethodCode = ReadString("CreateClassicUIMethodCSharp.txt"); else _createClassicUIMethodCode = ReadString("CreateClassicUIMethodVisualBasic.txt"); } return _createClassicUIMethodCode; } } public string RemoveClassicUIMethodCode { get { if (null == _removeClassicUIMethodCode) { if (TargetProgrammLanguage == TargetProgrammingLanguage.CSharp) _removeClassicUIMethodCode = ReadString("RemoveClassicUIMethodCSharp.txt"); else _removeClassicUIMethodCode = ReadString("RemoveClassicUIVisualBasic.txt"); } return _removeClassicUIMethodCode; } } public string CreateClassicUICallCode { get { if (null == _createClassicUICallCode) { if (TargetProgrammLanguage == TargetProgrammingLanguage.CSharp) _createClassicUICallCode = ReadString("CreateUICallCodeCSharp.txt"); else _createClassicUICallCode = ReadString("CreateUICallCodeVisualBasic.txt"); } return _createClassicUICallCode; } } public string RemoveClassicUICallCode { get { if (null == _removeClassicUICallCode) { if (TargetProgrammLanguage == TargetProgrammingLanguage.CSharp) _removeClassicUICallCode = ReadString("RemoveUICallCodeCSharp.txt"); else _removeClassicUICallCode = ReadString("RemoveUICallCodeVisualBasic.txt"); } return _removeClassicUICallCode; } } #endregion #region Methods #endregion #region Overrides internal override void FinishAction() { _addDictionary.Clear(); _addDictionary.Add("$assemblyGuid$", Guid.NewGuid().ToString()); string usingItems = GetDefaultUsings(); foreach (XmlNode item in (ListControls[0] as IWizardControl).SettingsDocument.FirstChild.ChildNodes) { if (item.Attributes[0].Value.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)) { if (item.Name == "Project") usingItems += UsingCode.Replace("%Name%", "MS" + item.Name); else usingItems += UsingCode.Replace("%Name%", item.Name); } } _addDictionary.Add("$usingItems$", usingItems); SetAssemblyReferences(); } protected internal void RunStarted(Dictionary<string, string> replacementsDictionary, TargetProgrammingLanguage targetProgrammingLanguage, TargetProjectType projectType) { _targetProgrammingLanguage = targetProgrammingLanguage; _targetProjectType = projectType; _replacementsDictionary = replacementsDictionary; _projectFolder = replacementsDictionary["$destinationdirectory$"]; _targetRuntime = replacementsDictionary["$targetframeworkversion$"]; HostControl hostControl = new HostControl(); NameControl nameControl = new NameControl(); SummaryControl sumControl = new SummaryControl(this); ListControls.Add(hostControl); ListControls.Add(nameControl); ListControls.Add(sumControl); WizardDialog dialog = new WizardDialog(this); dialog.ShowDialog(); _neededNetOfficeAssemblies = this.NeededAssemblies; foreach (KeyValuePair<string, string> item in this.AddDictionary) replacementsDictionary.Add(item.Key, item.Value); } internal override string Name { get { return "Console Project"; } } #endregion } }
using System; using System.Collections.Generic; using System.Data; namespace MadamRozikaPanel.BussinesLayer { /// <summary> /// Summary description for GalleryOperations /// </summary> public class O_Gallery { public List<M_Galleries> GetAllGalleries(int top) { List<M_Galleries> lst = new List<M_Galleries>(); DataTable dt = new DataTable(); Execute Exec = new Execute(DatabaseType.DBType1); dt = Exec.ExecuteQuery<DataTable>("SELECT TOP " + top + " * FROM Gallery ORDER BY GalleryId DESC", 0, CommandType.Text); foreach (DataRow dr in dt.Rows) { M_Galleries G = new M_Galleries(dr); lst.Add(G); } return lst; } public List<M_Galleries> GetAllGalleryListWithCondition(int top, string condition) { List<M_Galleries> lst = new List<M_Galleries>(); DataTable dt = new DataTable(); Execute Exec = new Execute(DatabaseType.DBType1); dt = Exec.ExecuteQuery<DataTable>("SELECT TOP " + top + " * FROM Gallery WHERE " + condition + " ORDER BY GalleryId DESC", 0, CommandType.Text); foreach (DataRow dr in dt.Rows) { M_Galleries G = new M_Galleries(dr); lst.Add(G); } return lst; } /// <summary> /// Panelde listelenen haberler için Edit sayfasına gitmeden başlık, spot, kategori, durum ve konum gibi bilgileri günceller /// </summary> /// <param name="title">String türünde data (haber başlığı)</param> /// <param name="summary">String türünde data (haber spotu)</param> /// <param name="categoryId">int türünde data (haber kategori id'si)</param> /// <param name="status">int türünde data (haber statüs'ü)</param> /// <param name="newsType">int türünde data (haber konumu) Veritabanında bir tabloda tutulmuyor, kod içerisinde manuel olarak eklenmiştir. Kutu Haber = 0, Manşet = 1, Sürmanşet = 2, Süper Manşet = 3, Üst Süper Manşet = 4, Seo = 5, Manşet Üstü Süper = 6</param> /// <param name="newsId">int türünde data (haber id'si)</param> public void UpdateGallery(string title, int categoryId, int status, int GalleryId) { Execute Exec = new Execute(DatabaseType.DBType1); Exec.ExecuteQuery("UPDATE Gallery SET Title='" + title + "', CategoryId=" + categoryId + ", Status=" + status + " WHERE GalleryId=" + GalleryId, 0, CommandType.Text); } public M_Galleries GalleryDetail(int GalleryId) { Execute Exec = new Execute(DatabaseType.DBType1); M_Galleries G = new M_Galleries(Exec.ExecuteQuery<DataRow>("SELECT * FROM Gallery WHERE GalleryId = " + GalleryId, 0, CommandType.Text)); return G; } public DataTable FillDropDownList() { DataTable dt = new DataTable(); Execute Exec = new Execute(DatabaseType.DBType1); dt = Exec.ExecuteQuery<DataTable>("SELECT Name, CategoryId FROM Category where ParentId = 0 AND Status = 1 ORDER BY Name", 3600, CommandType.Text); return dt; } public string InsertGallery(int CategoryId, string Title, int Type, int Status, string GalleryUrl) { Execute Exec = new Execute(DatabaseType.DBType1); string dsda = "INSERT INTO Gallery (CategoryId, Title, Type, PublishDate, Status, GalleryUrl) VALUES (" + CategoryId + ",'" + Title + "', " + Type + ", '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', " + Status + ", '" + GalleryUrl + "')"; Exec.ExecuteQuery("INSERT INTO Gallery (CategoryId, Title, Type, PublishDate, Status, GalleryUrl) VALUES (" + CategoryId + ",'" + Title + "', " + Type + ", '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', " + Status + ", '" + GalleryUrl + "')", 0, CommandType.Text); DataRow dr = Exec.ExecuteQuery<DataRow>("SELECT MAX(GalleryId) as MaxId FROM Gallery", 0, CommandType.Text); return dr["MaxId"].ToString(); } public string UpdateGallery(int CategoryId, string Title, int Type, int Status, string GalleryUrl,string GalleryId) { Execute Exec = new Execute(DatabaseType.DBType1); Exec.ExecuteQuery("UPDATE Gallery SET CategoryId=" + CategoryId + ", Title='" + Title + "', Type= " + Type + ", Status=" + Status + ", GalleryUrl='" + GalleryUrl + "' WHERE GalleryId=" + GalleryId, 0, CommandType.Text); DataRow dr = Exec.ExecuteQuery<DataRow>("SELECT MAX(GalleryId) as MaxId FROM Gallery", 0, CommandType.Text); return dr["MaxId"].ToString(); } public static void InsertGalleryItems(string sql) { Execute Exec = new Execute(DatabaseType.DBType1); Exec.ExecuteQuery(sql, 0, CommandType.Text); } } }
// Copyright 2011-2013 Anodyne. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Kostassoid.Anodyne.Domain.DataAccess { using System; using System.Linq; using Abstractions.DataAccess; using Common; using Common.CodeContracts; using Common.ExecutionContext; using Common.Reflection; using Base; using Events; using Exceptions; using Operations; using Policy; using Domain.Events; using Wiring; public class UnitOfWork : IUnitOfWorkEx, IDisposable { private const string HeadContextKey = "head-unit-of-work"; private static IDataSessionFactory _dataSessionFactory; private static IOperationResolver _operationResolver; private static DataAccessPolicy _policy = new DataAccessPolicy(); private static bool _eventHandlersAreSet; private readonly string _contextKey = HeadContextKey; private readonly UnitOfWork _parent; public IDomainDataSession DomainDataSession { get; protected set; } private readonly StaleDataPolicy _staleDataPolicy = StaleDataPolicy.Strict; public static Option<UnitOfWork> Current { get { return Context.FindAs<UnitOfWork>(HeadContextKey); } protected set { Context.Set(HeadContextKey, value.ValueOrDefault); } } public bool IsRoot { get { return _parent == null; } } public bool IsFinished { get; protected set; } public bool IsDisposed { get { return Context.Find(_contextKey).IsNone; } } public static bool IsConfigured { get { return _dataSessionFactory != null; } } public static void SetDataSessionFactory(IDataSessionFactory dataSessionFactory) { _dataSessionFactory = dataSessionFactory; } public static void SetOperationResolver(IOperationResolver operationResolver) { _operationResolver = operationResolver; } public static void EnforcePolicy(DataAccessPolicy policy) { _policy = policy; } public UnitOfWork(StaleDataPolicy? staleDataPolicy = null) { lock (HeadContextKey) EnsureAggregateEventHandlersAreSet(); if (Current.IsSome) { _parent = Current.Value; DomainDataSession = _parent.DomainDataSession; _contextKey = String.Format("{0}-{1}", _contextKey, Guid.NewGuid().ToString("N")); } else { DomainDataSession = new DomainDataSession(_dataSessionFactory.Open()); if (DomainDataSession == null) throw new Exception("Unable to create IDataSession (bad configuration?)"); } _staleDataPolicy = staleDataPolicy.HasValue ? staleDataPolicy.Value : _policy.StaleDataPolicy; Context.Set(_contextKey, this); Current = this; IsFinished = false; } protected static void EnsureAggregateEventHandlersAreSet() { if (_eventHandlersAreSet) return; _eventHandlersAreSet = true; EventBus .SubscribeTo() .AllBasedOn<IAggregateEvent>(From.AllAssemblies()) .With(e => { if (_policy.ReadOnly) throw new InvalidOperationException("You can't mutate AggregateRoots in ReadOnly mode."); if (Current.IsSome && !Current.Value.IsFinished) ((UnitOfWork)Current).DomainDataSession.Handle(e); }, Priority.Exact(1000)); } protected void AssertIfFinished() { Assumes.True(!IsFinished, "This UnitOfWork is finished"); } public void Complete() { AssertIfFinished(); IsFinished = true; if (!IsRoot) return; EventBus.Publish(new UnitOfWorkCompletingEvent(this)); var changeSet = DomainDataSession.SaveChanges(_staleDataPolicy); EventBus.Publish(new UnitOfWorkCompletedEvent(this, changeSet)); if (changeSet.StaleDataDetected && _staleDataPolicy == StaleDataPolicy.Strict) throw new StaleDataException(changeSet.StaleData, "Some aggregates weren't saved due to stale data (version mismatch)"); } public void Rollback() { AssertIfFinished(); IsFinished = true; if (!IsRoot) return; DomainDataSession.Rollback(); EventBus.Publish(new UnitOfWorkRollbackEvent(this)); } public virtual void Dispose() { if (IsDisposed) return; try { if (!IsFinished) Complete(); } finally { if (IsRoot) { EventBus.Publish(new UnitOfWorkDisposingEvent(this)); DomainDataSession.Dispose(); } Context.Release(_contextKey); Current = _parent; } } ~UnitOfWork() { if (!IsDisposed) throw new InvalidOperationException("UnitOfWork must be properly disposed!"); } public IRepository<TRoot> Query<TRoot>() where TRoot : class, IAggregateRoot { AssertIfFinished(); return new Repository<TRoot>(DomainDataSession.DataSession); } public IQueryable<TRoot> AllOf<TRoot>() where TRoot : class, IAggregateRoot { AssertIfFinished(); return Query<TRoot>().All(); } public TOp Using<TOp>() where TOp : class, IDomainOperation { AssertIfFinished(); return _operationResolver.Get<TOp>(); } public void MarkAsDeleted<TRoot>(TRoot entity) where TRoot : class, IAggregateRoot { AssertIfFinished(); DomainDataSession.MarkAsDeleted(entity); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class TopicoBehaviour : MonoBehaviour, IPointerDownHandler, IPointerUpHandler{ //Variável que contem a posicao private string id; private bool beenHold = false; private int corretude = 0; //Variável que contem a posição inicial da poção e a próxima private Vector2 defaultSpot; private Vector2 newSpot; private GameObject inContact = null; private bool inTopicContact = false; //Variável que contem a posição inicial e final do movimento da poção private Vector2 homeSpot, targetSpot, deltaSpot; //Variável que contem a velocidade atual private float moveSpeed = 0; private RectTransform rect; private Animator anim; // ************ Get n Set ***************** public void SetId(string id) { this.id = id; } // ************ MonoBehaviour *********************** void Start() { rect = GetComponent<RectTransform>(); anim = GetComponent<Animator>(); defaultSpot = rect.localPosition; } void Update() { if(beenHold) { transform.position = Input.mousePosition; } else if(moveSpeed > 0) { goTo(targetSpot); } } //quero que va para 480 740 // 2708 2084 // ************ Mátodos de Manipulação ******************* // Método que move a poção até um certo lugar private void goTo(Vector2 spot) { moveSpeed += Time.deltaTime * 895; // Duração do movimento atual é 0.2s, para alterar fazer a conta 179 / t (ex: 179/0.2 = 895) if(moveSpeed >= 180) { rect.localPosition = targetSpot; moveSpeed = 0; if(inContact != null) { if(inContact.name.Contains(id)) { if (corretude == 1) return; corretude = 1; SequenciaPanelBehavior.CurrentSequencia.Acertou(); anim.SetTrigger("Certo"); //Acertou } else { if(corretude == 1) SequenciaPanelBehavior.CurrentSequencia.Errou(); anim.SetTrigger("Errado"); corretude = 0; //Errou } } else { if (corretude == 1) SequenciaPanelBehavior.CurrentSequencia.Errou(); corretude = 0; } return; } rect.localPosition = homeSpot + (deltaSpot - deltaSpot * Mathf.Cos(moveSpeed * Mathf.Deg2Rad)) / 2; } public void OnPointerDown(PointerEventData eventData) { beenHold = true; transform.SetAsLastSibling(); } public void OnPointerUp(PointerEventData eventData) { beenHold = false; if (inContact != null) { targetSpot = newSpot; } else { targetSpot = defaultSpot; } homeSpot = rect.localPosition; deltaSpot = targetSpot - homeSpot; moveSpeed = 1; } // Métodos de colisão void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Topico") { inTopicContact = true; } else if(!inTopicContact) { newSpot = collision.gameObject.GetComponent<RectTransform>().localPosition; inContact = collision.gameObject; } } void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.tag == "Topico") { inTopicContact = false; } inContact = null; } }
using Phenix.Business; namespace Phenix.StandardRule.Information { /// <summary> /// 资料接口 /// </summary> public interface IInformation : IBusinessObject { #region 属性 /// <summary> /// 是否禁用 /// </summary> bool Disabled { get; set; } /// <summary> /// 资料状态 /// </summary> InformationStatus InformationStatus { get; } /// <summary> /// 是否需要审核 /// </summary> bool NeedVerify { get; } /// <summary> /// 审核状态 /// </summary> InformationVerifyStatus VerifyStatus { get; } #endregion #region 方法 /// <summary> /// 资料状态发生变化前 /// </summary> /// <param name="e">资料状态变更事件内容</param> void OnInformationStatusChanging(InformationStatusChangingEventArgs e); /// <summary> /// 资料状态发生变化后 /// </summary> /// <param name="e">资料状态变更事件内容</param> void OnInformationStatusChanged(InformationStatusChangedEventArgs e); #endregion } }
using Datos; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Negocio { public class Tarjeta { public int idTarjeta {get;set;} public int codSegTarjeta { get; set; } public long numeroTarjeta { get; set; } public int idTipoTarjeta { get; set; } public int idCliente { get; set; } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Constant of type `GameObject`. Inherits from `AtomBaseVariable&lt;GameObject&gt;`. /// </summary> [EditorIcon("atom-icon-teal")] [CreateAssetMenu(menuName = "Unity Atoms/Constants/GameObject", fileName = "GameObjectConstant")] public sealed class GameObjectConstant : AtomBaseVariable<GameObject> { } }
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Web; namespace RobotWizard { public class GlobalCode { public static Dictionary<string, string[]> ParseArrangeFile(string fileContents) { Dictionary<string, string[]> dicToReturn = new Dictionary<string, string[]>(); string[] items = fileContents.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in items) { string[] variableKeyAndValues = item.Split('='); string key = variableKeyAndValues[0].Trim(); string[] valuesArray = variableKeyAndValues[1].Split(','); dicToReturn.Add(key, valuesArray); } return dicToReturn; } } public static class JavaScriptConvert { public static IHtmlString SerializeObject(object value) { using (var sW = new StringWriter()) using (var jsonWriter = new JsonTextWriter(sW)) { var serializer = new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }; jsonWriter.QuoteName = false; serializer.Serialize(jsonWriter, value); return new HtmlString(sW.ToString()); } } } }