content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Linq; using System.Collections.Generic; using Lol.Foundation.Mvvm; using Lol.Database.Controller; using Lol.Database.Entites.Schema; namespace Lol.Loot.Local.ViewModels { public class LootViewModel : ObservableObject { #region Variables private List<Loots> _menus; private List<LootItemSortings> _filters; private List<PlantHeaders> _treeSource; private List<Loots> _summary; private Loots _currentMenu; private LootItemSortings _currentFilter; #endregion #region Menus public List<Loots> Menus { get => _menus; set { _menus = value; OnPropertyChanged(); } } #endregion #region CurrentMenu public Loots CurrentMenu { get => _currentMenu; set { _currentMenu = value; OnPropertyChanged(); MenuChanged(value.Seq); } } #endregion #region Filters public List<LootItemSortings> Filters { get => _filters; set { _filters = value; OnPropertyChanged(); } } #endregion #region CurrentFilter public LootItemSortings CurrentFilter { get => _currentFilter; set { _currentFilter = value; OnPropertyChanged(); } } #endregion #region TreeSource public List<PlantHeaders> TreeSource { get => _treeSource; set { _treeSource = value; OnPropertyChanged(); } } #endregion #region Summary public List<Loots> Summary { get => _summary; set { _summary = value; OnPropertyChanged(); } } #endregion #region Constructor public LootViewModel() { Menus = new LootApi().GetCategory(); CurrentMenu = Menus.First(); Filters = new LootApi().GetFilters(); CurrentFilter = Filters.First(); Summary = new LootApi().GetLootSummary(); } #endregion #region MenuChanged private void MenuChanged(int seq) { List<PlantHeaders> source = new LootApi().GetPlantHeaders(); if (seq != 0) { source = source.Where(x => x.LootSeq == seq).ToList(); } TreeSource = source; } #endregion } }
23.122642
86
0.545492
[ "MIT" ]
devncore-james/wpf-leagueoflegends
src/Lol.Loot/Local/ViewModels/LootViewModel.cs
2,453
C#
using System; namespace Backup_Practice { public class DoesnotContainOnlyLettersException : ApplicationException { private string _message; public DoesnotContainOnlyLettersException() { _message = "Word doesn't contain only letters."; } public DoesnotContainOnlyLettersException(in string message) { if (String.IsNullOrWhiteSpace(message)) _message = "Word doesn't contain only letters."; else _message = message; } public override string Message => _message; } }
26.291667
75
0.594295
[ "MIT" ]
Limitless-Rasul-Power/Transfer-Data
Backup Practice/DoesnotContainOnlyLettersException.cs
633
C#
using DatingApp.API.Models; using Microsoft.EntityFrameworkCore; namespace DatingApp.API.Data { public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options): base(options){} public DbSet<Value> Values { get; set; } public DbSet<User> Users { get; set; } public DbSet<Photo> Photos { get; set; } public DbSet<Like> Likes { get; set; } public DbSet<Message> Messages { get; set; } protected override void OnModelCreating(ModelBuilder builder){ builder.Entity<Like>() .HasKey(k => new {k.LikerId, k.LikeeId}); builder.Entity<Like>() .HasOne(u => u.Likee) .WithMany(u => u.Likers) .HasForeignKey(u => u.LikeeId) .OnDelete(DeleteBehavior.Restrict); builder.Entity<Like>() .HasOne(u => u.Liker) .WithMany(u => u.Likees) .HasForeignKey(u => u.LikerId) .OnDelete(DeleteBehavior.Restrict); builder.Entity<Message>() .HasOne(u => u.Sender) .WithMany(m => m.MessagesSent) .OnDelete(DeleteBehavior.Restrict); builder.Entity<Message>() .HasOne(u => u.Recipient) .WithMany(m => m.MessagesRecived) .OnDelete(DeleteBehavior.Restrict); } } }
34.333333
82
0.545076
[ "MIT" ]
Fractal-Technology/dateNow
DateNow.API/DatingApp.API/Data/DataContext.cs
1,442
C#
using Microsoft.AspNetCore.Mvc; using NHibernate; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TrnNHibernate.Api.Core.Requests; using TrnNHibernate.Entidades; namespace TrnNHibernate.Api.Controllers { [Route("produto")] public class ProductController : ControllerBase { private readonly ISession _session; public ProductController(ISession session) { _session = session; } [HttpPost] [Route("novo")] public IActionResult NovoProduto([FromBody] ProdutoRequest produtoRequest) { var produto = new Produto(produtoRequest.Nome, produtoRequest.PrecoUnitario, produtoRequest.QuantidadeEstoque); _session.Save(produto); return Ok("Cliente gravado com sucesso"); } [HttpPost] [Route("atualizar")] public IActionResult AtualizarProduto([FromBody] ProdutoRequest produtoRequest) { using (ITransaction transaction = _session.BeginTransaction()) { var produtoExistente = _session.Get<Produto>(produtoRequest.Id); produtoExistente.Atualizar(produtoRequest.Nome, produtoRequest.PrecoUnitario, produtoRequest.QuantidadeEstoque); _session.Update(produtoExistente); transaction.Commit(); } return Ok("Produto atualizado com sucesso"); } [HttpGet] [Route("{id}")] public IActionResult RecuperarProduto(int id) { var produto = _session.Get<Produto>(id); return Ok(produto); } } }
31.055556
128
0.635659
[ "MIT" ]
FelipeCabralz/trn-nhibernate
src/TrnNHibernate/TrnNHibernate.Api/Controllers/ProductController.cs
1,679
C#
using System; namespace LivestreamBot.Livestream.Events { public static class LivestreamEventExtensions { public static (TimeSpan untilNext, bool isOngoing) GetLivestreamEventInfo(this LivestreamEvent @event, DateTime dateTime) { var nextStart = @event.GetNext(dateTime); var previousStart = nextStart.AddDays(-7); var untilNext = nextStart - dateTime; var isOngoing = previousStart + @event.LivestreamEventDuration > dateTime; return (untilNext, isOngoing); } public static DateTime GetNext(this LivestreamEvent @event, DateTime dateTime) { var daysDiff = @event.DayOfWeek - dateTime.DayOfWeek; var nextStart = dateTime.Date.AddDays(daysDiff) + @event.LivestreamEventStart; if (nextStart < dateTime) { // earlier on the same Date nextStart = nextStart.AddDays(7); } return nextStart; } } }
30.117647
130
0.612305
[ "MIT" ]
SamuelKupferschmid/livestream-bot
src/LivestreamBot/LivestreamBot.Livestream/Events/LivestreamEventExtensions.cs
1,026
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Nito.AsyncEx; using NUnit.Framework; using SJP.Schematic.Core; using SJP.Schematic.Core.Comments; using SJP.Schematic.Core.Extensions; using SJP.Schematic.PostgreSql.Comments; using SJP.Schematic.Tests.Utilities; namespace SJP.Schematic.PostgreSql.Tests.Integration.Comments { internal sealed class PostgreSqlQueryViewCommentProviderTests : PostgreSqlTest { private IDatabaseViewCommentProvider ViewCommentProvider => new PostgreSqlQueryViewCommentProvider(DbConnection, IdentifierDefaults, IdentifierResolver); [OneTimeSetUp] public async Task Init() { await DbConnection.ExecuteAsync("create table view_comment_table_1 (test_column_1 int primary key not null, test_column_2 int, test_column_3 int)", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create view view_comment_view_1 as select test_column_1, test_column_2, test_column_3 from view_comment_table_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("create view view_comment_view_2 as select test_column_1, test_column_2, test_column_3 from view_comment_table_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("comment on view view_comment_view_2 is 'This is a test view.'", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("comment on column view_comment_view_2.test_column_2 is 'This is a test view column.'", CancellationToken.None).ConfigureAwait(false); } [OneTimeTearDown] public async Task CleanUp() { await DbConnection.ExecuteAsync("drop view view_comment_view_1", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop view view_comment_view_2", CancellationToken.None).ConfigureAwait(false); await DbConnection.ExecuteAsync("drop table view_comment_table_1", CancellationToken.None).ConfigureAwait(false); } private Task<IDatabaseViewComments> GetViewCommentsAsync(Identifier viewName) { if (viewName == null) throw new ArgumentNullException(nameof(viewName)); return GetViewCommentsAsyncCore(viewName); } private async Task<IDatabaseViewComments> GetViewCommentsAsyncCore(Identifier viewName) { using (await _lock.LockAsync().ConfigureAwait(false)) { if (!_commentsCache.TryGetValue(viewName, out var lazyComment)) { lazyComment = new AsyncLazy<IDatabaseViewComments>(() => ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync()); _commentsCache[viewName] = lazyComment; } return await lazyComment.ConfigureAwait(false); } } private readonly AsyncLock _lock = new(); private readonly Dictionary<Identifier, AsyncLazy<IDatabaseViewComments>> _commentsCache = new(); [Test] public async Task GetViewComments_WhenViewPresent_ReturnsViewComment() { var viewIsSome = await ViewCommentProvider.GetViewComments("view_comment_view_1").IsSome.ConfigureAwait(false); Assert.That(viewIsSome, Is.True); } [Test] public async Task GetViewComments_WhenViewPresent_ReturnsViewWithCorrectName() { const string viewName = "view_comment_view_1"; var viewComments = await ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(viewComments.ViewName.LocalName, Is.EqualTo(viewName)); } [Test] public async Task GetViewComments_WhenViewPresentGivenLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("view_comment_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var viewComments = await ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(viewComments.ViewName, Is.EqualTo(expectedViewName)); } [Test] public async Task GetViewComments_WhenViewPresentGivenSchemaAndLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Schema, "view_comment_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var viewComments = await ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(viewComments.ViewName, Is.EqualTo(expectedViewName)); } [Test] public async Task GetViewComments_WhenViewPresentGivenDatabaseAndSchemaAndLocalNameOnly_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var viewComments = await ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(viewComments.ViewName, Is.EqualTo(expectedViewName)); } [Test] public async Task GetViewComments_WhenViewPresentGivenFullyQualifiedName_ShouldBeQualifiedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var viewComments = await ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(viewComments.ViewName, Is.EqualTo(viewName)); } [Test] public async Task GetViewComments_WhenViewPresentGivenFullyQualifiedNameWithDifferentServer_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("A", IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var viewComments = await ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(viewComments.ViewName, Is.EqualTo(expectedViewName)); } [Test] public async Task GetViewComments_WhenViewPresentGivenFullyQualifiedNameWithDifferentServerAndDatabase_ShouldBeQualifiedCorrectly() { var viewName = new Identifier("A", "B", IdentifierDefaults.Schema, "view_comment_view_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var viewComments = await ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(viewComments.ViewName, Is.EqualTo(expectedViewName)); } [Test] public async Task GetViewComments_WhenViewPresentGivenDifferenceCaseName_ShouldBeResolvedCorrectly() { var viewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "VIEW_COMMENT_VIEW_1"); var expectedViewName = new Identifier(IdentifierDefaults.Server, IdentifierDefaults.Database, IdentifierDefaults.Schema, "view_comment_view_1"); var viewComments = await ViewCommentProvider.GetViewComments(viewName).UnwrapSomeAsync().ConfigureAwait(false); Assert.That(viewComments.ViewName, Is.EqualTo(expectedViewName)); } [Test] public async Task GetViewComments_WhenViewMissing_ReturnsNone() { var viewIsNone = await ViewCommentProvider.GetViewComments("view_that_doesnt_exist").IsNone.ConfigureAwait(false); Assert.That(viewIsNone, Is.True); } [Test] public async Task GetAllViewComments_WhenEnumerated_ContainsViewComments() { var hasViewComments = await ViewCommentProvider.GetAllViewComments() .AnyAsync() .ConfigureAwait(false); Assert.That(hasViewComments, Is.True); } [Test] public async Task GetAllViewComments_WhenEnumerated_ContainsTestViewComment() { var containsTestView = await ViewCommentProvider.GetAllViewComments() .AnyAsync(v => string.Equals(v.ViewName.LocalName, "view_comment_view_1", StringComparison.Ordinal)) .ConfigureAwait(false); Assert.That(containsTestView, Is.True); } [Test] public async Task GetViewComments_WhenViewMissingComment_ReturnsNone() { var comments = await GetViewCommentsAsync("view_comment_view_1").ConfigureAwait(false); Assert.That(comments.Comment.IsNone, Is.True); } [Test] public async Task GetViewComments_WhenViewMissingColumnComments_ReturnsLookupKeyedWithColumnNames() { var columnNames = new[] { new Identifier("test_column_1"), new Identifier("test_column_2"), new Identifier("test_column_3") }; var comments = await GetViewCommentsAsync("view_comment_view_1").ConfigureAwait(false); Assert.That(comments.ColumnComments.Keys.OrderBy(x => x), Is.EqualTo(columnNames)); } [Test] public async Task GetViewComments_WhenViewMissingColumnComments_ReturnsLookupWithOnlyNoneValues() { var comments = await GetViewCommentsAsync("view_comment_view_1").ConfigureAwait(false); var columnComments = comments.ColumnComments; var hasOnlyNones = columnComments.All(c => c.Value.IsNone); Assert.That(hasOnlyNones, Is.True); } [Test] public async Task GetViewComments_WhenViewContainsComment_ReturnsExpectedValue() { const string expectedComment = "This is a test view."; var comments = await GetViewCommentsAsync("view_comment_view_2").ConfigureAwait(false); var viewComment = comments.Comment.UnwrapSome(); Assert.That(viewComment, Is.EqualTo(expectedComment)); } [Test] public async Task GetViewComments_PropertyGetForColumnComments_ReturnsAllColumnNamesAsKeys() { var columnNames = new[] { new Identifier("test_column_1"), new Identifier("test_column_2"), new Identifier("test_column_3") }; var comments = await GetViewCommentsAsync("view_comment_view_2").ConfigureAwait(false); Assert.That(comments.ColumnComments.Keys.OrderBy(x => x), Is.EqualTo(columnNames)); } [Test] public async Task GetViewComments_PropertyGetForColumnComments_ReturnsCorrectNoneOrSome() { var expectedNoneStates = new[] { true, false, true }; var comments = await GetViewCommentsAsync("view_comment_view_2").ConfigureAwait(false); var columnComments = comments.ColumnComments; var noneStates = new[] { columnComments["test_column_1"].IsNone, columnComments["test_column_2"].IsNone, columnComments["test_column_3"].IsNone }; Assert.That(noneStates, Is.EqualTo(expectedNoneStates)); } [Test] public async Task GetViewComments_PropertyGetForColumnComments_ReturnsCorrectCommentValue() { const string expectedComment = "This is a test view column."; var comments = await GetViewCommentsAsync("view_comment_view_2").ConfigureAwait(false); var comment = comments.ColumnComments["test_column_2"].UnwrapSome(); Assert.That(comment, Is.EqualTo(expectedComment)); } } }
46.187726
207
0.677192
[ "MIT" ]
sjp/Schematic
src/SJP.Schematic.PostgreSql.Tests/Integration/Comments/PostgreSqlQueryViewCommentProviderTests.cs
12,796
C#
 namespace Examples { // https://stackoverflow.com/questions/521146/c-sharp-split-string-but-keep-split-chars-separators class SvgViewBoxSplitting { // Float validator regex: http://regexstorm.net/tester // [\+\-]?\s*[0-9]*(?:\.[0-9]*) public static string[] SplitAndKeepSeparators(string value, System.StringSplitOptions splitOptions, params char[] separators) { System.Collections.Generic.List<string> splitValues = new System.Collections.Generic.List<string>(); int itemStart = 0; for (int pos = 0; pos < value.Length; pos++) { for (int sepIndex = 0; sepIndex < separators.Length; sepIndex++) { if (separators[sepIndex] == value[pos]) { // add the section of string before the separator // (unless its empty and we are discarding empty sections) if (itemStart != pos || splitOptions == System.StringSplitOptions.None) { splitValues.Add(value.Substring(itemStart, pos - itemStart)); } itemStart = pos + 1; // add the separator splitValues.Add(separators[sepIndex].ToString()); break; } } } // add anything after the final separator // (unless its empty and we are discarding empty sections) if (itemStart != value.Length || splitOptions == System.StringSplitOptions.None) { splitValues.Add(value.Substring(itemStart, value.Length - itemStart)); } return splitValues.ToArray(); } public static string[] SplitAndKeepSeparators(string value, params char[] separators) { return SplitAndKeepSeparators(value, System.StringSplitOptions.RemoveEmptyEntries, separators); } public static System.Collections.Generic.IEnumerable<string> SplitAndKeepEnumerable1(string s, params char[] delims) { int start = 0, index; while ((index = s.IndexOfAny(delims, start)) != -1) { if (index - start > 0) yield return s.Substring(start, index - start); yield return s.Substring(index, 1); start = index + 1; } if (start < s.Length) { yield return s.Substring(start); } } public static string[] SplitAndKeep1(string s, params char[] delims) { System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>(); int start = 0, index; while ((index = s.IndexOfAny(delims, start)) != -1) { if (index - start > 0) ls.Add(s.Substring(start, index - start)); ls.Add(s.Substring(index, 1)); start = index + 1; } if (start < s.Length) { ls.Add(s.Substring(start)); } return ls.ToArray(); } public static System.Collections.Generic.IEnumerable<string> SplitAndKeepEnumerable(string s, params char[] delims) { if (string.IsNullOrEmpty(s)) yield return null; int start = 0, index; string separator = ""; while ((index = s.IndexOfAny(delims, start)) != -1) { if (index - start > 0) yield return Trim(separator) + s.Substring(start, index - start); separator = s.Substring(index, 1); start = index + 1; } if (start < s.Length) { yield return separator + s.Substring(start); } } public static string[] SplitAndKeep(string s, params char[] delims) { System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>(); if (string.IsNullOrEmpty(s)) return new string[0]; int start = 0, index; string separator = ""; while ((index = s.IndexOfAny(delims, start)) != -1) { if (index - start > 0) ls.Add(Trim(separator) + s.Substring(start, index - start)); separator = s.Substring(index, 1); start = index + 1; } if (start < s.Length) { ls.Add(separator + s.Substring(start)); } return ls.ToArray(); } public static string Trim(string input) { if (string.IsNullOrEmpty(input)) return input; input = input.Trim(' ', '\t', '\v', '\r', '\n', ',', '+'); return input; } public static int IndexOfAnyNonExponential(string s, char[] delims, int start) { int ret = s.IndexOfAny(delims, start); if (ret > 0) { char c = s[ret - 1]; if (c == 'E' || c == 'e') { start = ret + 1; return IndexOfAnyNonExponential(s, delims, start); } // End if (c == 'E' || c == 'e') } // End if (ret > 0) return ret; // ret [-1, 0] + ret } // End Function IndexOfAnyNonExponential public static string[] SplitSvgViewBox(string s, params char[] delims) { System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>(); if (string.IsNullOrEmpty(s)) return new string[0]; int start = 0, index; string separator = ""; while ((index = IndexOfAnyNonExponential(s, delims, start)) != -1) { if (index - start > 0) ls.Add(Trim(separator) + s.Substring(start, index - start)); separator = s.Substring(index, 1); start = index + 1; } // Whend if (start < s.Length) { ls.Add(separator + s.Substring(start)); } for (int i = ls.Count - 1; i > -1; --i) { if (ls[i].StartsWith(".")) ls[i] = "0" + ls[i]; else if (ls[i] == "-." || ls[i] == "+.") // OMG ls.RemoveAt(i); } return ls.ToArray(); } public static string[] SplitSvgViewBox(string input) { return SplitSvgViewBox(input, ' ', '\t', '\v', '\r', '\n', ',', '+', '-'); } public static decimal[] SplitViewBox(string input) { System.Collections.Generic.List<string> results = new System.Collections.Generic.List<string>(); // params char[] delims // delims = new char[] { ' ', '\t', '\v', '\r', '\n', ',' , '+', '-' }; // string delimiters = new string(delims); string delimiters = " \t\v\r\n,+-"; string previous = null; System.Collections.Generic.List<char> ls = new System.Collections.Generic.List<char>(); for (int i = 0; i < input.Length; ++i) { char c = input[i]; int pos = delimiters.IndexOf(c); if (pos != -1) { char splitChar = delimiters[pos]; if (previous == "E" || previous == "e") { ls.Add(c); } else { if (ls.Count > 0) { string s = new string(ls.ToArray()); if (s != "-" && s != "+" && s != "." && s != "-." && s != "+.") { if (s.StartsWith(".")) s = "0" + s; results.Add(s); } } // End if (ls.Count > 0) ls.Clear(); if (splitChar == '+' || splitChar == '-') ls.Add(splitChar); } // End else of if (previous == "E" || previous == "e") } else ls.Add(c); previous = c.ToString(); } // Next i decimal[] viewBoxValues = new decimal[results.Count]; for (int i = 0; i < results.Count; ++i) { viewBoxValues[i] = System.Decimal.Parse(results[i], System.Globalization.NumberStyles.Float); } return viewBoxValues; } // End Function SplitViewBox public static void TestViewBoxSplitting() { decimal d1 = decimal.Parse("0.", System.Globalization.NumberStyles.Float); decimal d2 = decimal.Parse(".0", System.Globalization.NumberStyles.Float); // decimal d3 = decimal.Parse(".", System.Globalization.NumberStyles.Float); // decimal d4 = decimal.Parse("", System.Globalization.NumberStyles.Float); System.Console.WriteLine(d1); System.Console.WriteLine(d2); decimal[] viewBoxValues1 = SplitViewBox("----2E4,,5E-3,12,0,+12-13.13, ,.0 ,14 -15 2E3"); decimal[] viewBoxValues2 = SplitViewBox("5E-3,12,0,+12-13.13, ,.0 ,14 -15 2E12 5---."); System.Console.WriteLine("{0} {1}", viewBoxValues1, viewBoxValues2); // string[] points = SplitSvgViewBox("2E4,,5E-3,12,0,+12-13.13, ,.0 ,14 -15 2E3132 5"); // string[] points = SplitSvgViewBox("5E-3,12,0,+12-13.13, ,.0 ,14 -15 2E3132 5---."); string[] points = SplitSvgViewBox("5E-3,12,0,+12-13.13, ,.0 ,14 -15 2E12 5---."); foreach (string num in points) { decimal dec = System.Decimal.Parse(num, System.Globalization.NumberStyles.Float); } System.Console.WriteLine(points); } } }
32.228395
133
0.459395
[ "MIT" ]
ststeiger/PdfSharpNetStandard
Examples/_SvgViewBoxSplitting.cs
10,444
C#
using System.Net; using System.Threading.Tasks; using Aspose.Slides.Web.UI.Services; using Microsoft.AspNetCore.Mvc; namespace Aspose.Slides.Web.UI.Controllers { public class SlidesController : Controller { public SlidesController(ISlidesViewModelFactory slidesViewModelFactory, IEditorService editorService) { SlidesViewModelFactory = slidesViewModelFactory; EditorService = editorService; } public ISlidesViewModelFactory SlidesViewModelFactory { get; } public IEditorService EditorService { get; } public ActionResult Index() { return View(SlidesViewModelFactory.CreateShowroomModel(Request)); } public ActionResult Annotation(string extension) { var model = SlidesViewModelFactory.CreateAnnotationModel(Request, extension); return View(model); } public ActionResult Search(string extension) { var model = SlidesViewModelFactory.CreateSearchModel(Request, extension); return View(model); } public ActionResult Watermark(string extension) { var model = SlidesViewModelFactory.CreateWatermarkModel(Request, extension); return View(model); } public ActionResult Redaction(string extension) { var model = SlidesViewModelFactory.CreateRedactionModel(Request, extension); return View(model); } public ActionResult Parser(string extension) { var model = SlidesViewModelFactory.CreateParserModel(Request, extension); return View(model); } public ActionResult Conversion(string extension) { var model = SlidesViewModelFactory.CreateConversionModel(Request, extension); return View(model); } public ActionResult Merger(string extension) { var model = SlidesViewModelFactory.CreateMergerModel(Request, extension); return View(model); } [Route("slides/storage/view/{folder?}/{fileName?}")] public ActionResult Slideshow(string folder, string fileName) { if (string.IsNullOrEmpty(folder) || string.IsNullOrEmpty(fileName)) { return Redirect("/slides/viewer"); } var model = SlidesViewModelFactory.CreateSlideshowModel(Request, folder, fileName); return View(model); } public ActionResult Viewer(string extension) { var model = SlidesViewModelFactory.CreateViewerModel(Request, extension); return View(model); } public ActionResult Unlock(string extension) { var model = SlidesViewModelFactory.CreateUnlockModel(Request, extension); return View(model); } public ActionResult Lock(string extension) { var model = SlidesViewModelFactory.CreateLockModel(Request, extension); return View(model); } public ActionResult Metadata(string extension) { var model = SlidesViewModelFactory.CreateMetadataModel(Request, extension); return View(model); } public ActionResult Video(string extension) { var model = SlidesViewModelFactory.CreateVideoModel(Request, extension); return View(model); } public ActionResult Splitter(string extension) { var model = SlidesViewModelFactory.CreateSplitterModel(Request, extension); return View(model); } [Route("slides/storage/edit/{copy?}/{new?}/{folder?}/{fileName?}")] public async Task<ActionResult> EditorApp(string copy, string @new, string folder, string fileName) { if (!string.IsNullOrEmpty(copy)) { var res = await EditorService.CopyProcessedAsync(folder, fileName); if (res == null) { return Redirect("/slides/storage/edit/?folder=NotFound&fileName=NotFound"); } return Redirect( $"/slides/storage/edit/?folder={res.Folder}&fileName={WebUtility.UrlEncode(res.Filename)}" ); } if (!string.IsNullOrEmpty(@new)) { var res = await EditorService.CreateByTemplateAsync(@new); if (res == null) { return Redirect("/slides/storage/edit/?folder=NotFound&fileName=NotFound"); } return Redirect( $"/slides/storage/edit/?folder={res.Folder}&fileName={WebUtility.UrlEncode(res.Filename)}" ); } var model = SlidesViewModelFactory.CreateEditorAppModel(Request, folder, fileName); return View(model); } public ActionResult Editor(string extension) { var model = SlidesViewModelFactory.CreateEditorUploaderModel(Request, extension); return View(model); } public ActionResult Signature(string extension) { var model = SlidesViewModelFactory.CreateSignatureModel(Request, extension); return View(model); } public ActionResult Chart(string extension) { var model = SlidesViewModelFactory.CreateChartModel(Request, extension); return View(model); } public ActionResult PermanentlyRedirect(string toaction, string extension) { return RedirectPermanent($"/slides/{toaction}/{extension}"); } public ActionResult Comparison(string extension) { var model = SlidesViewModelFactory.CreateComparisonModel(Request, extension); return View(model); } public ActionResult Import(string extension) { var model = SlidesViewModelFactory.CreateImportModel(Request, extension); return View(model); } [ActionName("Remove-Macros")] public ActionResult RemoveMacros(string extension) { var model = SlidesViewModelFactory.CreateRemoveMacrosModel(Request, extension); return View("RemoveMacros", model); } } }
24.815166
103
0.737586
[ "MIT" ]
aspose-slides/Aspose.Slides-for-.NET
Demos/Aspose.Slides.Web/UI/Controllers/SlidesController.cs
5,236
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the timestream-query-2018-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.TimestreamQuery.Model { /// <summary> /// This is the response object from the DescribeEndpoints operation. /// </summary> public partial class DescribeEndpointsResponse : AmazonWebServiceResponse { private List<Endpoint> _endpoints = new List<Endpoint>(); /// <summary> /// Gets and sets the property Endpoints. /// <para> /// An <code>Endpoints</code> object is returned when a <code>DescribeEndpoints</code> /// request is made. /// </para> /// </summary> [AWSProperty(Required=true)] public List<Endpoint> Endpoints { get { return this._endpoints; } set { this._endpoints = value; } } // Check to see if Endpoints property is set internal bool IsSetEndpoints() { return this._endpoints != null && this._endpoints.Count > 0; } } }
32.050847
115
0.639873
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/TimestreamQuery/Generated/Model/DescribeEndpointsResponse.cs
1,891
C#
using System; using Umbraco.Core; using Umbraco.Core.Dynamics; using Umbraco.Core.Models.PublishedContent; namespace Macaw.Umbraco.Foundation.Infrastructure.Converters { public class ContentPicker : BaseConverter, IConverter { public override bool IsConverter(PublishedPropertyType propertyType) { return IsConverter(propertyType.PropertyEditorAlias); } public bool IsConverter(string editoralias) { return Constants.PropertyEditors.ContentPickerAlias.Equals(editoralias); } public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { return ConvertDataToSource(source); } public object ConvertDataToSource(object source) { if (source != null && !source.ToString().IsNullOrWhiteSpace()) { var content = Repository.FindById(Convert.ToInt32(source)); if (content != null) return content; } return DynamicNull.Null; } } }
26.825
109
0.66356
[ "MIT" ]
MacawNL/Macaw.Umbraco.Foundation
Macaw.Umbraco.Foundation/Infrastructure/Converters/ContentPicker.cs
1,075
C#
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class LatestJobs_ascx:UserControl { protected void Page_Load(object sender, EventArgs e) { } }
19.947368
57
0.738786
[ "MIT" ]
stevenfollis/techorama-be-2019
windows/demos/app/Jobs/Jobs/UserControls/LatestJobs.ascx.cs
379
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Windows.Input; namespace Microsoft.Toolkit.Mvvm.Input { /// <summary> /// An interface expanding <see cref="ICommand"/> with the ability to raise /// the <see cref="ICommand.CanExecuteChanged"/> event externally. /// </summary> public interface IRelayCommand : ICommand { /// <summary> /// Notifies that the <see cref="ICommand.CanExecute"/> property has changed. /// </summary> void NotifyCanExecuteChanged(); } }
34.6
85
0.676301
[ "MIT" ]
ArchieCoder/WindowsCommunityToolkit
Microsoft.Toolkit.Mvvm/Input/Interfaces/IRelayCommand.cs
692
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using Azure.Core; namespace Azure.ResourceManager.Insights.Models { /// <summary> Represents a collection of alert rule resources. </summary> public partial class MetricAlertStatusCollection { /// <summary> Initializes a new instance of MetricAlertStatusCollection. </summary> internal MetricAlertStatusCollection() { Value = new ChangeTrackingList<MetricAlertStatus>(); } /// <summary> Initializes a new instance of MetricAlertStatusCollection. </summary> /// <param name="value"> the values for the alert rule resources. </param> internal MetricAlertStatusCollection(IReadOnlyList<MetricAlertStatus> value) { Value = value; } /// <summary> the values for the alert rule resources. </summary> public IReadOnlyList<MetricAlertStatus> Value { get; } } }
32
91
0.681818
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/insights/Azure.ResourceManager.Insights/src/Generated/Models/MetricAlertStatusCollection.cs
1,056
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using eCommerceStarterCode.Data; using eCommerceStarterCode.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; // this controller joins scouts to their organizations namespace eCommerceStarterCode.Controllers { [Route("api/scoutorganizationjoin")] [ApiController] public class ScoutOrganizationJoinController : ControllerBase { private readonly ApplicationDbContext _context; public ScoutOrganizationJoinController(ApplicationDbContext context) { _context = context; } // get all joins [HttpGet("all")] public IActionResult GetAllJoins() { var allJoins = _context.ScoutOrganizationJoins; return Ok(allJoins); } // add scout and Organization join [HttpPost("add")] public IActionResult AddScoutOrganizationJoin([FromBody] ScoutOrganizationJoin value) { var getJoinIds = _context.ScoutOrganizationJoins.Select(i => i.Id); if (getJoinIds.Contains(value.Id)) { return StatusCode(400, "join already exists for this user"); } else { _context.ScoutOrganizationJoins.Add(value); _context.SaveChanges(); return StatusCode(201, value); } } // deletes scout and organization join [HttpDelete("delete/{id}")] public IActionResult DeleteScoutOrganizationJoin(string id) { var deleteScoutOrganizationJoin = _context.ScoutOrganizationJoins.Where(p => p.Id == id).SingleOrDefault(); // if no join note found if (deleteScoutOrganizationJoin == null) { return NotFound(); } // if join found else { _context.ScoutOrganizationJoins.Remove(deleteScoutOrganizationJoin); _context.SaveChanges(); return Ok(deleteScoutOrganizationJoin); } } // get a scout's organization details using their Id [HttpGet("{id}")] public IActionResult GetScoutOrganizationInfo(string id) { var scoutOrganizationId = _context.ScoutOrganizationJoins.Where(p => p.Id == id).Select(p => p.OrganizationId).SingleOrDefault(); var scoutOrganizationDetails = _context.Organizations.Where(o => o.OrganizationId == scoutOrganizationId).SingleOrDefault(); return StatusCode(201, scoutOrganizationDetails); } // edit a scout's organization [HttpPut("edit/{id}")] public IActionResult UpdateOrganization([FromBody] ScoutOrganizationJoin value) { var join = _context.ScoutOrganizationJoins.Where(i => i.Id == value.Id).SingleOrDefault(); join.Id = value.Id; join.OrganizationId = value.OrganizationId; _context.ScoutOrganizationJoins.Update(join); _context.SaveChanges(); return Ok(join); } } }
32.188119
141
0.622885
[ "MIT" ]
MadisonLifeAgent/MyProScoutBackEndRepo
eCommerceStarterCode/Controllers/ScoutOrganizationJoinController.cs
3,253
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\EntityCollectionRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; /// <summary> /// The type WorkbookTablesCollectionRequestBuilder. /// </summary> public partial class WorkbookTablesCollectionRequestBuilder : BaseRequestBuilder, IWorkbookTablesCollectionRequestBuilder { /// <summary> /// Constructs a new WorkbookTablesCollectionRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public WorkbookTablesCollectionRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public IWorkbookTablesCollectionRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public IWorkbookTablesCollectionRequest Request(IEnumerable<Option> options) { return new WorkbookTablesCollectionRequest(this.RequestUrl, this.Client, options); } /// <summary> /// Gets an <see cref="IWorkbookTableRequestBuilder"/> for the specified WorkbookWorkbookTable. /// </summary> /// <param name="id">The ID for the WorkbookWorkbookTable.</param> /// <returns>The <see cref="IWorkbookTableRequestBuilder"/>.</returns> public IWorkbookTableRequestBuilder this[string id] { get { return new WorkbookTableRequestBuilder(this.AppendSegmentToRequestUrl(id), this.Client); } } /// <summary> /// Gets the request builder for WorkbookTableAdd. /// </summary> /// <returns>The <see cref="IWorkbookTableAddRequestBuilder"/>.</returns> public IWorkbookTableAddRequestBuilder Add( bool hasHeaders, string address = null) { return new WorkbookTableAddRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.add"), this.Client, hasHeaders, address); } /// <summary> /// Gets the request builder for WorkbookTableCount. /// </summary> /// <returns>The <see cref="IWorkbookTableCountRequestBuilder"/>.</returns> public IWorkbookTableCountRequestBuilder Count() { return new WorkbookTableCountRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.count"), this.Client); } /// <summary> /// Gets the request builder for WorkbookTableItemAt. /// </summary> /// <returns>The <see cref="IWorkbookTableItemAtRequestBuilder"/>.</returns> public IWorkbookTableItemAtRequestBuilder ItemAt( Int32 index) { return new WorkbookTableItemAtRequestBuilder( this.AppendSegmentToRequestUrl("microsoft.graph.itemAt"), this.Client, index); } } }
38.07767
153
0.585161
[ "MIT" ]
andrueastman/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/WorkbookTablesCollectionRequestBuilder.cs
3,922
C#
// This source code was generated by regenerator" using System; using System.Runtime.InteropServices; namespace ShrimpDX { public enum D3D12_RESOURCE_BARRIER_TYPE // 1 { _TRANSITION = 0x0, _ALIASING = 0x1, _UAV = 0x2, } }
20.846154
50
0.630996
[ "MIT" ]
ousttrue/ComPtrCS
ShrimpDX/d3d12/D3D12_RESOURCE_BARRIER_TYPE.cs
271
C#
using MachineLearning.Core.Logger; using MachineLearning.DataLayer; using System; namespace MachineLearning.Sandbox { class Program { static readonly Logger Logger = new Logger(); static readonly FromCsvTableProvider CsvProvider = new FromCsvTableProvider(); static readonly JsonProvider JsonProvider = new JsonProvider(); static int Main() { NeuronNetworkProgram.Run(); return Console.ReadKey().KeyChar; } } }
22.842105
80
0.764977
[ "MIT" ]
JillyMan/MachineLerningFramework
MachineLearning.Sandbox/Program.cs
436
C#
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; using FarmSystem.Plantação; using Microsoft.Reporting.WinForms; namespace FarmSystem { public partial class frmRelAcoes : Form { public frmRelAcoes() { InitializeComponent(); } private void frmRelAcoes_Load(object sender, EventArgs e) { // TODO: esta linha de código carrega dados na tabela 'postgresDataSet2.acoes_plantacao'. Você pode movê-la ou removê-la conforme necessário. this.acoes_plantacaoTableAdapter.Fill(this.postgresDataSet2.acoes_plantacao); this.reportViewer1.RefreshReport(); } private void btnFiltrar_Click(object sender, EventArgs e) { this.reportViewer1.LocalReport.SetParameters(new ReportParameter("plantacao", txtplantacao.Text)); this.reportViewer1.RefreshReport(); } private void btnListaPlant_Click(object sender, EventArgs e) { frmListaPlantacoes lp = new frmListaPlantacoes(); lp.ShowDialog(); if (lp.DialogResult == DialogResult.OK) { objplantacao op = lp.GetPlantacao(); txtplantacao.Text = op.codigo.ToString(); txtsemente.Text = op.sementeusada.ToString(); } } } }
30.12
153
0.648074
[ "MIT" ]
Williampaz/FarmSystem
Relatorios/frmRelAcoes.cs
1,515
C#
using System; using System.Collections; using Optional; namespace AlphaDev.Optional.Extensions { public static class ObjectExtensions { public static Option<T> SomeWhenNotNull<T>(this T? target) where T : class => target.SomeNotNull()!; public static Option<T, TException> SomeWhenNotNull<T, TException>(this T? target, Func<TException> exceptionFactory) where T : class => target.SomeWhenNotNull().WithException(exceptionFactory); public static Option<T> SomeNotEmpty<T>(this T target, Func<T, IEnumerable> getEnumerable) { return target.SomeWhen(arg => getEnumerable(arg).GetEnumerator().MoveNext()); } public static Option<T, TException> SomeNotEmpty<T, TException>(this T target, Func<T, IEnumerable> getEnumerable, Func<T, TException> exceptionFactory) { return target.SomeWhen(arg => getEnumerable(arg).GetEnumerator().MoveNext(), exceptionFactory); } } }
38.538462
108
0.674651
[ "Unlicense" ]
OlegKleyman/AlphaDev.Optional
core/AlphaDev.Optional.Extensions/ObjectExtensions.cs
1,004
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Text; using Newtonsoft.Json.Serialization; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer { [TestFixture] public class TraceWriter : TestFixtureBase { #region Types public class Account { public string FullName { get; set; } public bool Deleted { get; set; } } #endregion [Test] public void Example() { #region Usage string json = @"{ 'FullName': 'Dan Deleted', 'Deleted': true, 'DeletedDate': '2013-01-20T00:00:00' }"; MemoryTraceWriter traceWriter = new MemoryTraceWriter(); Account account = JsonConvert.DeserializeObject<Account>( json, new JsonSerializerSettings { TraceWriter = traceWriter } ); Console.WriteLine(traceWriter.ToString()); // 2013-01-21T01:36:24.422 Info Started deserializing Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path 'FullName', line 2, position 20. // 2013-01-21T01:36:24.442 Verbose Could not find member 'DeletedDate' on Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path 'DeletedDate', line 4, position 23. // 2013-01-21T01:36:24.447 Info Finished deserializing Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path '', line 5, position 8. // 2013-01-21T01:36:24.450 Verbose Deserialized JSON: // { // "FullName": "Dan Deleted", // "Deleted": true, // "DeletedDate": "2013-01-20T00:00:00" // } #endregion Assert.AreEqual(4, traceWriter.GetTraceMessages().Count()); } } }
35.824176
192
0.66411
[ "MIT" ]
belav/Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/TraceWriter.cs
3,262
C#
// <auto-generated /> using IdentityMicroservice.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; namespace IdentityMicroservice.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.1-rtm-125"); modelBuilder.Entity("IdentityMicroservice.Models.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("IdentityMicroservice.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("IdentityMicroservice.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("IdentityMicroservice.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("IdentityMicroservice.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.444934
95
0.480769
[ "MIT" ]
aacostamx/ASP.NETIdentityWithIdentityServer4Sample
IdentityMicroservice/Data/Migrations/ApplicationDbContextModelSnapshot.cs
7,594
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Application.DTOs { public class BanResponce { [Required] [EmailAddress] public string Email { get; set; } } }
17.933333
44
0.684015
[ "MIT" ]
Devsquares/AdlerZentrum-BackEnd
Application/DTOs/AccountDTO/BanResponce.cs
269
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DeviceManagementExchangeOnPremisesPolicyRequest. /// </summary> public partial class DeviceManagementExchangeOnPremisesPolicyRequest : BaseRequest, IDeviceManagementExchangeOnPremisesPolicyRequest { /// <summary> /// Constructs a new DeviceManagementExchangeOnPremisesPolicyRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DeviceManagementExchangeOnPremisesPolicyRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified DeviceManagementExchangeOnPremisesPolicy using POST. /// </summary> /// <param name="deviceManagementExchangeOnPremisesPolicyToCreate">The DeviceManagementExchangeOnPremisesPolicy to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DeviceManagementExchangeOnPremisesPolicy.</returns> public async System.Threading.Tasks.Task<DeviceManagementExchangeOnPremisesPolicy> CreateAsync(DeviceManagementExchangeOnPremisesPolicy deviceManagementExchangeOnPremisesPolicyToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; var newEntity = await this.SendAsync<DeviceManagementExchangeOnPremisesPolicy>(deviceManagementExchangeOnPremisesPolicyToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Creates the specified DeviceManagementExchangeOnPremisesPolicy using POST and returns a <see cref="GraphResponse{DeviceManagementExchangeOnPremisesPolicy}"/> object. /// </summary> /// <param name="deviceManagementExchangeOnPremisesPolicyToCreate">The DeviceManagementExchangeOnPremisesPolicy to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{DeviceManagementExchangeOnPremisesPolicy}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<DeviceManagementExchangeOnPremisesPolicy>> CreateResponseAsync(DeviceManagementExchangeOnPremisesPolicy deviceManagementExchangeOnPremisesPolicyToCreate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.POST; return this.SendAsyncWithGraphResponse<DeviceManagementExchangeOnPremisesPolicy>(deviceManagementExchangeOnPremisesPolicyToCreate, cancellationToken); } /// <summary> /// Deletes the specified DeviceManagementExchangeOnPremisesPolicy. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; await this.SendAsync<DeviceManagementExchangeOnPremisesPolicy>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the specified DeviceManagementExchangeOnPremisesPolicy and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse"/> to await.</returns> public System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.DELETE; return this.SendAsyncWithGraphResponse(null, cancellationToken); } /// <summary> /// Gets the specified DeviceManagementExchangeOnPremisesPolicy. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DeviceManagementExchangeOnPremisesPolicy.</returns> public async System.Threading.Tasks.Task<DeviceManagementExchangeOnPremisesPolicy> GetAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; var retrievedEntity = await this.SendAsync<DeviceManagementExchangeOnPremisesPolicy>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Gets the specified DeviceManagementExchangeOnPremisesPolicy and returns a <see cref="GraphResponse{DeviceManagementExchangeOnPremisesPolicy}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{DeviceManagementExchangeOnPremisesPolicy}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<DeviceManagementExchangeOnPremisesPolicy>> GetResponseAsync(CancellationToken cancellationToken = default) { this.Method = HttpMethods.GET; return this.SendAsyncWithGraphResponse<DeviceManagementExchangeOnPremisesPolicy>(null, cancellationToken); } /// <summary> /// Updates the specified DeviceManagementExchangeOnPremisesPolicy using PATCH. /// </summary> /// <param name="deviceManagementExchangeOnPremisesPolicyToUpdate">The DeviceManagementExchangeOnPremisesPolicy to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated DeviceManagementExchangeOnPremisesPolicy.</returns> public async System.Threading.Tasks.Task<DeviceManagementExchangeOnPremisesPolicy> UpdateAsync(DeviceManagementExchangeOnPremisesPolicy deviceManagementExchangeOnPremisesPolicyToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; var updatedEntity = await this.SendAsync<DeviceManagementExchangeOnPremisesPolicy>(deviceManagementExchangeOnPremisesPolicyToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified DeviceManagementExchangeOnPremisesPolicy using PATCH and returns a <see cref="GraphResponse{DeviceManagementExchangeOnPremisesPolicy}"/> object. /// </summary> /// <param name="deviceManagementExchangeOnPremisesPolicyToUpdate">The DeviceManagementExchangeOnPremisesPolicy to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The <see cref="GraphResponse{DeviceManagementExchangeOnPremisesPolicy}"/> object of the request.</returns> public System.Threading.Tasks.Task<GraphResponse<DeviceManagementExchangeOnPremisesPolicy>> UpdateResponseAsync(DeviceManagementExchangeOnPremisesPolicy deviceManagementExchangeOnPremisesPolicyToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PATCH; return this.SendAsyncWithGraphResponse<DeviceManagementExchangeOnPremisesPolicy>(deviceManagementExchangeOnPremisesPolicyToUpdate, cancellationToken); } /// <summary> /// Updates the specified DeviceManagementExchangeOnPremisesPolicy using PUT. /// </summary> /// <param name="deviceManagementExchangeOnPremisesPolicyToUpdate">The DeviceManagementExchangeOnPremisesPolicy object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task<DeviceManagementExchangeOnPremisesPolicy> PutAsync(DeviceManagementExchangeOnPremisesPolicy deviceManagementExchangeOnPremisesPolicyToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; var updatedEntity = await this.SendAsync<DeviceManagementExchangeOnPremisesPolicy>(deviceManagementExchangeOnPremisesPolicyToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Updates the specified DeviceManagementExchangeOnPremisesPolicy using PUT and returns a <see cref="GraphResponse{DeviceManagementExchangeOnPremisesPolicy}"/> object. /// </summary> /// <param name="deviceManagementExchangeOnPremisesPolicyToUpdate">The DeviceManagementExchangeOnPremisesPolicy object to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await of <see cref="GraphResponse{DeviceManagementExchangeOnPremisesPolicy}"/>.</returns> public System.Threading.Tasks.Task<GraphResponse<DeviceManagementExchangeOnPremisesPolicy>> PutResponseAsync(DeviceManagementExchangeOnPremisesPolicy deviceManagementExchangeOnPremisesPolicyToUpdate, CancellationToken cancellationToken = default) { this.ContentType = CoreConstants.MimeTypeNames.Application.Json; this.Method = HttpMethods.PUT; return this.SendAsyncWithGraphResponse<DeviceManagementExchangeOnPremisesPolicy>(deviceManagementExchangeOnPremisesPolicyToUpdate, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementExchangeOnPremisesPolicyRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementExchangeOnPremisesPolicyRequest Expand(Expression<Func<DeviceManagementExchangeOnPremisesPolicy, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementExchangeOnPremisesPolicyRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDeviceManagementExchangeOnPremisesPolicyRequest Select(Expression<Func<DeviceManagementExchangeOnPremisesPolicy, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="deviceManagementExchangeOnPremisesPolicyToInitialize">The <see cref="DeviceManagementExchangeOnPremisesPolicy"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(DeviceManagementExchangeOnPremisesPolicy deviceManagementExchangeOnPremisesPolicyToInitialize) { } } }
59.036
257
0.697337
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/DeviceManagementExchangeOnPremisesPolicyRequest.cs
14,759
C#
namespace TramsDataApi.ResponseModels.ApplyToBecome { public class A2BSchoolLoanResponse { public string SchoolLoanId {get; set;} public decimal? SchoolLoanAmount {get; set;} public string SchoolLoanPurpose {get; set;} public string SchoolLoanProvider {get; set;} public string SchoolLoanInterestRate {get; set;} public string SchoolLoanSchedule {get; set;} } }
35.083333
56
0.693587
[ "MIT" ]
DFE-Digital/trams-data-api
TramsDataApi/ResponseModels/ApplyToBecome/A2BSchoolLoanResponse.cs
421
C#
using System; using System.Collections.Generic; using System.Linq; namespace FazelMan.Collections.Extensions { /// <summary> /// Extension methods for <see cref="IEnumerable{T}"/>. /// </summary> public static class EnumerableExtensions { /// <summary> /// Concatenates the members of a constructed <see cref="IEnumerable{T}"/> collection of type System.String, using the specified separator between each member. /// This is a shortcut for string.Join(...) /// </summary> /// <param name="source">A collection that contains the strings to concatenate.</param> /// <param name="separator">The string to use as a separator. separator is included in the returned string only if values has more than one element.</param> /// <returns>A string that consists of the members of values delimited by the separator string. If values has no members, the method returns System.String.Empty.</returns> public static string JoinAsString(this IEnumerable<string> source, string separator) { return string.Join(separator, source); } /// <summary> /// Concatenates the members of a collection, using the specified separator between each member. /// This is a shortcut for string.Join(...) /// </summary> /// <param name="source">A collection that contains the objects to concatenate.</param> /// <param name="separator">The string to use as a separator. separator is included in the returned string only if values has more than one element.</param> /// <typeparam name="T">The type of the members of values.</typeparam> /// <returns>A string that consists of the members of values delimited by the separator string. If values has no members, the method returns System.String.Empty.</returns> public static string JoinAsString<T>(this IEnumerable<T> source, string separator) { return string.Join(separator, source); } /// <summary> /// Filters a <see cref="IEnumerable{T}"/> by given predicate if given condition is true. /// </summary> /// <param name="source">Enumerable to apply filtering</param> /// <param name="condition">A boolean value</param> /// <param name="predicate">Predicate to filter the enumerable</param> /// <returns>Filtered or not filtered enumerable based on <paramref name="condition"/></returns> public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, bool condition, Func<T, bool> predicate) { return condition ? source.Where(predicate) : source; } /// <summary> /// Filters a <see cref="IEnumerable{T}"/> by given predicate if given condition is true. /// </summary> /// <param name="source">Enumerable to apply filtering</param> /// <param name="condition">A boolean value</param> /// <param name="predicate">Predicate to filter the enumerable</param> /// <returns>Filtered or not filtered enumerable based on <paramref name="condition"/></returns> public static IEnumerable<T> WhereIf<T>(this IEnumerable<T> source, bool condition, Func<T, int, bool> predicate) { return condition ? source.Where(predicate) : source; } } }
51.818182
179
0.641228
[ "MIT" ]
FazelMan/Core
FazelMan/Collections/Extensions/EnumerableExtensions.cs
3,422
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using PierresBakery; namespace PierresBakeryTests { [TestClass] public class BreadTests { [TestMethod] public void BreadConstructor_CreateInstanceOfBread_Bread() { Bread newBread = new Bread(5); Assert.AreEqual(typeof(Bread), newBread.GetType()); } [TestMethod] public void GetCurrentAmount_GetOrderAmountForBread_Int() { Bread bread = new Bread(3); int result = bread.Amount; Assert.AreEqual(result, 3); } [TestMethod] public void GetCurrentCost_GetOrderCostFor6Bread_Int() { Bread bread = new Bread(6); int result = bread.GetCurrentCost(); Assert.AreEqual(result, 20); } [TestMethod] public void GetCurrentCost_GetOrderCostWithoutDiscountForBread_Int() { Bread bread = new Bread(4, false); int result = bread.GetCurrentCost(); Assert.AreEqual(result, 20); } [TestMethod] public void GetCurrentCost_GetOrderCostFor92Bread_Int() { Bread bread = new Bread(92); int result = bread.GetCurrentCost(); Assert.AreEqual(result, 310); } [TestMethod] public void GetCurrentCost_GetOrderCostFor49Bread_Int() { Bread bread = new Bread(49); int result = bread.GetCurrentCost(); Assert.AreEqual(result, 165); } [TestMethod] public void GetCurrentCost_GetOrderCostFor787Bread_Int() { Bread bread = new Bread(787); int result = bread.GetCurrentCost(); Assert.AreEqual(result, 2625); } [TestMethod] public void GetCurrentCost_GetOrderCostWithoutDiscountFor787Bread_Int() { Bread bread = new Bread(787, false); int result = bread.GetCurrentCost(); Assert.AreEqual(result, 3935); } [TestMethod] public void GetCurrentCost_GetOrderDiscountFor787Bread_Int() { Bread bread = new Bread(787, false); int cost = bread.GetCurrentCost(); Bread bread2 = new Bread(787); int discountedCost = bread2.GetCurrentCost(); int result = cost - discountedCost; Assert.AreEqual(result, 1310); } } }
20.212121
73
0.714143
[ "MIT" ]
ChrisRamer/Test-Driven-Developement-with-C
PierresBakery.Solution/PierresBakeryTests/ModelsTests/BreadTests.cs
2,001
C#
using Abp.Authorization; using ABP.WebApi.Authorization; using Microsoft.AspNetCore.JsonPatch.Operations; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ABP.WebApi.Web.Host.Startup { public class SecurityRequirementsOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Policy names map to scopes //var requiredScopes = context.MethodInfo // .GetCustomAttributes(true) // .OfType<AuthorizeAttribute>() // .Select(attr => attr.Policy) // .Distinct(); var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true) .Union(context.MethodInfo.GetCustomAttributes(true)) .OfType<AuthorizeAttribute>().Any(); if (authAttributes) { operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" }); operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" }); var oAuthScheme = new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }; operation.Security = new List<OpenApiSecurityRequirement> { new OpenApiSecurityRequirement { [ oAuthScheme ] = new[] {"apitest","email", "profile","openid","api1", "offline_access" } } }; } } } }
36.44898
109
0.608623
[ "MIT" ]
gnsilence/AntdPro-Vue-id4
ABP.WebApi/后端/src/ABP.WebApi.Web.Host/Startup/SecurityRequirementsOperationFilter.cs
1,788
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using LDY.Lesson8.EarthCalculator.BAL.EarthCalculator.Services; using LDY.Lesson8.EarthCalculator.Core.DI; namespace LDY.Lesson8.EarthCalculator.UI.WPF { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); AppContainer.ConfigureContainer(); } } }
26.633333
63
0.742178
[ "MIT" ]
LiDmYr/LDY.UIP.Class.EarthCalculator
LDY.Lesson8.EarthCalculator.UI.WPF/MainWindow.xaml.cs
801
C#
/* _BEGIN_TEMPLATE_ { "id": "BRMA14_1H", "name": [ "全能金刚防御系统", "Omnotron Defense System" ], "text": [ null, null ], "CardClass": "NEUTRAL", "type": "HERO", "cost": null, "rarity": null, "set": "BRM", "collectible": null, "dbfId": 2468 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_BRMA14_1H : SimTemplate { } }
13.357143
37
0.55615
[ "MIT" ]
chi-rei-den/Silverfish
cards/BRM/BRMA14/Sim_BRMA14_1H.cs
390
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using FakeStorage; using Microsoft.Azure.WebJobs.Host.Executors; using Microsoft.Azure.WebJobs.Host.Indexers; using Microsoft.Azure.WebJobs.Host.Protocols; using Microsoft.Azure.WebJobs.Host.TestCommon; using Microsoft.Azure.WebJobs.Host.Timers; using Microsoft.Azure.WebJobs.Logging; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Moq; using Xunit; using SingletonLockHandle = Microsoft.Azure.WebJobs.Host.StorageBaseDistributedLockManager.SingletonLockHandle; namespace Microsoft.Azure.WebJobs.Host.UnitTests.Singleton { internal static class Ext // $$$ move to better place { // Wrapper to get the internal class. public static async Task<SingletonLockHandle> TryLockInternalAsync(this SingletonManager manager, string lockId, string functionInstanceId, SingletonAttribute attribute, CancellationToken cancellationToken, bool retry = true) { var handle = await manager.TryLockAsync(lockId, functionInstanceId, attribute, cancellationToken, retry); return handle.GetInnerHandle(); } public static SingletonLockHandle GetInnerHandle(this RenewableLockHandle handle) { if (handle == null) { return null; } return (SingletonLockHandle)handle.InnerLock; } } public class SingletonManagerTests { private const string TestHostId = "testhost"; private const string TestLockId = "testid"; private const string TestInstanceId = "testinstance"; private const string TestLeaseId = "testleaseid"; private const string Secondary = "SecondaryStorage"; private StorageBaseDistributedLockManager _core; private SingletonManager _singletonManager; private SingletonOptions _singletonConfig; private CloudBlobDirectory _mockBlobDirectory; private CloudBlobDirectory _mockSecondaryBlobDirectory; internal FakeAccount _account1 = new FakeAccount(); internal FakeAccount _account2 = new FakeAccount(); private Mock<IWebJobsExceptionHandler> _mockExceptionDispatcher; private Mock<CloudBlockBlob> _mockStorageBlob; private TestLoggerProvider _loggerProvider; private readonly Dictionary<string, string> _mockBlobMetadata; private TestNameResolver _nameResolver; private class FakeLeaseProvider : StorageBaseDistributedLockManager { internal FakeAccount _account1 = new FakeAccount(); internal FakeAccount _account2 = new FakeAccount(); public FakeLeaseProvider(ILoggerFactory logger) : base(logger) { } protected override CloudBlobContainer GetContainer(string accountName) { FakeAccount account; if (string.IsNullOrEmpty(accountName) || accountName == ConnectionStringNames.Storage) { account = _account1; } else if (accountName == Secondary) { account = _account2; } else { throw new InvalidOperationException("Unknown account: " + accountName); } var container = account.CreateCloudBlobClient().GetContainerReference("azure-webjobs-hosts"); return container; } } public SingletonManagerTests() { ILoggerFactory loggerFactory = new LoggerFactory(); _loggerProvider = new TestLoggerProvider(); loggerFactory.AddProvider(_loggerProvider); var logger = loggerFactory?.CreateLogger(LogCategories.Singleton); var leaseProvider = new FakeLeaseProvider(loggerFactory); _mockBlobDirectory = leaseProvider._account1.CreateCloudBlobClient().GetContainerReference(HostContainerNames.Hosts).GetDirectoryReference(HostDirectoryNames.SingletonLocks); _mockSecondaryBlobDirectory = leaseProvider._account2.CreateCloudBlobClient().GetContainerReference(HostContainerNames.Hosts).GetDirectoryReference(HostDirectoryNames.SingletonLocks); _mockExceptionDispatcher = new Mock<IWebJobsExceptionHandler>(MockBehavior.Strict); _mockStorageBlob = new Mock<CloudBlockBlob>(MockBehavior.Strict, new Uri("https://fakeaccount.blob.core.windows.net/" + HostContainerNames.Hosts + "/" + HostDirectoryNames.SingletonLocks + "/" + TestLockId)); _mockBlobMetadata = new Dictionary<string, string>(); leaseProvider._account1.SetBlob(HostContainerNames.Hosts, HostDirectoryNames.SingletonLocks + "/" + TestLockId, _mockStorageBlob.Object); _singletonConfig = new SingletonOptions(); // use reflection to bypass the normal validations (so tests can run fast) TestHelpers.SetField(_singletonConfig, "_lockAcquisitionPollingInterval", TimeSpan.FromMilliseconds(25)); TestHelpers.SetField(_singletonConfig, "_lockPeriod", TimeSpan.FromMilliseconds(500)); _singletonConfig.LockAcquisitionTimeout = TimeSpan.FromMilliseconds(200); _nameResolver = new TestNameResolver(); _core = leaseProvider; _singletonManager = new SingletonManager(_core, new OptionsWrapper<SingletonOptions>(_singletonConfig), _mockExceptionDispatcher.Object, loggerFactory, new FixedHostIdProvider(TestHostId), _nameResolver); _singletonManager.MinimumLeaseRenewalInterval = TimeSpan.FromMilliseconds(250); } [Fact] public void GetLockDirectory_HandlesMultipleAccounts() { var directory = _core.GetLockDirectory(ConnectionStringNames.Storage); Assert.Equal(_mockBlobDirectory.Uri, directory.Uri); directory = _core.GetLockDirectory(null); Assert.Equal(_mockBlobDirectory.Uri, directory.Uri); directory = _core.GetLockDirectory(Secondary); Assert.Equal(_mockSecondaryBlobDirectory.Uri, directory.Uri); } [Fact] public async Task TryLockAsync_CreatesBlob_WhenItDoesNotExist() { CancellationToken cancellationToken = new CancellationToken(); RequestResult storageResult = new RequestResult { HttpStatusCode = 404 }; StorageException storageException = new StorageException(storageResult, null, null); int count = 0; MockAcquireLeaseAsync(null, () => { if (count++ == 0) { throw storageException; } return TestLeaseId; }); _mockStorageBlob.Setup(p => p.UploadTextAsync(string.Empty, null, null, null, null, cancellationToken)).Returns(Task.FromResult(true)); //_mockStorageBlob.SetupGet(p => p.Metadata).Returns(_mockBlobMetadata); _mockStorageBlob.Setup(p => p.SetMetadataAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); _mockStorageBlob.Setup(p => p.ReleaseLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); SingletonAttribute attribute = new SingletonAttribute(); RenewableLockHandle lockHandle = await _singletonManager.TryLockAsync(TestLockId, TestInstanceId, attribute, cancellationToken); var innerHandle = lockHandle.GetInnerHandle(); Assert.Equal(_mockStorageBlob.Object, innerHandle.Blob); Assert.Equal(TestLeaseId, innerHandle.LeaseId); Assert.Equal(1, _mockStorageBlob.Object.Metadata.Keys.Count); Assert.Equal(_mockStorageBlob.Object.Metadata[StorageBaseDistributedLockManager.FunctionInstanceMetadataKey], TestInstanceId); } [Fact] public async Task TryLockAsync_CreatesBlobLease_WithAutoRenewal() { CancellationToken cancellationToken = new CancellationToken(); //_mockStorageBlob.SetupGet(p => p.Metadata).Returns(_mockBlobMetadata); MockAcquireLeaseAsync(null, () => TestLeaseId); _mockStorageBlob.Setup(p => p.SetMetadataAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); _mockStorageBlob.Setup(p => p.ReleaseLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); int renewCount = 0; _mockStorageBlob.Setup(p => p.RenewLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, It.IsAny<CancellationToken>())) .Callback<AccessCondition, BlobRequestOptions, OperationContext, CancellationToken>( (mockAccessCondition, mockOptions, mockContext, mockCancellationToken) => { renewCount++; }).Returns(Task.FromResult(true)); SingletonAttribute attribute = new SingletonAttribute(); var lockHandle = await _singletonManager.TryLockAsync(TestLockId, TestInstanceId, attribute, cancellationToken); var innerHandle = lockHandle.GetInnerHandle(); Assert.Equal(_mockStorageBlob.Object, innerHandle.Blob); Assert.Equal(TestLeaseId, innerHandle.LeaseId); Assert.Equal(1, _mockStorageBlob.Object.Metadata.Keys.Count); Assert.Equal(_mockStorageBlob.Object.Metadata[StorageBaseDistributedLockManager.FunctionInstanceMetadataKey], TestInstanceId); // wait for enough time that we expect some lease renewals to occur int duration = 2000; int expectedRenewalCount = (int)(duration / (_singletonConfig.LockPeriod.TotalMilliseconds / 2)) - 1; await Task.Delay(duration); Assert.Equal(expectedRenewalCount, renewCount); // now release the lock and verify no more renewals await _singletonManager.ReleaseLockAsync(lockHandle, cancellationToken); // verify the logger TestLogger logger = _loggerProvider.CreatedLoggers.Single() as TestLogger; Assert.Equal(LogCategories.Singleton, logger.Category); var messages = logger.GetLogMessages(); Assert.Equal(2, messages.Count); Assert.NotNull(messages.Single(m => m.Level == Microsoft.Extensions.Logging.LogLevel.Debug && m.FormattedMessage == "Singleton lock acquired (testid)")); Assert.NotNull(messages.Single(m => m.Level == Microsoft.Extensions.Logging.LogLevel.Debug && m.FormattedMessage == "Singleton lock released (testid)")); renewCount = 0; await Task.Delay(1000); Assert.Equal(0, renewCount); _mockStorageBlob.VerifyAll(); } [Fact] public async Task TryLockAsync_WithContention_PollsForLease() { CancellationToken cancellationToken = new CancellationToken(); // _mockStorageBlob.SetupGet(p => p.Metadata).Returns(_mockBlobMetadata); _mockStorageBlob.Setup(p => p.SetMetadataAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); int numRetries = 3; int count = 0; MockAcquireLeaseAsync(null, () => { count++; return count > numRetries ? TestLeaseId : null; }); SingletonAttribute attribute = new SingletonAttribute(); var lockHandle = await _singletonManager.TryLockAsync(TestLockId, TestInstanceId, attribute, cancellationToken); var innerHandle = lockHandle.GetInnerHandle(); Assert.NotNull(lockHandle); Assert.Equal(TestLeaseId, innerHandle.LeaseId); Assert.Equal(numRetries, count - 1); Assert.NotNull(lockHandle.LeaseRenewalTimer); _mockStorageBlob.VerifyAll(); } [Fact] public async Task TryLockAsync_WithContention_NoRetry_DoesNotPollForLease() { CancellationToken cancellationToken = new CancellationToken(); int count = 0; MockAcquireLeaseAsync(null, () => { count++; return null; }); SingletonAttribute attribute = new SingletonAttribute(); SingletonLockHandle lockHandle = await _singletonManager.TryLockInternalAsync(TestLockId, TestInstanceId, attribute, cancellationToken, retry: false); Assert.Null(lockHandle); Assert.Equal(1, count); _mockStorageBlob.VerifyAll(); } // Helper to setup mock since the signatures are very complex private void MockAcquireLeaseAsync(Action fpAction, Func<string> returns) { _mockStorageBlob.Setup( p => p.AcquireLeaseAsync(_singletonConfig.LockPeriod, null, It.IsAny<AccessCondition>(), It.IsAny<BlobRequestOptions>(), It.IsAny<OperationContext>(), It.IsAny<CancellationToken>()) ) .Callback<TimeSpan?, string, AccessCondition, BlobRequestOptions, OperationContext, CancellationToken>( (mockPeriod, mockLeaseId, accessCondition, blobRequest, opCtx, cancelToken) => { fpAction?.Invoke(); }).Returns(() => { var retResult = returns(); return Task.FromResult<string>(retResult); }); } private void MockFetchAttributesAsync(Action fpAction) { _mockStorageBlob.Setup( p => p.FetchAttributesAsync(It.IsAny<AccessCondition>(), It.IsAny<BlobRequestOptions>(), It.IsAny<OperationContext>(), It.IsAny<CancellationToken>()) ) .Callback<AccessCondition, BlobRequestOptions, OperationContext, CancellationToken>( (accessCondition, blobRequest, opCtx, cancelToken) => { fpAction?.Invoke(); }).Returns(() => { return Task.CompletedTask; }); } [Fact] public async Task LockAsync_WithContention_AcquisitionTimeoutExpires_Throws() { CancellationToken cancellationToken = new CancellationToken(); int count = 0; MockAcquireLeaseAsync(() => { ++count; }, () => null); SingletonAttribute attribute = new SingletonAttribute(); TimeoutException exception = await Assert.ThrowsAsync<TimeoutException>(async () => await _singletonManager.LockAsync(TestLockId, TestInstanceId, attribute, cancellationToken)); int expectedRetryCount = (int)(_singletonConfig.LockAcquisitionTimeout.TotalMilliseconds / _singletonConfig.LockAcquisitionPollingInterval.TotalMilliseconds); Assert.Equal(expectedRetryCount, count - 1); Assert.Equal("Unable to acquire singleton lock blob lease for blob 'testid' (timeout of 0:00:00.2 exceeded).", exception.Message); _mockStorageBlob.VerifyAll(); } [Fact] public async Task ReleaseLockAsync_StopsRenewalTimerAndReleasesLease() { CancellationToken cancellationToken = new CancellationToken(); Mock<ITaskSeriesTimer> mockRenewalTimer = new Mock<ITaskSeriesTimer>(MockBehavior.Strict); mockRenewalTimer.Setup(p => p.StopAsync(cancellationToken)).Returns(Task.FromResult(true)); _mockStorageBlob.Setup(p => p.ReleaseLeaseAsync(It.Is<AccessCondition>(q => q.LeaseId == TestLeaseId), null, null, cancellationToken)).Returns(Task.FromResult(true)); var handle = new RenewableLockHandle( new SingletonLockHandle { Blob = _mockStorageBlob.Object, LeaseId = TestLeaseId }, mockRenewalTimer.Object ); await _singletonManager.ReleaseLockAsync(handle, cancellationToken); mockRenewalTimer.VerifyAll(); } [Fact] public async Task GetLockOwnerAsync_LeaseLocked_ReturnsOwner() { MockFetchAttributesAsync(null); _mockStorageBlob.Object.Properties.SetLeaseState(LeaseState.Leased); SingletonAttribute attribute = new SingletonAttribute(); string lockOwner = await _singletonManager.GetLockOwnerAsync(attribute, TestLockId, CancellationToken.None); Assert.Equal(null, lockOwner); _mockStorageBlob.Object.Metadata.Add(StorageBaseDistributedLockManager.FunctionInstanceMetadataKey, TestLockId); lockOwner = await _singletonManager.GetLockOwnerAsync(attribute, TestLockId, CancellationToken.None); Assert.Equal(TestLockId, lockOwner); _mockStorageBlob.VerifyAll(); } [Fact] public async Task GetLockOwnerAsync_LeaseAvailable_ReturnsNull() { MockFetchAttributesAsync(null); _mockStorageBlob.Object.Properties.SetLeaseState(LeaseState.Available); _mockStorageBlob.Object.Properties.SetLeaseStatus(LeaseStatus.Unlocked); SingletonAttribute attribute = new SingletonAttribute(); string lockOwner = await _singletonManager.GetLockOwnerAsync(attribute, TestLockId, CancellationToken.None); Assert.Equal(null, lockOwner); _mockStorageBlob.VerifyAll(); } [Theory] [InlineData(SingletonScope.Function, null, "TestHostId/Microsoft.Azure.WebJobs.Host.UnitTests.Singleton.SingletonManagerTests.TestJob")] [InlineData(SingletonScope.Function, "", "TestHostId/Microsoft.Azure.WebJobs.Host.UnitTests.Singleton.SingletonManagerTests.TestJob")] [InlineData(SingletonScope.Function, "testscope", "TestHostId/Microsoft.Azure.WebJobs.Host.UnitTests.Singleton.SingletonManagerTests.TestJob.testscope")] [InlineData(SingletonScope.Host, "testscope", "TestHostId/testscope")] public void FormatLockId_ReturnsExpectedValue(SingletonScope scope, string scopeId, string expectedLockId) { MethodInfo methodInfo = this.GetType().GetMethod("TestJob", BindingFlags.Static | BindingFlags.NonPublic); var descriptor = FunctionIndexer.FromMethod(methodInfo); string actualLockId = SingletonManager.FormatLockId(descriptor, scope, "TestHostId", scopeId); Assert.Equal(expectedLockId, actualLockId); } [Fact] public void HostId_InvokesHostIdProvider_AndCachesResult() { Mock<IHostIdProvider> mockHostIdProvider = new Mock<IHostIdProvider>(MockBehavior.Strict); mockHostIdProvider.Setup(p => p.GetHostIdAsync(CancellationToken.None)).ReturnsAsync(TestHostId); SingletonManager singletonManager = new SingletonManager(null, new OptionsWrapper<SingletonOptions>(null), null, null, mockHostIdProvider.Object); Assert.Equal(TestHostId, singletonManager.HostId); Assert.Equal(TestHostId, singletonManager.HostId); Assert.Equal(TestHostId, singletonManager.HostId); mockHostIdProvider.Verify(p => p.GetHostIdAsync(It.IsAny<CancellationToken>()), Times.Once); } [Fact] public void GetBoundScopeId_Success_ReturnsExceptedResult() { Dictionary<string, object> bindingData = new Dictionary<string, object>(); bindingData.Add("Region", "testregion"); bindingData.Add("Zone", 1); string result = _singletonManager.GetBoundScopeId(@"{Region}\{Zone}", bindingData); Assert.Equal(@"testregion\1", result); } [Fact] public void GetBoundScopeId_BindingError_Throws() { // Missing binding data for "Zone" Dictionary<string, object> bindingData = new Dictionary<string, object>(); bindingData.Add("Region", "testregion"); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => _singletonManager.GetBoundScopeId(@"{Region}\{Zone}", bindingData)); Assert.Equal("No value for named parameter 'Zone'.", exception.Message); } [Theory] [InlineData("", "")] [InlineData("scope", "scope")] public void GetBoundScopeId_NullBindingDataScenarios_Succeeds(string scope, string expectedResult) { string result = _singletonManager.GetBoundScopeId(scope, null); Assert.Equal(expectedResult, result); } [Theory] [InlineData("", "")] [InlineData("scope", "scope")] [InlineData("scope{P1}", "scopeTest1")] [InlineData("scope:{P1}-{P2}", "scope:Test1-Test2")] [InlineData("%var1%", "Value1")] [InlineData("{P1}%var2%{P2}%var1%", "Test1Value2Test2Value1")] public void GetBoundScopeId_BindingDataScenarios_Succeeds(string scope, string expectedResult) { Dictionary<string, object> bindingData = new Dictionary<string, object>(); bindingData.Add("P1", "Test1"); bindingData.Add("P2", "Test2"); _nameResolver.Names.Add("var1", "Value1"); _nameResolver.Names.Add("var2", "Value2"); string result = _singletonManager.GetBoundScopeId(scope, bindingData); Assert.Equal(expectedResult, result); } [Fact] public void GetFunctionSingletonOrNull_ThrowsOnMultiple() { MethodInfo method = this.GetType().GetMethod("TestJob_MultipleFunctionSingletons", BindingFlags.Static | BindingFlags.NonPublic); NotSupportedException exception = Assert.Throws<NotSupportedException>(() => { SingletonManager.GetFunctionSingletonOrNull(new FunctionDescriptor() { SingletonAttributes = method.GetCustomAttributes<SingletonAttribute>() }, isTriggered: true); }); Assert.Equal("Only one SingletonAttribute using mode 'Function' is allowed.", exception.Message); } [Fact] public void GetFunctionSingletonOrNull_ListenerSingletonOnNonTriggeredFunction_Throws() { MethodInfo method = this.GetType().GetMethod("TestJob_ListenerSingleton", BindingFlags.Static | BindingFlags.NonPublic); NotSupportedException exception = Assert.Throws<NotSupportedException>(() => { SingletonManager.GetFunctionSingletonOrNull(new FunctionDescriptor() { SingletonAttributes = method.GetCustomAttributes<SingletonAttribute>() }, isTriggered: false); }); Assert.Equal("SingletonAttribute using mode 'Listener' cannot be applied to non-triggered functions.", exception.Message); } [Fact] public void GetListenerSingletonOrNull_ThrowsOnMultiple() { MethodInfo method = this.GetType().GetMethod("TestJob_MultipleListenerSingletons", BindingFlags.Static | BindingFlags.NonPublic); var descriptor = FunctionIndexer.FromMethod(method); NotSupportedException exception = Assert.Throws<NotSupportedException>(() => { SingletonManager.GetListenerSingletonOrNull(typeof(TestListener), descriptor); }); Assert.Equal("Only one SingletonAttribute using mode 'Listener' is allowed.", exception.Message); } [Fact] public void GetListenerSingletonOrNull_MethodSingletonTakesPrecedence() { MethodInfo method = this.GetType().GetMethod("TestJob_ListenerSingleton", BindingFlags.Static | BindingFlags.NonPublic); var descriptor = FunctionIndexer.FromMethod(method); SingletonAttribute attribute = SingletonManager.GetListenerSingletonOrNull(typeof(TestListener), descriptor); Assert.Equal("Function", attribute.ScopeId); } [Fact] public void GetListenerSingletonOrNull_ReturnsListenerClassSingleton() { MethodInfo method = this.GetType().GetMethod("TestJob", BindingFlags.Static | BindingFlags.NonPublic); var descriptor = FunctionIndexer.FromMethod(method); SingletonAttribute attribute = SingletonManager.GetListenerSingletonOrNull(typeof(TestListener), descriptor); Assert.Equal("Listener", attribute.ScopeId); } [Theory] [InlineData(SingletonMode.Function)] [InlineData(SingletonMode.Listener)] public void ValidateSingletonAttribute_ScopeIsHost_ScopeIdEmpty_Throws(SingletonMode mode) { SingletonAttribute attribute = new SingletonAttribute(null, SingletonScope.Host); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => { SingletonManager.ValidateSingletonAttribute(attribute, mode); }); Assert.Equal("A ScopeId value must be provided when using scope 'Host'.", exception.Message); } [Fact] public void ValidateSingletonAttribute_ScopeIsHost_ModeIsListener_Throws() { SingletonAttribute attribute = new SingletonAttribute("TestScope", SingletonScope.Host); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => { SingletonManager.ValidateSingletonAttribute(attribute, SingletonMode.Listener); }); Assert.Equal("Scope 'Host' cannot be used when the mode is set to 'Listener'.", exception.Message); } [Fact] public void GetLockPeriod_ReturnsExpectedValue() { SingletonAttribute attribute = new SingletonAttribute { Mode = SingletonMode.Listener }; var config = new SingletonOptions() { LockPeriod = TimeSpan.FromSeconds(16), ListenerLockPeriod = TimeSpan.FromSeconds(17) }; TimeSpan value = SingletonManager.GetLockPeriod(attribute, config); Assert.Equal(config.ListenerLockPeriod, value); attribute.Mode = SingletonMode.Function; value = SingletonManager.GetLockPeriod(attribute, config); Assert.Equal(config.LockPeriod, value); } [Fact] public void GetLockAcquisitionTimeout_ReturnsExpectedValue() { // override via attribute var method = GetType().GetMethod("TestJob_LockAcquisitionTimeoutOverride", BindingFlags.Static | BindingFlags.NonPublic); var attribute = method.GetCustomAttribute<SingletonAttribute>(); var config = new SingletonOptions(); var result = SingletonManager.GetLockAcquisitionTimeout(attribute, config); Assert.Equal(TimeSpan.FromSeconds(5), result); // when not set via attribute, defaults to config value attribute = new SingletonAttribute(); config.LockAcquisitionTimeout = TimeSpan.FromSeconds(3); result = SingletonManager.GetLockAcquisitionTimeout(attribute, config); Assert.Equal(config.LockAcquisitionTimeout, result); } private static void TestJob() { } [Singleton("Function", Mode = SingletonMode.Function, LockAcquisitionTimeout = 5)] private static void TestJob_LockAcquisitionTimeoutOverride() { } [Singleton("Function", Mode = SingletonMode.Listener)] private static void TestJob_ListenerSingleton() { } [Singleton("bar")] [Singleton("foo")] private static void TestJob_MultipleFunctionSingletons() { } [Singleton("bar", Mode = SingletonMode.Listener)] [Singleton("foo", Mode = SingletonMode.Listener)] private static void TestJob_MultipleListenerSingletons() { } [Singleton("Listener", Mode = SingletonMode.Listener)] private class TestListener { } private class TestNameResolver : INameResolver { public TestNameResolver() { Names = new Dictionary<string, string>(); } public Dictionary<string, string> Names { get; private set; } public string Resolve(string name) { if (Names.TryGetValue(name, out string value)) { return value; } throw new NotSupportedException(string.Format("Cannot resolve name: '{0}'", name)); } } } }
44.885671
233
0.65298
[ "MIT" ]
Nasicus/azure-webjobs-sdk
test/Microsoft.Azure.WebJobs.Host.FunctionalTests/Singleton/SingletonManagerTests.cs
29,447
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos { using System; using System.Net; using System.Threading; using System.Threading.Tasks; /// <summary> /// Cosmos Change Feed Iterator for a particular Partition Key Range /// </summary> internal class ChangeFeedPartitionKeyResultSetIteratorCore : FeedIterator { private readonly CosmosClientContext clientContext; private readonly ContainerCore container; private readonly ChangeFeedRequestOptions changeFeedOptions; private string continuationToken; private string partitionKeyRangeId; private bool hasMoreResultsInternal; internal ChangeFeedPartitionKeyResultSetIteratorCore( CosmosClientContext clientContext, ContainerCore container, string partitionKeyRangeId, string continuationToken, int? maxItemCount, ChangeFeedRequestOptions options) { if (container == null) { throw new ArgumentNullException(nameof(container)); } if (partitionKeyRangeId == null) { throw new ArgumentNullException(nameof(partitionKeyRangeId)); } this.clientContext = clientContext; this.container = container; this.changeFeedOptions = options; this.MaxItemCount = maxItemCount; this.continuationToken = continuationToken; this.partitionKeyRangeId = partitionKeyRangeId; } /// <summary> /// Gets or sets the maximum number of items to be returned in the enumeration operation in the Azure Cosmos DB service. /// </summary> public int? MaxItemCount { get; set; } public override bool HasMoreResults => this.hasMoreResultsInternal; /// <summary> /// Get the next set of results from the cosmos service /// </summary> /// <param name="cancellationToken">(Optional) <see cref="CancellationToken"/> representing request cancellation.</param> /// <returns>A change feed response from cosmos service</returns> public override Task<ResponseMessage> ReadNextAsync(CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return this.NextResultSetDelegateAsync(this.continuationToken, this.partitionKeyRangeId, this.MaxItemCount, this.changeFeedOptions, cancellationToken) .ContinueWith(task => { ResponseMessage response = task.Result; // Change Feed uses ETAG this.continuationToken = response.Headers.ETag; this.hasMoreResultsInternal = response.StatusCode != HttpStatusCode.NotModified; response.Headers.ContinuationToken = this.continuationToken; return response; }, cancellationToken); } private Task<ResponseMessage> NextResultSetDelegateAsync( string continuationToken, string partitionKeyRangeId, int? maxItemCount, ChangeFeedRequestOptions options, CancellationToken cancellationToken) { Uri resourceUri = this.container.LinkUri; return this.clientContext.ProcessResourceOperationAsync<ResponseMessage>( cosmosContainerCore: this.container, resourceUri: resourceUri, resourceType: Documents.ResourceType.Document, operationType: Documents.OperationType.ReadFeed, requestOptions: options, requestEnricher: request => { ChangeFeedRequestOptions.FillContinuationToken(request, continuationToken); ChangeFeedRequestOptions.FillMaxItemCount(request, maxItemCount); ChangeFeedRequestOptions.FillPartitionKeyRangeId(request, partitionKeyRangeId); }, responseCreator: response => response, partitionKey: null, streamPayload: null, cancellationToken: cancellationToken); } } }
42.817308
162
0.61554
[ "MIT" ]
SnehaGunda/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/Resource/QueryResponses/ChangeFeedPartitionKeyResultSetIteratorCore.cs
4,453
C#
using System; using Xunit.Internal; using Xunit.v3; namespace Xunit.Runner.Common { /// <summary> /// Logs diagnostic messages to the system console. /// </summary> public class ConsoleDiagnosticMessageSink : _IMessageSink { readonly string? assemblyDisplayName; readonly object consoleLock; readonly ConsoleColor displayColor; readonly bool noColor; ConsoleDiagnosticMessageSink( object consoleLock, string? assemblyDisplayName, bool noColor, ConsoleColor displayColor) { Guard.ArgumentNotNull(consoleLock); this.consoleLock = consoleLock; this.assemblyDisplayName = assemblyDisplayName; this.noColor = noColor; this.displayColor = displayColor; } /// <summary> /// Creates a message sink for public diagnostics. /// </summary> /// <param name="consoleLock">The console lock, used to prevent console contention</param> /// <param name="assemblyDisplayName">The display name for the test assembly</param> /// <param name="showDiagnostics">A flag to indicate whether to show public diagnostics</param> /// <param name="noColor">A flag to indicate whether to disable color output</param> public static ConsoleDiagnosticMessageSink? ForDiagnostics( object consoleLock, string assemblyDisplayName, bool showDiagnostics, bool noColor) => showDiagnostics ? new(consoleLock, assemblyDisplayName, noColor, ConsoleColor.Yellow) : null; /// <summary> /// Creates a message sink for internal diagnostics. /// </summary> /// <param name="consoleLock">The console lock, used to prevent console contention</param> /// <param name="assemblyDisplayName">The display name for the test assembly</param> /// <param name="showDiagnostics">A flag to indicate whether to show internal diagnostics</param> /// <param name="noColor">A flag to indicate whether to disable color output</param> public static ConsoleDiagnosticMessageSink? ForInternalDiagnostics( object consoleLock, string assemblyDisplayName, bool showDiagnostics, bool noColor) => showDiagnostics ? new(consoleLock, assemblyDisplayName, noColor, ConsoleColor.DarkGray) : null; /// <summary> /// Creates a message sink for internal diagnostics. /// </summary> /// <param name="consoleLock">The console lock, used to prevent console contention</param> /// <param name="showDiagnostics">A flag to indicate whether to show internal diagnostics</param> /// <param name="noColor">A flag to indicate whether to disable color output</param> public static ConsoleDiagnosticMessageSink? ForInternalDiagnostics( object consoleLock, bool showDiagnostics, bool noColor) => showDiagnostics ? new(consoleLock, null, noColor, ConsoleColor.DarkGray) : null; /// <inheritdoc/> public bool OnMessage(_MessageSinkMessage message) { Guard.ArgumentNotNull(message); if (message is _DiagnosticMessage diagnosticMessage) { lock (consoleLock) { if (!noColor) ConsoleHelper.SetForegroundColor(displayColor); if (assemblyDisplayName == null) Console.WriteLine(diagnosticMessage.Message); else Console.WriteLine($" {assemblyDisplayName}: {diagnosticMessage.Message}"); if (!noColor) ConsoleHelper.ResetColor(); } } return true; } } }
33.804124
99
0.732235
[ "Apache-2.0" ]
PKRoma/xunit
src/xunit.v3.runner.common/Sinks/ConsoleDiagnosticMessageSink.cs
3,281
C#
/* Copyright (C) 2011 Mark P Owen This file is part of XLW, a free-software/open-source C++ wrapper of the Excel C API - http://xlw.sourceforge.net/ XLW is free software: you can redistribute it and/or modify it under the terms of the XLW license. You should have received a copy of the license along with this program; if not, please email xlw-users@lists.sf.net This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ using System; namespace ReflectionFactory { [AttributeUsage(AttributeTargets.Constructor)] public class RegisterConstructorAttribute : Attribute { } }
30.6
78
0.756863
[ "MIT" ]
red2901/sandbox
xlw/xlw-5.0.2f0/xlwDotNet/Examples/ReflectionFactory/common_source/ReflectionFactory/RegisterConstructorAttribute.cs
767
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using BalancedCollections.RedBlackTree; namespace BalancedCollections.Tests.RedBlackTree { [TestFixture] [Parallelizable(ParallelScope.All)] public class KeyCollectionTests { [Test] public void CanConstructKeyCollections() { RedBlackTree<int, string> redBlackTree = new RedBlackTree<int, string> { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; ICollection<int> keys = redBlackTree.Keys; Assert.That(keys, Is.Not.Null); Assert.That(keys.Count, Is.EqualTo(5)); WeightedRedBlackTree<int, string> redBlackTree2 = new WeightedRedBlackTree<int, string> { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; keys = redBlackTree2.Keys; Assert.That(keys, Is.Not.Null); Assert.That(keys.Count, Is.EqualTo(5)); } [Test] public void CanEnumerateKeysNewSchool() { RedBlackTree<int, string> redBlackTree = new RedBlackTree<int, string> { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; ICollection<int> keys = redBlackTree.Keys; IEnumerator<int> enumerator = ((IEnumerable<int>)keys).GetEnumerator(); int[] expectedKeys = { 1, 2, 3, 4, 5 }; int index = 0; while (enumerator.MoveNext()) { Assert.That(enumerator.Current, Is.EqualTo(expectedKeys[index])); index++; } enumerator.Reset(); index = 0; while (enumerator.MoveNext()) { Assert.That(enumerator.Current, Is.EqualTo(expectedKeys[index])); index++; } } [Test] public void CanEnumerateKeysOldSchool() { RedBlackTree<int, string> redBlackTree = new RedBlackTree<int, string> { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; ICollection<int> keys = redBlackTree.Keys; IEnumerator enumerator = ((IEnumerable)keys).GetEnumerator(); int[] expectedKeys = { 1, 2, 3, 4, 5 }; int index = 0; while (enumerator.MoveNext()) { Assert.That((int)(enumerator.Current), Is.EqualTo(expectedKeys[index])); index++; } enumerator.Reset(); index = 0; while (enumerator.MoveNext()) { Assert.That((int)(enumerator.Current), Is.EqualTo(expectedKeys[index])); index++; } } [Test] public void CanModifyTheUnderlyingCollection() { RedBlackTree<int, string> redBlackTree = new RedBlackTree<int, string> { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; ICollection<int> keys = redBlackTree.Keys; keys.Add(6); List<KeyValuePair<int, string>> pairs = redBlackTree.Select(n => n.ToKeyValuePair()).ToList(); CollectionAssert.AreEqual(pairs, new[] { new KeyValuePair<int, string>(1, "1"), new KeyValuePair<int, string>(2, "2"), new KeyValuePair<int, string>(3, "3"), new KeyValuePair<int, string>(4, "4"), new KeyValuePair<int, string>(5, "5"), new KeyValuePair<int, string>(6, null), }); keys.Remove(3); pairs = redBlackTree.Select(n => n.ToKeyValuePair()).ToList(); CollectionAssert.AreEqual(pairs, new[] { new KeyValuePair<int, string>(1, "1"), new KeyValuePair<int, string>(2, "2"), new KeyValuePair<int, string>(4, "4"), new KeyValuePair<int, string>(5, "5"), new KeyValuePair<int, string>(6, null), }); keys.Clear(); pairs = redBlackTree.Select(n => n.ToKeyValuePair()).ToList(); CollectionAssert.AreEqual(pairs, new KeyValuePair<int, string>[0]); } [Test] public void CanCopyToAnArray() { RedBlackTree<int, string> redBlackTree = new RedBlackTree<int, string> { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; ICollection<int> keys = redBlackTree.Keys; int[] keyArray = keys.ToArray(); CollectionAssert.AreEqual(keyArray, new[] { 1, 2, 3, 4, 5 }); } [Test] public void CanTestForContainment() { RedBlackTree<int, string> redBlackTree = new RedBlackTree<int, string> { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; ICollection<int> keys = redBlackTree.Keys; Assert.That(keys.Contains(3), Is.True); Assert.That(keys.Contains(6), Is.False); } [Test] public void ReadOnlyShouldMirrorTheUnderlyingCollection() { RedBlackTree<int, string> redBlackTree = new RedBlackTree<int, string> { { 1, "1" }, { 2, "2" }, { 3, "3" }, { 4, "4" }, { 5, "5" }, }; ICollection<int> keys = redBlackTree.Keys; Assert.That(keys.IsReadOnly, Is.False); ReadOnlyRedBlackTree<int, string> readOnlyTree = new ReadOnlyRedBlackTree<int, string>(redBlackTree); keys = readOnlyTree.Keys; Assert.That(keys.IsReadOnly, Is.True); } } }
23.641509
105
0.570032
[ "MIT" ]
seanofw/balanced-collections
BalancedCollections.Tests/RedBlackTree/KeyCollectionTests.cs
5,012
C#
using System; namespace EOLib.Net { public class NoDataSentException : Exception { public NoDataSentException() : base("No data was sent to the server.") { } } }
17.818182
57
0.612245
[ "MIT" ]
Septharoth/EndlessClient
EOLib/Net/NoDataSentException.cs
198
C#
namespace Heizung.ServerDotNet.Migrations { using FluentMigrator; /// <summary> /// Fügt der Tabelle ErrorList ein Autoincrement auf Id hinzu /// </summary> [Migration(3, "Fügt der Tabelle ErrorList ein Autoincrement auf Id hinzu.")] public class _0003_ErrorTableAutoincrement : Migration { #region Up /// <summary> /// Migriert zur nächsten Version /// </summary> public override void Up() { base.Execute.Sql("ALTER TABLE Heizung.ErrorList MODIFY COLUMN Id int(10) unsigned auto_increment NOT NULL COMMENT 'Die Id vom Error.';"); } #endregion #region Down /// <summary> /// Migriert zur vorherigen Version /// </summary> public override void Down() { base.Execute.Script("ALTER TABLE Heizung.ErrorList MODIFY COLUMN Id int(10) unsigned NOT NULL COMMENT 'Die Id vom Error.';"); } #endregion } } //ALTER TABLE Heizung.ErrorList MODIFY COLUMN Id int(10) unsigned auto_increment NOT NULL COMMENT 'Die Id vom Error.';
32.382353
149
0.623978
[ "MIT" ]
Orangenkuchen/Heizung.ServerDotNet
Migrations/0003_ErrorTableAutoincrement.cs
1,104
C#
using System; namespace TypeScriptCompileOnSave { public class Constants { public const int CompileTimeout = 10; // seconds public const string ConfigFileName = "tsconfig.json"; public static string TscLocation = Environment.ExpandEnvironmentVariables(@"%programfiles(x86)%\Microsoft SDKs\TypeScript\"); public static string[] FileExtensions = { ".js", ".jsx" }; public static string[] ProjectGuids = { "{9A19103F-16F7-4668-BE54-9A1E7A4F7556}", // ASP.NET Core "{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}", // Project K }; public const string DefaultTsConfig = @"{{ ""compileOnSave"": true, ""compilerOptions"": {{ ""allowJs"": true, ""sourceMap"": true, ""jsx"": ""react"", ""outFile"": ""wwwroot/js/bundle.js"" }}, ""files"": [ ""{0}"" ] }}"; } }
24.864865
133
0.567391
[ "Apache-2.0" ]
interoptech/TypeScriptCompileOnSave
src/Constants.cs
922
C#
using System; using XamarinEvolve.DataObjects; using XamarinEvolve.DataStore.Abstractions; namespace XamarinEvolve.DataStore.Azure { public class EventStore : BaseStore<FeaturedEvent>, IEventStore { public override string Identifier => "FeaturedEvent"; public EventStore() { } } }
20.058824
67
0.668622
[ "MIT" ]
chhari/XamarinNewMemeApp
src/XamarinEvolve.DataStore.Azure/Stores/EventStore.cs
343
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingObstacleReaction : MonoBehaviour { public float Speed; public Transform distanceToPlayer; Player player; public bool b=false; void Start() { this.player = GameObject.Find("Player").GetComponent<Player>(); } // Update is called once per frame void Update () { if (CheckDistance()) { React(); } if (b) { print("obstacle : " + distanceToPlayer.position.x); print("player : " + player.transform.position.x); } } public void ReactTo(Player obj) { if (obj != null) this.player = obj; } bool CheckDistance() { bool d=false; if (player != null && distanceToPlayer!=null) { d = (distanceToPlayer.position.x - player.transform.position.x) <= 0; } return d; } void React() { this.GetComponent<Rigidbody2D>().velocity = new Vector2(Speed, GetComponent<Rigidbody2D>().velocity.y); } }
21.264151
111
0.561668
[ "MIT" ]
ardasatata/RushArea-DynamicLight
Assets/Scripts/ObstacleScripts/MovingObstacleReaction.cs
1,129
C#
namespace SFA.Apprenticeships.Infrastructure.VacancyIndexer.Mappers { using Application.Vacancies.Entities; using Common.Mappers; using Elastic.Common.Entities; public class VacancyIndexerMapper : MapperEngine { public override void Initialise() { Mapper.CreateMap<ApprenticeshipSummaryUpdate, ApprenticeshipSummary>() .ForMember(d => d.Location, opt => opt.ResolveUsing<GeoPointDomainToElasticResolver>().FromMember(src => src.Location)) .ForMember(d => d.WageType, opt => opt.MapFrom(src => src.Wage.Type)) .ForMember(d => d.WageAmount, opt => opt.MapFrom(src => src.Wage.Amount)) .ForMember(d => d.WageAmountLowerBound, opt => opt.MapFrom(src => src.Wage.AmountLowerBound)) .ForMember(d => d.WageAmountUpperBound, opt => opt.MapFrom(src => src.Wage.AmountUpperBound)) .ForMember(d => d.WageText, opt => opt.MapFrom(src => src.Wage.Text)) .ForMember(d => d.WageUnit, opt => opt.MapFrom(src => src.Wage.Unit)) .ForMember(d => d.HoursPerWeek, opt => opt.MapFrom(src => src.Wage.HoursPerWeek)) .ForMember(d => d.AnonymousEmployerName, opt => opt.MapFrom(src => src.AnonymousEmployerName)); Mapper.CreateMap<TraineeshipSummaryUpdate, TraineeshipSummary>() .ForMember(d => d.Location, opt => opt.ResolveUsing<GeoPointDomainToElasticResolver>().FromMember(src => src.Location)); } } }
56.851852
135
0.633225
[ "MIT" ]
BugsUK/FindApprenticeship
src/SFA.Apprenticeships.Infrastructure.VacancyIndexer/Mappers/VacancyIndexerMapper.cs
1,537
C#
namespace EateryPOSSystem.Models.Storekeeper { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using EateryPOSSystem.Services.Models; using static Data.DataConstants; public class AddProviderFormModel { [Required] [StringLength(ProviderNameMaxLength, MinimumLength = ProviderNameMinLength)] public string Name { get; init; } [Range(0, int.MaxValue)] public int Number { get; init; } public int CityId { get; init; } public int AddressId { get; init; } public IEnumerable<AddressServiceModel> Addresses { get; set; } public IEnumerable<CityServiceModel> Cities { get; set; } } }
27.5
84
0.675524
[ "MIT" ]
ismailsirakov/ASP.NET-Core-Project-Eatery-POS-System
EateryPOSSystem/Models/Storekeeper/AddProviderFormModel.cs
715
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Linq; namespace Gyomu.Access { public class MarketDateAccess { public enum SupportMarket { [Description("JP")] Japan } private string Market { get; set; } List<DateTime> holidays = null; static Dictionary<string, DateTime> dictMarketLastReferenceTime = new Dictionary<string, DateTime>(); static Dictionary<string, List<DateTime>> dictMarketHolidays = new Dictionary<string, List<DateTime>>(); public MarketDateAccess(SupportMarket market) { Market = EnumAccess.GetEnumValueDescription(market); init(); } private void init() { lock (dictMarketHolidays) { lock (dictMarketLastReferenceTime) { if (dictMarketLastReferenceTime.ContainsKey(Market) && dictMarketHolidays.ContainsKey(Market) && DateTime.UtcNow.Subtract(dictMarketLastReferenceTime[Market]).TotalMinutes < 15) { holidays = dictMarketHolidays[Market]; return; } try { using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Suppress)) { holidays = Common.GyomuDataAccess.ListHoliday(Market); if (dictMarketHolidays.ContainsKey(Market) == false) dictMarketHolidays.Add(Market, holidays); else dictMarketHolidays[Market] = holidays; if (dictMarketLastReferenceTime.ContainsKey(Market) == false) dictMarketLastReferenceTime.Add(Market, DateTime.UtcNow); else dictMarketLastReferenceTime[Market] = DateTime.UtcNow; } } catch (Exception ex) { if (dictMarketHolidays.ContainsKey(Market)) holidays = dictMarketHolidays[Market]; else throw ex; } } } } public int MarketOffset(DateTime targetDate, DateTime offsetDate) { if (targetDate.Equals(offsetDate)) return 0; int iMove = 1; if (targetDate < offsetDate) { iMove = -1; } DateTime tmpDate = offsetDate; int iOffset = 0; while (tmpDate.Equals(targetDate) == false) { tmpDate = GetBusinessDay(tmpDate, iMove); iOffset += iMove; } return iOffset; } public DateTime GetBusinessDay(DateTime targetDate, int days) { if (days == 0) throw new InvalidOperationException("days need to be non-zero"); if (days > 0) return getNextBusinessDay(targetDate, days); else return getPreviousBusinessDay(targetDate, Math.Abs(days)); } private DateTime getNextBusinessDay(DateTime targetDate, int days) { if (days <= 0) throw new InvalidOperationException("Negative value not allowed"); DateTime busDay = targetDate; while (days > 0) { busDay = busDay.AddDays(1); if (_isBusinessDay(busDay)) days--; } return busDay; } private DateTime getPreviousBusinessDay(DateTime targetDate, int days) { if (days <= 0) throw new InvalidOperationException("Negative value not allowed"); DateTime busDay = targetDate; while (days > 0) { busDay = busDay.AddDays(-1); if (_isBusinessDay(busDay)) days--; } return busDay; } public DateTime GetBusinessDayOfBeginningMonthWithOffset(DateTime targetDate, int offsetDays=1) { DateTime dtBBOM = new DateTime(targetDate.Year, targetDate.Month, 1); if (IsBusinessDay(dtBBOM)) if (offsetDays > 1) return GetBusinessDay(dtBBOM, offsetDays - 1); else return dtBBOM; return GetBusinessDay(dtBBOM, offsetDays); } public DateTime GetBusinessDayOfNextBeginningMonthWithOffset(DateTime targetDate, int offsetDays = 1) { DateTime dtNextBBOM = new DateTime(targetDate.Year + (targetDate.Month == 12 ? 1 : 0), targetDate.Month + (targetDate.Month == 12 ? -11 : 1), 1); DateTime dtTmpNextBBOM = dtNextBBOM; if (IsBusinessDay(dtNextBBOM)) { if (offsetDays > 1) dtTmpNextBBOM = GetBusinessDay(dtNextBBOM, offsetDays - 1); } else dtTmpNextBBOM = GetBusinessDay(dtNextBBOM, offsetDays); if (dtTmpNextBBOM.Equals(targetDate) || targetDate > dtTmpNextBBOM) { dtNextBBOM = dtNextBBOM.AddMonths(1); if (IsBusinessDay(dtNextBBOM)) { if (offsetDays > 1) dtTmpNextBBOM = GetBusinessDay(dtNextBBOM, offsetDays - 1); } else dtTmpNextBBOM = GetBusinessDay(dtNextBBOM, offsetDays); } return dtTmpNextBBOM; } public DateTime GetBusinessDayOfPreviousBeginningMonthWithOffset(DateTime targetDate, int offsetDays = 1) { DateTime dtPrevBBOM = new DateTime(targetDate.Year + (targetDate.Month == 1 ? -1 : 0), targetDate.Month + (targetDate.Month == 1 ? 11 : 1), 1); DateTime dtTmpPrevBBOM = dtPrevBBOM; if (IsBusinessDay(dtPrevBBOM)) { if (offsetDays > 1) dtTmpPrevBBOM = GetBusinessDay(dtPrevBBOM, offsetDays - 1); } else dtTmpPrevBBOM = GetBusinessDay(dtPrevBBOM, offsetDays); if (dtTmpPrevBBOM.Equals(targetDate) || targetDate > dtTmpPrevBBOM) { dtPrevBBOM = dtPrevBBOM.AddMonths(1); if (IsBusinessDay(dtPrevBBOM)) { if (offsetDays > 1) dtTmpPrevBBOM = GetBusinessDay(dtPrevBBOM, offsetDays - 1); } else dtTmpPrevBBOM = GetBusinessDay(dtPrevBBOM, offsetDays); } return dtTmpPrevBBOM; } public DateTime GetBusinessDayOfEndMonthWithOffset(DateTime targetDate,int offsetDays) { DateTime dtEBOM = new DateTime(targetDate.Year + (targetDate.Month == 12 ? 1 : 0), targetDate.Month + (targetDate.Month == 12 ? -11 : 1), 1); return GetBusinessDay(dtEBOM, -offsetDays); } public DateTime GetBusinessDayOfNextEndMonthWithOffset(DateTime targetDate,int offsetDays) { DateTime dtNextEBOM = new DateTime(targetDate.Year + (targetDate.Month == 12 ? 1 : 0), targetDate.Month + (targetDate.Month == 12 ? -11 : 1), 1); DateTime dtTmpNextEBOM = GetBusinessDay(dtNextEBOM, -offsetDays); if (targetDate.Equals(dtTmpNextEBOM) || targetDate < dtTmpNextEBOM) { dtNextEBOM = dtNextEBOM.AddMonths(1); dtTmpNextEBOM = GetBusinessDay(dtNextEBOM, -offsetDays); } return dtTmpNextEBOM; } public DateTime GetBusinessDayOfPreviousEndMonthWithOffset(DateTime targetDate,int offsetDays) { DateTime dtPREEBOM = new DateTime(targetDate.Year, targetDate.Month, 1); return GetBusinessDay(dtPREEBOM, -offsetDays); } public DateTime GetBusinessDayOfBeginningOfYear(DateTime targetDate, int offsetDays) { DateTime dtBBOY = new DateTime(targetDate.Year, 1, 1); if (IsBusinessDay(dtBBOY)) return GetBusinessDay(dtBBOY, offsetDays - 1); else return GetBusinessDay(dtBBOY, offsetDays); } public DateTime GetBusinessDayOfEndOfYear(DateTime targetDate, int offsetDays) { DateTime dtBEOY = new DateTime(targetDate.Year + 1, 1, 1); return GetBusinessDay(dtBEOY, -offsetDays); } public bool IsBusinessDay(DateTime targetDate) { return _isBusinessDay(targetDate); } private bool _isBusinessDay(DateTime targetDate) { switch (targetDate.DayOfWeek) { case DayOfWeek.Saturday: case DayOfWeek.Sunday: return false; default: int cnt = holidays.Count(h => h.Equals(targetDate)); if (cnt > 0) return false; return true; } } } }
41.101266
171
0.517503
[ "MIT" ]
Yoshihisa-Matsumoto/Gyomu
Gyomu/Access/MarketDateAccess.cs
9,743
C#
using System; using Newtonsoft.Json; namespace Nindo.Net.Models { public class StreamHours { [JsonProperty("stop")] public DateTime Stop { get; set; } [JsonProperty("start")] public DateTime Start { get; set; } } }
18.714286
43
0.599237
[ "MIT" ]
Stefaaaaaaaaaaan/Nindo.Net
src/Nindo.Net/Models/StreamHours.cs
264
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generation date: 10/4/2020 2:55:10 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for RetailKitOrderType in the schema. /// </summary> public enum RetailKitOrderType { AssemblyOrder = 0, DisassemblyOrder = 1 } }
30.130435
81
0.497835
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/RetailKitOrderType.cs
695
C#
using AleRoe.HomematicIpApi.Model.Channels; using AleRoe.HomematicIpApi.Tests; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using AleRoe.HomematicIpApi.Json; namespace AleRoe.HomematicIpApi.Tests.Json { [TestFixture()] public class DictionaryToListConverterTests { private static IEnumerable<TestCaseData> AddCases() { string path = @"TestData\DictionaryToListConverter"; var files = Directory.GetFiles(path, "*.json"); foreach (var file in files) { //var typeName = $"AleRoe.HomematicIpApi.Model.Channels.{Path.GetFileNameWithoutExtension(file)}"; //var type = typeof(FunctionalChannelConverter).Assembly.GetType(typeName, true); var type = typeof(List<IFunctionalChannel>); yield return new TestCaseData(file, type); } } [Test, TestCaseSource(nameof(AddCases))] public void TestConversion(string filePath, Type type) { var json = File.ReadAllText(filePath); var settings = JsonAssert.GetJsonSerializerSettings() .AddConverter(new DictionaryToListConverter<IFunctionalChannel>()); JsonAssert.Deserialize(json, type, settings, out var result); JsonAssert.Serialize(result, settings, out var jsonResult); JsonAssert.AreDeepEqual(json, jsonResult); } } }
36.8
114
0.652174
[ "MIT" ]
AleRoe/HomematicIPApi
AleRoe.HomematicIPApi.Tests/Json/DictionaryToListConverterTests.cs
1,474
C#
namespace SE_training.Server.Controllers { public class RatingController : ControllerBase { private readonly IRatingRepository _repository; private readonly ILogger<RatingController> _logger; public RatingController(ILogger<RatingController> logger, IRatingRepository repository) { _logger = logger; _repository = repository; } public Task<Status> DeleteRating(int ratingID) { return _repository.DeleteAsync(ratingID); } public Task<(Status status, RatingDTO rating)> CreateRating(CreateRatingDTO rating) { return _repository.CreateAsync(rating); } public Task<IReadOnlyCollection<RatingDTO>> ReadAllRatings(int MaterialId) { return _repository.ReadAsync(MaterialId); } public async Task<Status> DeleteAllRatings(int materialId) => await _repository.DeleteAllAsync(materialId); } }
31.580645
115
0.6619
[ "MIT" ]
nissemand243/Dwarfs_and_Giants
Server/Controllers/RatingController.cs
979
C#
// ----------------------------------------------------------------- // <copyright file="MechanicsConstants.cs" company="2Dudes"> // Copyright (c) | Jose L. Nunez de Caceres et al. // https://linkedin.com/in/nunezdecaceres // // All Rights Reserved. // // Licensed under the MIT License. See LICENSE in the project root for license information. // </copyright> // ----------------------------------------------------------------- namespace Fibula.Mechanics.Contracts.Constants { /// <summary> /// Static class that contains mechanics constants. /// </summary> public static class MechanicsConstants { /// <summary> /// A default value to use when calculating movement penalty. /// </summary> public const int DefaultGroundMovementPenaltyInMs = 150; } }
32.44
91
0.55857
[ "MIT" ]
jlnunez89/fibula-mmo
src/Fibula.Mechanics.Contracts/Constants/MechanicsConstants.cs
813
C#
// string.Format("Foo: {0}", foo); //
9.5
31
0.5
[ "MIT" ]
HighSchoolHacking/GLS-Draft
test/integration/StringFormat/one input.cs
38
C#
using AspectCore.Extensions.DependencyInjection; using AspectCore.Injector; using Microsoft.Extensions.DependencyInjection; using System; using xLiAd.Limiter.Core; using xLiAd.Limiter.Memory; using Xunit; namespace xLiAd.Limiter.Tests { public class TestOfMemory { private ISampleService Before() { IServiceCollection services = new ServiceCollection(); services.AddSingleton<ISampleService, SampleService>(); services.AddLimiterMemory(); var container = services.ToServiceContainer(); var sr = container.Build(); var serv = sr.GetService<ISampleService>(); return serv; } [Fact] public void TestService1() { var serv = Before(); serv.DoSomething(); serv.DoSomething(); Assert.Throws<AspectCore.DynamicProxy.AspectInvocationException>(serv.DoSomething); } [Fact] public void TestService2() { var serv = Before(); serv.DoSomething(2); serv.DoSomething(2); serv.DoSomething(2); serv.DoSomething(3); Assert.Throws<AspectCore.DynamicProxy.AspectInvocationException>(() => serv.DoSomething(2)); serv.DoSomething(3); } [Fact] public void TestService3() { var serv = Before(); serv.DoSomething(2, "a"); serv.DoSomething(2, null); serv.DoSomething(2, string.Empty); } [Fact] public void TestLimitPolicy1() { var limitPolicy = new DefaultLimitPolicyProvider(); var lp = limitPolicy.ParsePolicy("2seconds:50;1minutes:100"); Assert.Equal(2, lp.Count); Assert.Equal(50, lp[2]); Assert.Equal(100, lp[60]); } [Fact] public void TestKeyProvider() { var keyProvider = new DefaultKeyProvider(); var p1 = new P() { P1 = 1, P2 = "abc" }; var p2 = new P() { P3 = p1 }; var key = keyProvider.ProvideKey(Abstractions.KeyTypeEnum.InParam, new object[] { p1, p2 }, null, "1:P1;2:P3:P2"); Assert.Equal("1-abc", key); } } }
28.271605
126
0.557205
[ "Apache-2.0" ]
zl33842901/Limiter
xLiAd.Limiter.Tests/TestOfMemory.cs
2,290
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace EliteQuant { public class GaussKronrodNonAdaptive : global::System.IDisposable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; internal GaussKronrodNonAdaptive(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(GaussKronrodNonAdaptive obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~GaussKronrodNonAdaptive() { Dispose(); } public virtual void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_GaussKronrodNonAdaptive(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); } } public GaussKronrodNonAdaptive(double absoluteAccuracy, uint maxEvaluations, double relativeAccuracy) : this(NQuantLibcPINVOKE.new_GaussKronrodNonAdaptive(absoluteAccuracy, maxEvaluations, relativeAccuracy), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } } }
36.82
217
0.67409
[ "Apache-2.0" ]
qg0/EliteQuant_Excel
SwigConversionLayer/csharp/GaussKronrodNonAdaptive.cs
1,841
C#
using System; using System.Collections.Generic; using System.Text; namespace Algorithms.Test.Typical { public class SearchTest { } }
12.333333
33
0.716216
[ "Apache-2.0" ]
Library-Starlight/ProgramerCore
Algorithms/Algorithms.Test/Typical/SearchTest.cs
150
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; /// <summary> /// The type ListOperationsCollectionRequestBuilder. /// </summary> public partial class ListOperationsCollectionRequestBuilder : BaseRequestBuilder, IListOperationsCollectionRequestBuilder { /// <summary> /// Constructs a new ListOperationsCollectionRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public ListOperationsCollectionRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public IListOperationsCollectionRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public IListOperationsCollectionRequest Request(IEnumerable<Option> options) { return new ListOperationsCollectionRequest(this.RequestUrl, this.Client, options); } /// <summary> /// Gets an <see cref="IRichLongRunningOperationRequestBuilder"/> for the specified ListRichLongRunningOperation. /// </summary> /// <param name="id">The ID for the ListRichLongRunningOperation.</param> /// <returns>The <see cref="IRichLongRunningOperationRequestBuilder"/>.</returns> public IRichLongRunningOperationRequestBuilder this[string id] { get { return new RichLongRunningOperationRequestBuilder(this.AppendSegmentToRequestUrl(id), this.Client); } } } }
38.227273
153
0.596512
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/ListOperationsCollectionRequestBuilder.cs
2,523
C#
using System.Collections.Generic; using Intersect.Server.Web.RestApi.Middleware; using JetBrains.Annotations; using Microsoft.Owin; using Owin; namespace Intersect.Server.Web.RestApi.Authentication.OAuth { // ReSharper disable once InconsistentNaming /// <summary> /// /// </summary> public static class IAppBuilderExtensions { /// <summary> /// /// </summary> /// <param name="appBuilder"></param> /// <param name="requestMap"></param> /// <returns></returns> public static IAppBuilder UseContentTypeMappingMiddleware( [NotNull] this IAppBuilder appBuilder, [NotNull] IDictionary<(PathString, string, string), RequestMapFunc> requestMap ) { return appBuilder.Use<ContentTypeMappingMiddleware>(requestMap); } } }
22.868421
90
0.629459
[ "Unlicense" ]
Claytoo/Archisect-Online
Intersect.Server/Web/RestApi/Authentication/OAuth/IAppBuilderExtensions.cs
871
C#
using System; namespace Parquet.Data { /// <summary> /// Represents a list of items. The list can contain either a normal data field or a complex structure. /// If you need to get a list of primitive data fields it's more efficient to use arrays. /// </summary> public class ListField : Field, IEquatable<ListField> { internal const string _containerName = "list"; /// <summary> /// Item contained within this list /// </summary> public Field Item { get; internal set; } /// <summary> /// Creates a new instance of <see cref="ListField"/> /// </summary> /// <param name="name">Field name</param> /// <param name="item">Field representing list element</param> public ListField(string name, Field item) : this(name) { Item = item ?? throw new ArgumentNullException(nameof(item)); PathPrefix = null; } private ListField(string name) : base(name, SchemaType.List) { } internal override string PathPrefix { set { Path = value.AddPath(Name, _containerName); Item.PathPrefix = Path; } } /// <summary> /// </summary> public override string ToString() { return $"{Name}: ({Item})"; } internal static ListField CreateWithNoItem(string name) { return new ListField(name); } internal override void Assign(Field field) { if(Item != null) { throw new InvalidOperationException($"item was already assigned to this list ({Name}), somethin is terribly wrong because a list can only have one item."); } Item = field ?? throw new ArgumentNullException(nameof(field)); } /// <summary> /// </summary> public bool Equals(ListField other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Name.Equals(other.Name) && Item.Equals(other.Item); } /// <summary> /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((ListField)obj); } /// <summary> /// </summary> public override int GetHashCode() { return Name.GetHashCode() * Item.GetHashCode(); } } }
27.387097
167
0.572438
[ "MIT" ]
corrego/parquet-dotnet
src/Parquet/Data/Schema/ListField.cs
2,549
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace Microting.EformMonitoringBase.Migrations { public partial class AddDeviceUsers : Migration { protected override void Up(MigrationBuilder migrationBuilder) { //Setup for SQL Server Provider var autoIdGenStrategy = "SqlServer:ValueGenerationStrategy"; object autoIdGenStrategyValue = SqlServerValueGenerationStrategy.IdentityColumn; // Setup for MySQL Provider if (migrationBuilder.ActiveProvider == "Pomelo.EntityFrameworkCore.MySql") { DbConfig.IsMySQL = true; autoIdGenStrategy = "MySql:ValueGenerationStrategy"; autoIdGenStrategyValue = MySqlValueGenerationStrategy.IdentityColumn; } migrationBuilder.CreateTable( name: "DeviceUsers", columns: table => new { Id = table.Column<int>() .Annotation(autoIdGenStrategy, autoIdGenStrategyValue), CreatedAt = table.Column<DateTime>(), UpdatedAt = table.Column<DateTime>(nullable: true), WorkflowState = table.Column<string>(maxLength: 255, nullable: true), CreatedByUserId = table.Column<int>(), UpdatedByUserId = table.Column<int>(), Version = table.Column<int>(), DeviceUserId = table.Column<int>(), NotificationRuleId = table.Column<int>() }, constraints: table => { table.PrimaryKey("PK_DeviceUsers", x => x.Id); table.ForeignKey( name: "FK_DeviceUsers_Rules_NotificationRuleId", column: x => x.NotificationRuleId, principalTable: "Rules", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_DeviceUsers_NotificationRuleId", table: "DeviceUsers", column: "NotificationRuleId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "DeviceUsers"); } } }
40.901639
92
0.554309
[ "MIT" ]
Gid733/eform-monitoring-base
Microting.EformMonitoringBase/Migrations/20200109133004_AddDeviceUsers.cs
2,497
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using FluentAssertions; using Xunit; namespace Microsoft.Extensions.DependencyModel.Tests { public class DependencyContextJsonReaderTest { // Same as the default for StreamWriter private static readonly Encoding s_utf8NoPreamble = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private DependencyContext Read(string text, bool withPreamble = false) { using (var stream = new MemoryStream(Encoding.UTF8.GetMaxByteCount(text.Length))) using (var writer = new StreamWriter(stream, withPreamble ? Encoding.UTF8 : s_utf8NoPreamble)) { writer.Write(text); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); return new DependencyContextJsonReader().Read(stream); } } [Theory] [InlineData(false)] [InlineData(true)] public void ReadsRuntimeTargetInfo(bool withPreamble) { var context = Read( @"{ ""runtimeTarget"": { ""name"":"".NETCoreApp,Version=v1.0/osx.10.10-x64"", ""signature"":""target-signature"" }, ""targets"": { "".NETCoreApp,Version=v1.0/osx.10.10-x64"": {} } }", withPreamble); context.Target.IsPortable.Should().BeFalse(); context.Target.Framework.Should().Be(".NETCoreApp,Version=v1.0"); context.Target.Runtime.Should().Be("osx.10.10-x64"); context.Target.RuntimeSignature.Should().Be("target-signature"); } [Fact] public void ReadsRuntimeTargetInfoWithCommentsIsInvalid() { var exception = Assert.Throws<JsonReaderException>(() => Read( @"{ ""runtimeTarget"": { ""name"":"".NETCoreApp,Version=v1.0/osx.10.10-x64"", ""signature"":""target-signature"" }, ""targets"": { // Ignore comments "".NETCoreApp,Version=v1.0/osx.10.10-x64"": {} /* * Ignore multi-line comments */ } }")); Assert.Equal("'/' is invalid after a value. Expected either ',', '}', or ']'. LineNumber: 6 | BytePositionInLine: 8.", exception.Message); } [Fact] public void IgnoredUnknownPropertiesInRuntimeTarget() { var context = Read( @"{ ""runtimeTarget"": { ""shouldIgnoreString"": ""this-will-never-exist"", ""shouldIgnoreObject"": {""inner"": [1, 2]}, ""name"":"".NETCoreApp,Version=v1.0/osx.10.10-x64"", ""signature"":""target-signature"" }, ""targets"": { "".NETCoreApp,Version=v1.0/osx.10.10-x64"": {} } }"); context.Target.IsPortable.Should().BeFalse(); context.Target.Framework.Should().Be(".NETCoreApp,Version=v1.0"); context.Target.Runtime.Should().Be("osx.10.10-x64"); context.Target.RuntimeSignature.Should().Be("target-signature"); } [Fact] public void GroupsRuntimeAssets() { string json = @" { ""targets"": { "".NETStandard,Version=v1.5"": { ""System.Banana/1.0.0"": { ""runtimeTargets"": { ""runtimes/unix/Banana.dll"": { ""rid"": ""unix"", ""assetType"": ""runtime"" }, ""runtimes/win7/Banana.dll"": { ""rid"": ""win7"", ""assetType"": ""runtime"" }, ""runtimes/native/win7/Apple.dll"": { ""rid"": ""win7"", ""assetType"": ""native"" }, ""runtimes/native/unix/libapple.so"": { ""rid"": ""unix"", ""assetType"": ""native"" } } } } }, ""libraries"": { ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"" } } }"; ReadGroupsRuntimeAssets(json); } [Fact] public void GroupsRuntimeAssetsWithAssemblyVersions() { string json = @" { ""targets"": { "".NETStandard,Version=v1.5"": { ""System.Banana/1.0.0"": { ""runtimeTargets"": { ""runtimes/unix/Banana.dll"": { ""rid"": ""unix"", ""assetType"": ""runtime"", ""assemblyVersion"": ""1.2.3"", ""fileVersion"": ""4.5.6"" }, ""runtimes/win7/Banana.dll"": { ""rid"": ""win7"", ""assetType"": ""runtime"", ""fileVersion"": ""1.2.3""}, ""runtimes/native/win7/Apple.dll"": { ""rid"": ""win7"", ""assetType"": ""native"" }, ""runtimes/native/unix/libapple.so"": { ""rid"": ""unix"", ""assetType"": ""native"" } } } } }, ""libraries"": { ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"" } } }"; RuntimeLibrary runtimeLib = ReadGroupsRuntimeAssets(json); runtimeLib.RuntimeAssemblyGroups.GetRuntimeFileAssets("unix").Single().AssemblyVersion.Should().Be("1.2.3"); runtimeLib.RuntimeAssemblyGroups.GetRuntimeFileAssets("unix").Single().FileVersion.Should().Be("4.5.6"); runtimeLib.RuntimeAssemblyGroups.GetRuntimeFileAssets("win7").Single().AssemblyVersion.Should().BeNull(); runtimeLib.RuntimeAssemblyGroups.GetRuntimeFileAssets("win7").Single().FileVersion.Should().Be("1.2.3"); } private RuntimeLibrary ReadGroupsRuntimeAssets(string json) { var context = Read(json); context.RuntimeLibraries.Should().HaveCount(1); RuntimeLibrary runtimeLib = context.RuntimeLibraries.Single(); runtimeLib.RuntimeAssemblyGroups.Should().HaveCount(2); runtimeLib.RuntimeAssemblyGroups.All(g => g.AssetPaths.Count == 1).Should().BeTrue(); runtimeLib.NativeLibraryGroups.Should().HaveCount(2); runtimeLib.NativeLibraryGroups.All(g => g.AssetPaths.Count == 1).Should().BeTrue(); return runtimeLib; } [Fact] public void SetsPortableIfRuntimeTargetHasNoRid() { var context = Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0"": {} } }"); context.Target.IsPortable.Should().BeTrue(); } [Fact] public void SetsNotPortableIfRuntimeTargetHasRid() { var context = Read( @"{ ""runtimeTarget"": { ""name"": "".NETCoreApp,Version=v1.0/osx.10.10-x64"" }, ""targets"": { "".NETCoreApp,Version=v1.0/osx.10.10-x64"": {} } }"); context.Target.IsPortable.Should().BeFalse(); } [Fact] public void ReadsMainTarget() { var context = Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0"": {} } }"); context.Target.Framework.Should().Be(".NETCoreApp,Version=v1.0"); } [Fact] public void IgnoresExtraTopLevelNodes() { var context = Read( @"{ ""shouldIgnoreObject"": {""inner"": [1, 2]}, ""targets"": { "".NETCoreApp,Version=v1.0"": {} }, ""shouldIgnoreString"": ""this-will-never-exist"" }"); context.Target.Framework.Should().Be(".NETCoreApp,Version=v1.0"); } [Fact] public void ReadsRuntimeGraph() { var context = Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0/osx.10.10-x64"": {} }, ""runtimes"": { ""osx.10.10-x64"": [ ], ""osx.10.11-x64"": [ ""osx"" ], ""rhel.7-x64"": [ ""linux-x64"", ""unix"" ] } }"); context.RuntimeGraph.Should().Contain(p => p.Runtime == "osx.10.10-x64").Which .Fallbacks.Should().BeEquivalentTo(); context.RuntimeGraph.Should().Contain(p => p.Runtime == "osx.10.11-x64").Which .Fallbacks.Should().BeEquivalentTo("osx"); context.RuntimeGraph.Should().Contain(p => p.Runtime == "rhel.7-x64").Which .Fallbacks.Should().BeEquivalentTo("linux-x64", "unix"); } [Fact] public void ReadsCompilationTarget() { var context = Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0"": { ""MyApp/1.0.1"": { ""dependencies"": { ""AspNet.Mvc"": ""1.0.0"" }, ""compile"": { ""MyApp.dll"": { } } }, ""System.Banana/1.0.0"": { ""dependencies"": { ""System.Foo"": ""1.0.0"" }, ""compile"": { ""ref/dotnet5.4/System.Banana.dll"": { } } } } }, ""libraries"":{ ""MyApp/1.0.1"": { ""type"": ""project"" }, ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"", ""path"": ""PackagePath"", ""hashPath"": ""PachageHashPath"" } } }"); context.CompileLibraries.Should().HaveCount(2); var project = context.CompileLibraries.Should().Contain(l => l.Name == "MyApp").Subject; project.Version.Should().Be("1.0.1"); project.Assemblies.Should().BeEquivalentTo("MyApp.dll"); project.Type.Should().Be("project"); var package = context.CompileLibraries.Should().Contain(l => l.Name == "System.Banana").Subject; package.Version.Should().Be("1.0.0"); package.Assemblies.Should().BeEquivalentTo("ref/dotnet5.4/System.Banana.dll"); package.Hash.Should().Be("HASH-System.Banana"); package.Type.Should().Be("package"); package.Serviceable.Should().Be(false); package.Path.Should().Be("PackagePath"); package.HashPath.Should().Be("PachageHashPath"); } [Fact] public void RejectsMissingLibrary() { var exception = Assert.Throws<InvalidOperationException>(() => Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0"": { ""System.Banana/1.0.0"": {} } }, ""libraries"": {} }")); Assert.Equal($"Cannot find library information for System.Banana/1.0.0", exception.Message); } [Fact] public void IgnoresUnknownPropertiesInLibrary() { var context = Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0"": { ""System.Banana/1.0.0"": { ""shouldIgnoreString"": ""this-will-never-exist"", ""shouldIgnoreObject"": {""inner"": [1, 2]}, ""compile"": { ""ref/dotnet5.4/System.Banana.dll"": { } } } } }, ""libraries"": { ""System.Banana/1.0.0"": { ""shouldIgnoreString"": ""this-will-never-exist"", ""shouldIgnoreObject"": {""inner"": [1, 2]}, ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"" } } }"); context.CompileLibraries.Should().HaveCount(1); var package = context.CompileLibraries.Should().Contain(l => l.Name == "System.Banana").Subject; package.Version.Should().Be("1.0.0"); package.Assemblies.Should().BeEquivalentTo("ref/dotnet5.4/System.Banana.dll"); package.Hash.Should().Be("HASH-System.Banana"); package.Type.Should().Be("package"); package.Serviceable.Should().Be(false); package.Path.Should().BeNull(); package.HashPath.Should().BeNull(); } [Fact] public void ReadsCompilationTargetWithNullPathAndHashPath() { var context = Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0"": { ""System.Banana/1.0.0"": { ""dependencies"": { ""System.Foo"": ""1.0.0"" }, ""compile"": { ""ref/dotnet5.4/System.Banana.dll"": { } } } } }, ""libraries"":{ ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"", ""path"": null, ""hashPath"": null } } }"); context.CompileLibraries.Should().HaveCount(1); var package = context.CompileLibraries.Should().Contain(l => l.Name == "System.Banana").Subject; package.Version.Should().Be("1.0.0"); package.Assemblies.Should().BeEquivalentTo("ref/dotnet5.4/System.Banana.dll"); package.Hash.Should().Be("HASH-System.Banana"); package.Type.Should().Be("package"); package.Serviceable.Should().Be(false); package.Path.Should().BeNull(); package.HashPath.Should().BeNull(); } [Fact] public void ReadsCompilationTargetWithMissingPathAndHashPath() { var context = Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0"": { ""System.Banana/1.0.0"": { ""dependencies"": { ""System.Foo"": ""1.0.0"" }, ""compile"": { ""ref/dotnet5.4/System.Banana.dll"": { } } } } }, ""libraries"":{ ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"" } } }"); context.CompileLibraries.Should().HaveCount(1); var package = context.CompileLibraries.Should().Contain(l => l.Name == "System.Banana").Subject; package.Version.Should().Be("1.0.0"); package.Assemblies.Should().BeEquivalentTo("ref/dotnet5.4/System.Banana.dll"); package.Hash.Should().Be("HASH-System.Banana"); package.Type.Should().Be("package"); package.Serviceable.Should().Be(false); package.Path.Should().BeNull(); package.HashPath.Should().BeNull(); } [Fact] public void DoesNotReadRuntimeLibraryFromCompilationOnlyEntries() { var context = Read( @"{ ""targets"": { "".NETCoreApp,Version=v1.0"": { ""MyApp/1.0.1"": { ""dependencies"": { ""AspNet.Mvc"": ""1.0.0"" }, ""compile"": { ""MyApp.dll"": { } } }, ""System.Banana/1.0.0"": { ""dependencies"": { ""System.Foo"": ""1.0.0"" }, ""compileOnly"": true, ""compile"": { ""ref/dotnet5.4/System.Banana.dll"": { } } } } }, ""libraries"":{ ""MyApp/1.0.1"": { ""type"": ""project"" }, ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"" } } }"); context.CompileLibraries.Should().HaveCount(2); context.RuntimeLibraries.Should().HaveCount(1); context.RuntimeLibraries[0].Name.Should().Be("MyApp"); } [Fact] public void ReadsRuntimeLibrariesWithSubtargetsFromMainTargetForPortable() { ReadsRuntimeLibrariesWithSubtargetsFromMainTargetForPortable(false); } [Fact] public void ReadsRuntimeLibrariesWithSubtargetsFromMainTargetForPortableWithAssemblyVersions() { ReadsRuntimeLibrariesWithSubtargetsFromMainTargetForPortable(true); } private void ReadsRuntimeLibrariesWithSubtargetsFromMainTargetForPortable(bool useAssemblyVersions) { string json = @"{ ""runtimeTarget"": { ""name"": "".NETCoreApp,Version=v1.0"" }, ""targets"": { "".NETCoreApp,Version=v1.0"": { ""MyApp/1.0.1"": { ""dependencies"": { ""AspNet.Mvc"": ""1.0.0"" }, ""runtime"": { ""MyApp.dll"": { } } }, ""System.Banana/1.0.0"": { ""dependencies"": { ""System.Foo"": ""1.0.0"" }, ""runtime"": { ""lib/dotnet5.4/System.Banana.dll"": {"; if (useAssemblyVersions) { json += @" ""assemblyVersion"": ""1.2.3"", ""fileVersion"": ""7.8.9"" }"; } else { json += " }"; } json += @" }, ""runtimeTargets"": { ""lib/win7/System.Banana.dll"": { ""assetType"": ""runtime"", ""rid"": ""win7-x64""}, ""lib/win7/Banana.dll"": { ""assetType"": ""native"", ""rid"": ""win7-x64""} }, ""resources"": { ""System.Banana.resources.dll"": { ""locale"": ""en-US"" } } } } }, ""libraries"":{ ""MyApp/1.0.1"": { ""type"": ""project"" }, ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"", ""path"": ""PackagePath"", ""hashPath"": ""PackageHashPath"", ""runtimeStoreManifestName"": ""placeHolderManifest.xml"" } } }"; var context = Read(json); context.CompileLibraries.Should().HaveCount(2); var project = context.RuntimeLibraries.Should().Contain(l => l.Name == "MyApp").Subject; project.Version.Should().Be("1.0.1"); project.RuntimeAssemblyGroups.GetDefaultAssets().Should().Contain("MyApp.dll"); project.Type.Should().Be("project"); var package = context.RuntimeLibraries.Should().Contain(l => l.Name == "System.Banana").Subject; package.Version.Should().Be("1.0.0"); package.Hash.Should().Be("HASH-System.Banana"); package.Type.Should().Be("package"); package.Serviceable.Should().Be(false); package.Path.Should().Be("PackagePath"); package.HashPath.Should().Be("PackageHashPath"); package.RuntimeStoreManifestName.Should().Be("placeHolderManifest.xml"); package.ResourceAssemblies.Should().Contain(a => a.Path == "System.Banana.resources.dll") .Subject.Locale.Should().Be("en-US"); if (useAssemblyVersions) { var assets = package.RuntimeAssemblyGroups.GetDefaultRuntimeFileAssets(); assets.Should().HaveCount(1); var runtimeFile = assets.First(); runtimeFile.Path.Should().Be("lib/dotnet5.4/System.Banana.dll"); runtimeFile.AssemblyVersion.Should().Be("1.2.3"); runtimeFile.FileVersion.Should().Be("7.8.9"); } else { package.RuntimeAssemblyGroups.GetDefaultAssets().Should().Contain("lib/dotnet5.4/System.Banana.dll"); } package.RuntimeAssemblyGroups.GetRuntimeAssets("win7-x64").Should().Contain("lib/win7/System.Banana.dll"); package.NativeLibraryGroups.GetRuntimeAssets("win7-x64").Should().Contain("lib/win7/Banana.dll"); } [Fact] public void ReadsRuntimeTargetPlaceholdersAsEmptyGroups() { var context = Read( @"{ ""runtimeTarget"": { ""name"": "".NETCoreApp,Version=v1.0"" }, ""targets"": { "".NETCoreApp,Version=v1.0"": { ""System.Banana/1.0.0"": { ""runtimeTargets"": { ""runtime/win7-x64/lib/_._"": { ""assetType"": ""runtime"", ""rid"": ""win7-x64""}, ""runtime/linux-x64/native/_._"": { ""assetType"": ""native"", ""rid"": ""linux-x64""} } } } }, ""libraries"":{ ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"" } } }"); context.CompileLibraries.Should().HaveCount(1); var package = context.RuntimeLibraries.Should().Contain(l => l.Name == "System.Banana").Subject; package.RuntimeAssemblyGroups.Should().Contain(g => g.Runtime == "win7-x64") .Which.AssetPaths.Should().BeEmpty(); package.NativeLibraryGroups.Should().Contain(g => g.Runtime == "linux-x64") .Which.AssetPaths.Should().BeEmpty(); } [Fact] public void IgnoresUnknownPropertiesInRuntimeTargets() { var context = Read( @"{ ""runtimeTarget"": { ""name"": "".NETCoreApp,Version=v1.0"" }, ""targets"": { "".NETCoreApp,Version=v1.0"": { ""System.Banana/1.0.0"": { ""runtimeTargets"": { ""runtime/win7-x64/lib/_._"": { ""shouldIgnoreString"": ""this-will-never-exist"", ""shouldIgnoreObject"": {""inner"": [1, 2]}, ""assetType"": ""runtime"", ""rid"": ""win7-x64"" }, ""runtime/linux-x64/native/_._"": { ""assetType"": ""native"", ""rid"": ""linux-x64""} } } } }, ""libraries"":{ ""System.Banana/1.0.0"": { ""type"": ""package"", ""serviceable"": false, ""sha512"": ""HASH-System.Banana"" } } }"); var package = context.RuntimeLibraries.Should().Contain(l => l.Name == "System.Banana").Subject; package.RuntimeAssemblyGroups.Should().Contain(g => g.Runtime == "win7-x64") .Which.AssetPaths.Should().BeEmpty(); package.NativeLibraryGroups.Should().Contain(g => g.Runtime == "linux-x64") .Which.AssetPaths.Should().BeEmpty(); } [Fact] public void ReadsCompilationOptions() { var context = Read( @"{ ""compilationOptions"": { ""allowUnsafe"": true, ""defines"": [""MY"", ""DEFINES""], ""delaySign"": true, ""emitEntryPoint"": true, ""xmlDoc"": true, ""keyFile"": ""Key.snk"", ""languageVersion"": ""C#8"", ""platform"": ""Platform"", ""publicSign"": true, ""warningsAsErrors"": true, ""optimize"": true }, ""targets"": { "".NETCoreApp,Version=v1.0/osx.10.10-x64"": {} } }"); context.CompilationOptions.AllowUnsafe.Should().Be(true); context.CompilationOptions.Defines.Should().BeEquivalentTo(new[] { "MY", "DEFINES" }); context.CompilationOptions.DelaySign.Should().Be(true); context.CompilationOptions.EmitEntryPoint.Should().Be(true); context.CompilationOptions.GenerateXmlDocumentation.Should().Be(true); context.CompilationOptions.KeyFile.Should().Be("Key.snk"); context.CompilationOptions.LanguageVersion.Should().Be("C#8"); context.CompilationOptions.Optimize.Should().Be(true); context.CompilationOptions.Platform.Should().Be("Platform"); context.CompilationOptions.PublicSign.Should().Be(true); context.CompilationOptions.WarningsAsErrors.Should().Be(true); } [Fact] public void IgnoresUnknownPropertiesInCompilationOptions() { var context = Read( @"{ ""compilationOptions"": { ""shouldIgnoreString"": ""this-will-never-exist"", ""shouldIgnoreObject"": {""inner"": [1, 2]}, ""allowUnsafe"": true, ""defines"": [""MY"", ""DEFINES""], ""delaySign"": true, ""emitEntryPoint"": true, ""xmlDoc"": true, ""keyFile"": ""Key.snk"", ""languageVersion"": ""C#8"", ""platform"": ""Platform"", ""publicSign"": true, ""warningsAsErrors"": true, ""optimize"": true }, ""targets"": { "".NETCoreApp,Version=v1.0/osx.10.10-x64"": {} } }"); context.CompilationOptions.AllowUnsafe.Should().Be(true); context.CompilationOptions.Defines.Should().BeEquivalentTo(new[] { "MY", "DEFINES" }); context.CompilationOptions.DelaySign.Should().Be(true); context.CompilationOptions.EmitEntryPoint.Should().Be(true); context.CompilationOptions.GenerateXmlDocumentation.Should().Be(true); context.CompilationOptions.KeyFile.Should().Be("Key.snk"); context.CompilationOptions.LanguageVersion.Should().Be("C#8"); context.CompilationOptions.Optimize.Should().Be(true); context.CompilationOptions.Platform.Should().Be("Platform"); context.CompilationOptions.PublicSign.Should().Be(true); context.CompilationOptions.WarningsAsErrors.Should().Be(true); } } }
34.901084
161
0.501456
[ "MIT" ]
batzen/core-setup
src/test/Microsoft.Extensions.DependencyModel.Tests/DependencyContextJsonReaderTest.cs
25,759
C#
/* * Xillio Engine * * No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 0.1 * Contact: dev@sphereon.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Sphereon.SDK.Xillio.Engine.Client; using Sphereon.SDK.Xillio.Engine.Model; namespace Sphereon.SDK.Xillio.Engine.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IContentApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Download an Entity\&quot;s Binary Content /// </summary> /// <remarks> /// Download an Entity\&quot;s Binary Content /// </remarks> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>System.IO.Stream</returns> System.IO.Stream GetContent (string configurationId, string path); /// <summary> /// Download an Entity\&quot;s Binary Content /// </summary> /// <remarks> /// Download an Entity\&quot;s Binary Content /// </remarks> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>ApiResponse of System.IO.Stream</returns> ApiResponse<System.IO.Stream> GetContentWithHttpInfo (string configurationId, string path); /// <summary> /// Replaces an Entity\&quot;s Binary Content /// </summary> /// <remarks> /// Replaces an Entity\&quot;s Binary Content /// </remarks> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns></returns> void UpdateContent (string configurationId, string path); /// <summary> /// Replaces an Entity\&quot;s Binary Content /// </summary> /// <remarks> /// Replaces an Entity\&quot;s Binary Content /// </remarks> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> UpdateContentWithHttpInfo (string configurationId, string path); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Download an Entity\&quot;s Binary Content /// </summary> /// <remarks> /// Download an Entity\&quot;s Binary Content /// </remarks> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>Task of System.IO.Stream</returns> System.Threading.Tasks.Task<System.IO.Stream> GetContentAsync (string configurationId, string path); /// <summary> /// Download an Entity\&quot;s Binary Content /// </summary> /// <remarks> /// Download an Entity\&quot;s Binary Content /// </remarks> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>Task of ApiResponse (System.IO.Stream)</returns> System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> GetContentAsyncWithHttpInfo (string configurationId, string path); /// <summary> /// Replaces an Entity\&quot;s Binary Content /// </summary> /// <remarks> /// Replaces an Entity\&quot;s Binary Content /// </remarks> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task UpdateContentAsync (string configurationId, string path); /// <summary> /// Replaces an Entity\&quot;s Binary Content /// </summary> /// <remarks> /// Replaces an Entity\&quot;s Binary Content /// </remarks> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> UpdateContentAsyncWithHttpInfo (string configurationId, string path); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ContentApi : IContentApi { private Sphereon.SDK.Xillio.Engine.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ContentApi"/> class. /// </summary> /// <returns></returns> public ContentApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Sphereon.SDK.Xillio.Engine.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="ContentApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ContentApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Sphereon.SDK.Xillio.Engine.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Sphereon.SDK.Xillio.Engine.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Download an Entity\&quot;s Binary Content Download an Entity\&quot;s Binary Content /// </summary> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>System.IO.Stream</returns> public System.IO.Stream GetContent (string configurationId, string path) { ApiResponse<System.IO.Stream> localVarResponse = GetContentWithHttpInfo(configurationId, path); return localVarResponse.Data; } /// <summary> /// Download an Entity\&quot;s Binary Content Download an Entity\&quot;s Binary Content /// </summary> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>ApiResponse of System.IO.Stream</returns> public ApiResponse< System.IO.Stream > GetContentWithHttpInfo (string configurationId, string path) { // verify the required parameter 'configurationId' is set if (configurationId == null) throw new ApiException(400, "Missing required parameter 'configurationId' when calling ContentApi->GetContent"); // verify the required parameter 'path' is set if (path == null) throw new ApiException(400, "Missing required parameter 'path' when calling ContentApi->GetContent"); var localVarPath = "/contents/{configurationId}/{path}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/octet-stream" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (configurationId != null) localVarPathParams.Add("configurationId", Configuration.ApiClient.ParameterToString(configurationId)); // path parameter if (path != null) localVarPathParams.Add("path", Configuration.ApiClient.ParameterToString(path)); // path parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetContent", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<System.IO.Stream>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream))); } /// <summary> /// Download an Entity\&quot;s Binary Content Download an Entity\&quot;s Binary Content /// </summary> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>Task of System.IO.Stream</returns> public async System.Threading.Tasks.Task<System.IO.Stream> GetContentAsync (string configurationId, string path) { ApiResponse<System.IO.Stream> localVarResponse = await GetContentAsyncWithHttpInfo(configurationId, path); return localVarResponse.Data; } /// <summary> /// Download an Entity\&quot;s Binary Content Download an Entity\&quot;s Binary Content /// </summary> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>Task of ApiResponse (System.IO.Stream)</returns> public async System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> GetContentAsyncWithHttpInfo (string configurationId, string path) { // verify the required parameter 'configurationId' is set if (configurationId == null) throw new ApiException(400, "Missing required parameter 'configurationId' when calling ContentApi->GetContent"); // verify the required parameter 'path' is set if (path == null) throw new ApiException(400, "Missing required parameter 'path' when calling ContentApi->GetContent"); var localVarPath = "/contents/{configurationId}/{path}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/octet-stream" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (configurationId != null) localVarPathParams.Add("configurationId", Configuration.ApiClient.ParameterToString(configurationId)); // path parameter if (path != null) localVarPathParams.Add("path", Configuration.ApiClient.ParameterToString(path)); // path parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetContent", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<System.IO.Stream>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream))); } /// <summary> /// Replaces an Entity\&quot;s Binary Content Replaces an Entity\&quot;s Binary Content /// </summary> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns></returns> public void UpdateContent (string configurationId, string path) { UpdateContentWithHttpInfo(configurationId, path); } /// <summary> /// Replaces an Entity\&quot;s Binary Content Replaces an Entity\&quot;s Binary Content /// </summary> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> UpdateContentWithHttpInfo (string configurationId, string path) { // verify the required parameter 'configurationId' is set if (configurationId == null) throw new ApiException(400, "Missing required parameter 'configurationId' when calling ContentApi->UpdateContent"); // verify the required parameter 'path' is set if (path == null) throw new ApiException(400, "Missing required parameter 'path' when calling ContentApi->UpdateContent"); var localVarPath = "/contents/{configurationId}/{path}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/octet-stream" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (configurationId != null) localVarPathParams.Add("configurationId", Configuration.ApiClient.ParameterToString(configurationId)); // path parameter if (path != null) localVarPathParams.Add("path", Configuration.ApiClient.ParameterToString(path)); // path parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateContent", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Replaces an Entity\&quot;s Binary Content Replaces an Entity\&quot;s Binary Content /// </summary> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task UpdateContentAsync (string configurationId, string path) { await UpdateContentAsyncWithHttpInfo(configurationId, path); } /// <summary> /// Replaces an Entity\&quot;s Binary Content Replaces an Entity\&quot;s Binary Content /// </summary> /// <exception cref="Sphereon.SDK.Xillio.Engine.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="configurationId">The id of a configured repository.</param> /// <param name="path">The XDIP path to the entity.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateContentAsyncWithHttpInfo (string configurationId, string path) { // verify the required parameter 'configurationId' is set if (configurationId == null) throw new ApiException(400, "Missing required parameter 'configurationId' when calling ContentApi->UpdateContent"); // verify the required parameter 'path' is set if (path == null) throw new ApiException(400, "Missing required parameter 'path' when calling ContentApi->UpdateContent"); var localVarPath = "/contents/{configurationId}/{path}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/octet-stream" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (configurationId != null) localVarPathParams.Add("configurationId", Configuration.ApiClient.ParameterToString(configurationId)); // path parameter if (path != null) localVarPathParams.Add("path", Configuration.ApiClient.ParameterToString(path)); // path parameter // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateContent", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } } }
50.188748
161
0.639835
[ "Apache-2.0" ]
Sphereon-Opensource/xillio-engine-integration
xillio-engine-sdk/csharp-net4/src/Sphereon.SDK.Xillio.Engine/Api/ContentApi.cs
27,654
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using C1.C1Report; using C1.Win.C1TrueDBGrid; using PCSComProcurement.Purchase.BO; using PCSComUtils.Common; using PCSComUtils.Common.BO; using PCSComUtils.DataContext; using PCSComUtils.Framework.ReportFrame.BO; using PCSComUtils.PCSExc; using PCSUtils.Framework.ReportFrame; using PCSUtils.Log; using PCSUtils.Utils; using CancelEventArgs = System.ComponentModel.CancelEventArgs; using v_PurchaseOrderOfItem = PCSComUtils.Common.v_PurchaseOrderOfItem; using v_ReceiptBySchedule = PCSComUtils.Common.v_ReceiptBySchedule; namespace PCSProcurement.Purchase { public partial class PurchaseOrderReceipts : Form { #region constants private const string This = "PCSProcurement.Purchase.PurchaseOrderReceipts"; private const string ReceiptlineCol = "ReceiptLine"; private const string Seperator = "-"; private const string SlipEndFormat = "yyyyMMddhh"; private const string YearFilter = "[Year]"; private const string MonthFilter = "[Month]"; private const string DayFilter = "[Day]"; private const string HourFilter = "[Hour]"; #endregion #region fields private EnumAction _formMode = EnumAction.Default; private RadioStatus _enmOldRadioStatus = RadioStatus.BySlip; private RadioStatus _enmStatus = RadioStatus.BySlip; private DataTable _gridLayOut = new DataTable(); private DataSet _dataSource; private DataSet _dataCopy; private DateTime _currentDate; private DateTime _slipDate; private int _ccnId; private int _masterLocationId; private int _partyId; private string _pONumber = string.Empty; private PO_PurchaseOrderReceiptMaster _receiptMaster; private PO_InvoiceMaster _invoiceMaster = new PO_InvoiceMaster(); private MST_MasterLocation _masterLocation = new MST_MasterLocation(); private PO_PurchaseOrderDetail _poDetail = new PO_PurchaseOrderDetail(); private PO_PurchaseOrderMaster _poMaster = new PO_PurchaseOrderMaster(); #endregion public PurchaseOrderReceipts() { InitializeComponent(); } private void PurchaseOrderReceipts_Load(object sender, EventArgs e) { const string methodName = This + ".PurchaseOrderReceipts_Load()"; try { //Set authorization for user var objSecurity = new Security(); Name = This; if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0) { Close(); PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning); return; } // fill data to CCN combo FormControlComponents.PutDataIntoC1ComboBox(CCNCombo, Utilities.Instance.ListCCN(), MST_CCNTable.CODE_FLD, MST_CCNTable.CCNID_FLD, MST_CCNTable.TABLE_NAME); // set selected value to default CCN CCNCombo.SelectedValue = SystemProperty.CCNID; // set value to PostDate = null PostDatePicker.Value = null; radBySlip.Checked = true; _currentDate = Utilities.Instance.GetServerDate().AddDays(1); // switch form mode SwitchFormMode(); _gridLayOut = FormControlComponents.StoreGridLayout(dgrdData); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void ReceiveNoText_Validating(object sender, CancelEventArgs e) { const string methodName = This + ".ReceiveNoText_Validating()"; try { if (!SearchReceiveButton.Enabled) return; if (ReceiveNoText.Modified) { if (ReceiveNoText.Text.Trim().Length == 0) { ResetForm(); return; } // display open search form var htCon = new Hashtable { { PO_PurchaseOrderReceiptMasterTable.CCNID_FLD, SystemProperty.CCNID } }; var drvResult = FormControlComponents.OpenSearchForm(PO_PurchaseOrderReceiptMasterTable.TABLE_NAME, PO_PurchaseOrderReceiptMasterTable.RECEIVENO_FLD, ReceiveNoText.Text.Trim(), htCon, false); if (drvResult != null) FillMasterData((int)drvResult[PO_PurchaseOrderReceiptMasterTable.PURCHASEORDERRECEIPTID_FLD]); else e.Cancel = true; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void ReceiveNoText_KeyDown(object sender, KeyEventArgs e) { if (SearchReceiveButton.Enabled && e.KeyCode == Keys.F4) SearchReceiveButton_Click(null, null); } private void SearchReceiveButton_Click(object sender, EventArgs e) { const string methodName = This + ".SearchReceiveButton_Click()"; try { // display open search form var htCon = new Hashtable { { PO_PurchaseOrderReceiptMasterTable.CCNID_FLD, SystemProperty.CCNID } }; var drvResult = FormControlComponents.OpenSearchForm(PO_PurchaseOrderReceiptMasterTable.TABLE_NAME, PO_PurchaseOrderReceiptMasterTable.RECEIVENO_FLD, ReceiveNoText.Text.Trim(), htCon, true); if (drvResult != null) FillMasterData((int)drvResult[PO_PurchaseOrderReceiptMasterTable.PURCHASEORDERRECEIPTID_FLD]); else ReceiveNoText.Focus(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void txtMasLoc_Validating(object sender, CancelEventArgs e) { const string methodName = This + ".txtMasLoc_Validating()"; try { if (!btnSearchMasLoc.Enabled) return; if (txtMasLoc.Modified) { if (txtMasLoc.Text.Trim().Length == 0) { FillMasterLocationData(0); return; } // display open search form var htCon = new Hashtable { { MST_MasterLocationTable.CCNID_FLD, SystemProperty.CCNID } }; var drvResult = FormControlComponents.OpenSearchForm(MST_MasterLocationTable.TABLE_NAME, MST_MasterLocationTable.CODE_FLD, txtMasLoc.Text.Trim(), htCon, false); if (drvResult != null) FillMasterData((int)drvResult[MST_MasterLocationTable.MASTERLOCATIONID_FLD]); else e.Cancel = true; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void txtMasLoc_KeyDown(object sender, KeyEventArgs e) { if (btnSearchMasLoc.Enabled && e.KeyCode == Keys.F4) btnSearchMasLoc_Click(null, null); } private void btnSearchMasLoc_Click(object sender, EventArgs e) { const string methodName = This + ".btnSearchMasLoc_Click()"; try { // display open search form var htCon = new Hashtable { { MST_MasterLocationTable.CCNID_FLD, SystemProperty.CCNID } }; var drvResult = FormControlComponents.OpenSearchForm(MST_MasterLocationTable.TABLE_NAME, MST_MasterLocationTable.CODE_FLD, txtMasLoc.Text.Trim(), htCon, true); if (drvResult != null) FillMasterData((int)drvResult[MST_MasterLocationTable.MASTERLOCATIONID_FLD]); else txtMasLoc.Focus(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void radBySlip_CheckedChanged(object sender, EventArgs e) { const string methodName = This + ".radBySlip_CheckedChanged()"; try { if (!radBySlip.Enabled) return; // Avoid recursive if (_enmStatus == RadioStatus.NoChange) return; _enmStatus = RadioStatus.BySlip; if (!ConfirmRadio()) return; EnableButtons(); if (radBySlip.Checked) { txtInvoice.Text = string.Empty; txtProductionLine.Text = txtOutside.Text = string.Empty; txtVendorName.Text = string.Empty; txtVendorNo.Text = string.Empty; _invoiceMaster = new PO_InvoiceMaster(); if (_dataSource != null && _dataSource.Tables.Count > 0) _dataSource.Tables[0].Clear(); // lock grid foreach (C1DisplayColumn dcolC1 in dgrdData.Splits[0].DisplayColumns) dcolC1.Locked = true; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void btnDeliverySlip_Click(object sender, EventArgs e) { const string methodName = This + ".ReceiveNoText_Validating()"; try { string strSlipNumber = txtDeliverySlip.Text.Trim(); if (strSlipNumber == string.Empty) { if (_dataSource != null && _dataSource.Tables.Count > 0) _dataSource.Tables[0].Clear(); // lock the grid dgrdData.Splits[0].Locked = true; return; } // user must select CCN first int intCCNID = 0; try { intCCNID = int.Parse(CCNCombo.SelectedValue.ToString()); if (intCCNID <= 0) throw new Exception(); } catch { PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_CCN, MessageBoxIcon.Error); CCNCombo.Focus(); return; } if (_masterLocationId <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_MASTERLOCATION, MessageBoxButtons.OK, MessageBoxIcon.Error); txtMasLoc.Focus(); return; } try { // now get the po number from slip number _pONumber = strSlipNumber.Remove( strSlipNumber.Length - SlipEndFormat.Length - Seperator.Length, SlipEndFormat.Length + Seperator.Length); // get PO Master object from the code _poMaster = PurchaseOrderReceiptBO.Instance.GetPurchaseOrderMaster(_pONumber); if (_poMaster.PurchaseTypeID != (int)POType.Domestic) { var strMsg = new string[2]; strMsg[0] = radBySlip.Text; strMsg[1] = POType.Domestic.ToString(); PCSMessageBox.Show(ErrorCode.MESSAGE_INVALID_POTYPE, MessageBoxIcon.Error, strMsg); return; } // remove Po number from the string strSlipNumber = strSlipNumber.Substring(_pONumber.Length + 1); // slip number = yyyyMMddHH // get year from first 4 char of slip number int intYear = int.Parse(strSlipNumber.Substring(0, 4)); int intMonth = int.Parse(strSlipNumber.Substring(4, 2)); int intDay = int.Parse(strSlipNumber.Substring(6, 2)); int intHours = int.Parse(strSlipNumber.Substring(8)); _slipDate = new DateTime(intYear, intMonth, intDay, intHours, 0, 0); } catch (Exception ex) { var strMsg = new string[2]; strMsg[0] = txtDeliverySlip.Text.Trim(); strMsg[1] = "xxxxx" + Seperator + SlipEndFormat; PCSMessageBox.Show(ErrorCode.MESSAGE_INVALID_FORMAT, MessageBoxIcon.Error, strMsg); txtDeliverySlip.Focus(); txtDeliverySlip.SelectAll(); return; } _partyId = _poMaster.PartyID; FillCustomerInfo(_partyId); // retrieve detail data from delivery schedule by PO number _dataSource = PurchaseOrderReceiptBO.Instance.ListByPurchaseOrderCode(_pONumber, _slipDate); // fill to data grid if (_dataSource.Tables.Count > 0 && _dataSource.Tables[0].Rows.Count > 0) BindDataToGrid(false); else { if (_dataSource != null && _dataSource.Tables.Count > 0) _dataSource.Tables[0].Clear(); BindDataToGrid(false); // lock the grid dgrdData.Splits[0].Locked = true; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void radByInvoice_CheckedChanged(object sender, EventArgs e) { const string methodName = This + ".radByInvoice_CheckedChanged()"; try { if (!radByInvoice.Enabled) return; // Avoid recursive if (_enmStatus == RadioStatus.NoChange) return; _enmStatus = RadioStatus.ByInvoice; if (!ConfirmRadio()) return; EnableButtons(); if (radByInvoice.Checked) { txtDeliverySlip.Text = string.Empty; txtOutside.Text = txtProductionLine.Text = string.Empty; if (_dataSource != null && _dataSource.Tables.Count > 0) _dataSource.Tables[0].Clear(); // lock grid foreach (C1DisplayColumn dcolC1 in dgrdData.Splits[0].DisplayColumns) dcolC1.Locked = true; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void txtInvoice_Validating(object sender, CancelEventArgs e) { const string methodName = This + ".txtInvoice_Validating()"; try { if (!btnInvoice.Enabled) return; if (txtInvoice.Modified) { if (txtInvoice.Text.Trim().Length == 0) { FillInvoiceData(null); return; } // display open search form var htCon = new Hashtable { { PO_InvoiceMasterTable.CCNID_FLD, SystemProperty.CCNID } }; var drvResult = FormControlComponents.OpenSearchForm(PO_InvoiceMasterTable.TABLE_NAME, PO_InvoiceMasterTable.INVOICENO_FLD, txtInvoice.Text.Trim(), htCon, false); if (drvResult != null) FillInvoiceData(drvResult.Row); else e.Cancel = true; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void txtInvoice_KeyDown(object sender, KeyEventArgs e) { if (btnInvoice.Enabled && e.KeyCode == Keys.F4) btnInvoice_Click(null, null); } private void btnInvoice_Click(object sender, EventArgs e) { const string methodName = This + ".btnInvoice_Click()"; try { // display open search form var htCon = new Hashtable {{PO_InvoiceMasterTable.CCNID_FLD, SystemProperty.CCNID}}; var drvResult = FormControlComponents.OpenSearchForm(PO_InvoiceMasterTable.TABLE_NAME, PO_InvoiceMasterTable.INVOICENO_FLD, txtInvoice.Text.Trim(), htCon, false); if (drvResult != null) FillInvoiceData(drvResult.Row); else txtInvoice.Focus(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void radOutside_CheckedChanged(object sender, EventArgs e) { const string methodName = This + ".radOutside_CheckedChanged()"; try { if (!radOutside.Enabled) return; // Avoid recursive if (_enmStatus == RadioStatus.NoChange) return; _enmStatus = RadioStatus.ByOutside; if (!ConfirmRadio()) return; EnableButtons(); if (radOutside.Checked) { txtInvoice.Text = string.Empty; txtInvoice.Text = string.Empty; txtDeliverySlip.Text = string.Empty; txtVendorName.Text = string.Empty; txtVendorNo.Text = string.Empty; _invoiceMaster = new PO_InvoiceMaster(); if (_dataSource != null && _dataSource.Tables.Count > 0) _dataSource.Tables[0].Clear(); // lock grid foreach (C1DisplayColumn dcolC1 in dgrdData.Splits[0].DisplayColumns) dcolC1.Locked = true; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void btnOutside_Click(object sender, EventArgs e) { const string methodName = This + ".btnOutside_Click()"; try { string strSlipNumber = txtOutside.Text.Trim(); // Empty slip number if (strSlipNumber == string.Empty) { if (_dataSource != null && _dataSource.Tables.Count > 0) _dataSource.Tables[0].Clear(); // lock the grid dgrdData.Splits[0].Locked = true; return; } if (_masterLocationId <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_MASTERLOCATION, MessageBoxButtons.OK, MessageBoxIcon.Error); txtMasLoc.Focus(); return; } try { // now get the po number from slip number _pONumber = strSlipNumber.Remove( strSlipNumber.Length - SlipEndFormat.Length - Seperator.Length, SlipEndFormat.Length + Seperator.Length); // get PO Master object from the code _poMaster = PurchaseOrderReceiptBO.Instance.GetPurchaseOrderMaster(_pONumber); if (_poMaster.PurchaseTypeID != (int)POType.Outside) { var strMsg = new string[2]; strMsg[0] = radOutside.Text; strMsg[1] = POType.Outside.ToString(); PCSMessageBox.Show(ErrorCode.MESSAGE_INVALID_POTYPE, MessageBoxIcon.Error, strMsg); return; } // remove Po number from the string strSlipNumber = strSlipNumber.Substring(_pONumber.Length + 1); // slip number = yyyyMMddHH // get year from first 4 char of slip number int intYear = int.Parse(strSlipNumber.Substring(0, 4)); int intMonth = int.Parse(strSlipNumber.Substring(4, 2)); int intDay = int.Parse(strSlipNumber.Substring(6, 2)); int intHours = int.Parse(strSlipNumber.Substring(8)); _slipDate = new DateTime(intYear, intMonth, intDay, intHours, 0, 0); } catch { var strMsg = new string[2]; strMsg[0] = txtOutside.Text.Trim(); strMsg[1] = "xxxxx" + Seperator + SlipEndFormat; PCSMessageBox.Show(ErrorCode.MESSAGE_INVALID_FORMAT, MessageBoxIcon.Error, strMsg); txtOutside.Focus(); txtOutside.SelectAll(); return; } _partyId = _poMaster.PartyID; FillCustomerInfo(_partyId); // retrieve detail data from delivery schedule by PO number _dataSource = PurchaseOrderReceiptBO.Instance.ListByPurchaseOrderCode(_pONumber, _slipDate); // fill to data grid if (_dataSource.Tables.Count > 0 && _dataSource.Tables[0].Rows.Count > 0) BindDataToGrid(false); else { if (_dataSource != null && _dataSource.Tables.Count > 0) _dataSource.Tables[0].Clear(); BindDataToGrid(false); // lock the grid dgrdData.Splits[0].Locked = true; } //HACK: added by Tuan TQ: Enable BOM shortage button if (radOutside.Checked && _dataSource != null && txtProductionLine.Tag != null && _pONumber != string.Empty && !PostDatePicker.Text.Trim().Equals(string.Empty) && !txtOutside.Text.Trim().Equals(string.Empty) && dgrdData.RowCount > 0) { btnBOMShortage.Enabled = true; } else { btnBOMShortage.Enabled = false; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void txtProductionLine_Validating(object sender, CancelEventArgs e) { const string methodName = This + ".txtProductionLine_Validating()"; try { if (!btnProductionLine.Enabled) return; if (txtProductionLine.Modified) { if (txtProductionLine.Text.Trim().Length == 0) { ResetForm(); return; } var drowData = FormControlComponents.OpenSearchForm(PRO_ProductionLineTable.TABLE_NAME, PRO_ProductionLineTable.CODE_FLD, txtProductionLine.Text.Trim(), null, false); if (drowData != null) FillProductionLine(drowData.Row); else e.Cancel = true; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void txtProductionLine_KeyDown(object sender, KeyEventArgs e) { if (btnProductionLine.Enabled && e.KeyCode == Keys.F4) btnProductionLine_Click(null, null); } private void btnProductionLine_Click(object sender, EventArgs e) { const string methodName = This + ".btnProductionLine_Click()"; try { var drowData = FormControlComponents.OpenSearchForm(PRO_ProductionLineTable.TABLE_NAME, PRO_ProductionLineTable.CODE_FLD, txtProductionLine.Text.Trim(), null, true); if (drowData != null) FillProductionLine(drowData.Row); else txtProductionLine.Focus(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void dgrdData_AfterColUpdate(object sender, ColEventArgs e) { const string methodName = This + ".dgrdData_AfterColUpdate()"; try { switch (e.Column.DataColumn.DataField) { case PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD: if (e.Column.DataColumn.Tag != null && dgrdData[dgrdData.Row, PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD].ToString() != string.Empty) FillPOLineData((DataRow)e.Column.DataColumn.Tag); else FillPOLineData(null); break; case MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD: if (e.Column.DataColumn.Tag != null && dgrdData[dgrdData.Row, MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD].ToString() != string.Empty) FillLocationData((DataRow)e.Column.DataColumn.Tag); else FillLocationData(null); break; case MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD: if (e.Column.DataColumn.Tag != null && dgrdData[dgrdData.Row, MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].ToString() != string.Empty) FillBinData((DataRow)e.Column.DataColumn.Tag); else FillBinData(null); break; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void dgrdData_AfterDelete(object sender, EventArgs e) { const string methodName = This + ".dgrdData_AfterDelete()"; try { if (dgrdData.RowCount == 0) return; // re-assign line value int intCount = 0; for (int i = 0; i < dgrdData.RowCount; i++) { dgrdData[i, ReceiptlineCol] = ++intCount; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void dgrdData_BeforeColEdit(object sender, BeforeColEditEventArgs e) { const string methodName = This + ".dgrdData_BeforeColEdit()"; try { switch (e.Column.DataColumn.DataField) { case MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD: // if current selected Location is not controlled by Bin then lock Bin cell var locationId = (int)dgrdData[dgrdData.Row, MST_LocationTable.LOCATIONID_FLD]; if (locationId > 0) { var voLocation = Utilities.Instance.GetLocation(locationId); if (voLocation.Bin.GetValueOrDefault(false)) e.Column.Locked = false; else { e.Cancel = true; e.Column.Locked = true; } } break; case PO_PurchaseOrderReceiptDetailTable.LOT_FLD: // if current Item is not controlled by Lot then Lock Lot cell var productId = (int)dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD]; if (productId > 0) { var voCurrentProduct = Utilities.Instance.GetProductInfo(productId); if (!voCurrentProduct.LotControl.GetValueOrDefault(false)) { e.Cancel = true; // lock Lot cell e.Column.Locked = true; } else // unlock Lot cell e.Column.Locked = false; } break; } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void dgrdData_BeforeColUpdate(object sender, BeforeColUpdateEventArgs e) { const string methodName = This + ".dgrdData_BeforeColUpdate()"; try { string strColumn = dgrdData.Columns[dgrdData.Col].DataField; string strValue = dgrdData.Columns[dgrdData.Col].Text.Trim(); if (strValue == string.Empty) return; var htbConditions = new Hashtable(); decimal receiveQuantity = 0; ITM_Product currentProduct; decimal totalQuantityOfLot; int poDetailId; DataRowView drvData = null; switch (strColumn) { #region Receive Quantity case PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD: try { poDetailId = (int)dgrdData[dgrdData.Row, PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD]; if (poDetailId <= 0) throw new Exception(); } catch { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SELECT_PRODUCT, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]); dgrdData.Columns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].Text = string.Empty; dgrdData.Focus(); dgrdData.Select(); return; } try { receiveQuantity = decimal.Parse(strValue); if (receiveQuantity <= 0) { PCSMessageBox.Show(ErrorCode.POSITIVE_NUMBER, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]); e.Cancel = true; } } catch { PCSMessageBox.Show(ErrorCode.MESSAGE_INVALID_NUMERIC, MessageBoxButtons.OK,MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]); e.Cancel = true; } break; #endregion #region Purchase order line // select purchase order line case (PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD): if (radBySlip.Checked) { if (_slipDate != DateTime.MaxValue) { htbConditions.Add(YearFilter, _slipDate.Year); htbConditions.Add(MonthFilter, _slipDate.Month); htbConditions.Add(DayFilter, _slipDate.Day); htbConditions.Add(HourFilter, _slipDate.Hour); } } var purchaseOrderMasterId = (int)dgrdData[dgrdData.Row, PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD]; htbConditions.Add(PO_PurchaseOrderDetailTable.PURCHASEORDERMASTERID_FLD, purchaseOrderMasterId); if (strValue != string.Empty) { drvData = radBySlip.Checked ? FormControlComponents.OpenSearchForm(v_ReceiptBySchedule.VIEW_NAME, PO_PurchaseOrderDetailTable.LINE_FLD, strValue, htbConditions, true) : FormControlComponents.OpenSearchForm(v_PurchaseOrderOfItem.VIEW_NAME, PO_PurchaseOrderDetailTable.LINE_FLD, strValue, htbConditions, true); } if (drvData == null) { if (strValue != string.Empty) e.Cancel = true; } else { string strExpression = PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD + Constants.EQUAL + drvData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD]; if (radBySlip.Checked) strExpression += Constants.AND + PO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD + Constants.EQUAL + drvData[PO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD].ToString(); // get current row purchase order detail and delivery schedule var intRowPODetailId = (int)dgrdData[dgrdData.Row, PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD]; var intDeliveryScheduleId = (int)dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.DELIVERYSCHEDULEID_FLD]; // we need to check for exsiting PO Line and delivery line in the list DataRow[] drowExisted = _dataSource.Tables[0].Select(strExpression); if (drowExisted.Length.Equals(0)) { e.Column.DataColumn.Tag = drvData.Row; } else { if (radBySlip.Checked) { if (drvData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].Equals(intRowPODetailId) && drvData[PO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD].Equals(intDeliveryScheduleId)) e.Column.DataColumn.Tag = drvData.Row; } } } break; #endregion #region Location // select location case (MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD): // user must select master location first if (_masterLocation.MasterLocationID < 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SELECT_MASTERLOCATION, MessageBoxIcon.Error); txtMasLoc.Focus(); e.Cancel = true; return; } htbConditions.Add(MST_LocationTable.MASTERLOCATIONID_FLD, _masterLocation.MasterLocationID); if (strValue != string.Empty) drvData = FormControlComponents.OpenSearchForm(MST_LocationTable.TABLE_NAME, MST_LocationTable.CODE_FLD, strValue, htbConditions, true); if (drvData == null) { if (strValue != string.Empty) e.Cancel = true; } else e.Column.DataColumn.Tag = drvData.Row; break; #endregion #region Bin // select bin case (MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD): int locationId; try { locationId = (int)dgrdData[dgrdData.Row, MST_LocationTable.LOCATIONID_FLD]; // user must select location first if (locationId <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, MessageBoxButtons.OK,MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]); e.Cancel = true; return; } } catch { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, MessageBoxButtons.OK,MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]); e.Cancel = true; return; } var voLocation = Utilities.Instance.GetLocation(locationId); if (voLocation.Bin.GetValueOrDefault(false)) dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Locked = false; else { dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Locked = true; return; } htbConditions.Add(MST_BINTable.LOCATIONID_FLD, locationId); if (radByInvoice.Checked) { htbConditions.Add(MST_BINTable.BINTYPEID_FLD, (int)BinTypeEnum.OK + " OR " + MST_BINTable.TABLE_NAME + ".BinTypeID = " + (int)BinTypeEnum.NG); } if (strValue != string.Empty) drvData = FormControlComponents.OpenSearchForm(MST_BINTable.TABLE_NAME, MST_BINTable.CODE_FLD, strValue, htbConditions, true); if (drvData == null) { if (strValue != string.Empty) e.Cancel = true; } else e.Column.DataColumn.Tag = drvData.Row; break; #endregion } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void dgrdData_BeforeDelete(object sender, C1.Win.C1TrueDBGrid.CancelEventArgs e) { if (_dataSource != null && _dataSource.Tables.Count > 0) { _dataSource.Tables[0].Columns[ReceiptlineCol].AutoIncrement = false; } } private void dgrdData_ButtonClick(object sender, ColEventArgs e) { const string methodName = This + ".dgrdData_ButtonClick()"; try { if (!dgrdData.AllowAddNew && !dgrdData.AllowUpdate) { return; } // if current column is locked then return if (dgrdData.Splits[0].Locked || dgrdData.Splits[0].DisplayColumns[dgrdData.Col].Locked) return; FillDataToGrid(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void dgrdData_KeyDown(object sender, KeyEventArgs e) { if (_formMode == EnumAction.Default) { return; } switch (e.KeyCode) { case Keys.F4: dgrdData_ButtonClick(null, null); break; case Keys.Delete: if (dgrdData.SelectedRows.Count <= 0) { return; } dgrdData.DeleteMultiRows(); // re-assign line value int intCount = 0; for (int i = 0; i < dgrdData.RowCount; i++) { dgrdData[i, ReceiptlineCol] = ++intCount; } break; } } private void dgrdData_OnAddNew(object sender, EventArgs e) { int intMaxLine = 0; // get max line number if (dgrdData.Row > 0) intMaxLine = (int)dgrdData[dgrdData.Row - 1, ReceiptlineCol]; dgrdData[dgrdData.Row, ReceiptlineCol] = ++intMaxLine; } private void dgrdData_RowColChange(object sender, RowColChangeEventArgs e) { const string methodName = This + ".dgrdData_RowColChange()"; try { if (e.LastRow != dgrdData.Row) { // if current Item is not controlled by Lot then Lock Lot cell var productId = 0; try { productId = (int)dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD]; // check if Lot cell of current row have no value then lock serial cell string strLot = dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.LOT_FLD].ToString().Trim(); dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.SERIAL_FLD].Locked = string.IsNullOrEmpty(strLot); } catch{} if (productId > 0) { var voCurrentProduct = Utilities.Instance.GetProductInfo(productId); dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.LOT_FLD].Locked = !voCurrentProduct.LotControl.GetValueOrDefault(false); } } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void btnAdd_Click(object sender, EventArgs e) { const string methodName = This + ".btnAdd_Click()"; try { // turn form mode to ADD _formMode = EnumAction.Add; // clear all data ResetForm(); _receiptMaster = new PO_PurchaseOrderReceiptMaster(); PostDatePicker.Value = Utilities.Instance.GetServerDate(); // fill in receive number ReceiveNoText.Text = FormControlComponents.GetNoByMask(this); //Fill Default Master Location FormControlComponents.SetDefaultMasterLocation(txtMasLoc); _masterLocationId = SystemProperty.MasterLocationID; _masterLocation.MasterLocationID = SystemProperty.MasterLocationID; radBySlip.Checked = true; _enmStatus = RadioStatus.BySlip; // switching form mode SwitchFormMode(); PostDatePicker.Focus(); PostDatePicker.SelectAll(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void btnSave_Click(object sender, EventArgs e) { const string methodName = This + ".btnSave_Click()"; try { DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_CONFIRM_BEFORE_SAVE_DATA, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (dlgResult == DialogResult.No) return; if (Security.IsDifferencePrefix(this, ReceiveNoLabel, ReceiveNoText)) return; if (dgrdData.EditActive) return; if (!CheckMandatoryFields()) return; // make a copy of source dataset _dataCopy = _dataSource.Copy(); if (SaveData()) { // turn to DEFAULT mode _formMode = EnumAction.Default; // get new data _dataSource = PurchaseOrderReceiptBO.Instance.ListReceiptDetailByReceiptMaster(_receiptMaster.PurchaseOrderReceiptID); // bind to grid BindDataToGrid(false); // switch form to DEFAULT mode SwitchFormMode(); // display successful message _enmOldRadioStatus = RadioStatus.BySlip; PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA, MessageBoxButtons.OK,MessageBoxIcon.Information); } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } // restore the source _dataSource = new DataSet(); _dataSource = _dataCopy.Copy(); BindDataToGrid(false); } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } // restore the source _dataSource = new DataSet(); _dataSource = _dataCopy.Copy(); BindDataToGrid(false); } } private void btnDelete_Click(object sender, EventArgs e) { const string methodName = This + ".btnDelete_Click()"; if (PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { try { var products = _dataSource.Tables[0].Rows.Cast<DataRow>().Select(r => (int)r[PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD]).ToList(); string strReturnNo = PurchaseOrderReceiptBO.Instance.CheckReturn(_receiptMaster, products, radByInvoice.Checked); if (strReturnNo != string.Empty) { var strMsg = new[] { strReturnNo }; PCSMessageBox.Show(ErrorCode.MESSAGE_CANNOT_DELETE_RECEIPT, MessageBoxIcon.Information, strMsg); return; } //1. turn form mode to Delete _formMode = EnumAction.Delete; PurchaseOrderReceiptBO.Instance.DeletePOReceipt(_receiptMaster.PurchaseOrderReceiptID); //2. turn form mode to Default _formMode = EnumAction.Default; //3. clear all data ResetForm(); //4. Enable and Disable controls SwitchFormMode(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } } private void btnDeleteRow_Click(object sender, EventArgs e) { const string methodName = This + ".btnDeleteRow_Click()"; if (PCSMessageBox.Show(ErrorCode.MESSAGE_DELETE_RECORD, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { try { var products = new List<int>(); products.Add(dgrdData.RowCount > 0 ? Convert.ToInt32(dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD]) : Convert.ToInt32(_dataSource.Tables[0].Rows[0][PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD])); string strReturnNo = PurchaseOrderReceiptBO.Instance.CheckReturn(_receiptMaster, products, radByInvoice.Checked); if (strReturnNo != string.Empty) { var strMsg = new[] { strReturnNo }; PCSMessageBox.Show(ErrorCode.MESSAGE_CANNOT_DELETE_RECEIPT, MessageBoxIcon.Information, strMsg); return; } if (dgrdData.RowCount > 0) { #region delete row //1. turn form mode to Delete _formMode = EnumAction.Delete; // If Rows.count = 1 then delete voucher int intPurchaseOrderReceiptId = GetCurrentRow(); PurchaseOrderReceiptBO.Instance.DeleteRowPOReceipt(_receiptMaster.PurchaseOrderReceiptID,intPurchaseOrderReceiptId); //2. turn form mode to Default _formMode = EnumAction.Default; //3. Load Receipt no DataRowView drowData = FormControlComponents.OpenSearchForm(PO_PurchaseOrderReceiptMasterTable.TABLE_NAME, PO_PurchaseOrderReceiptMasterTable.RECEIVENO_FLD, ReceiveNoText.Text.Trim(), null, false); if (drowData != null) FillMasterData((int)drowData.Row[PO_PurchaseOrderReceiptMasterTable.PURCHASEORDERRECEIPTID_FLD]); #endregion } else { #region Delete voucher //1. turn form mode to Delete _formMode = EnumAction.Delete; PurchaseOrderReceiptBO.Instance.DeletePOReceipt(_receiptMaster.PurchaseOrderReceiptID); //2. turn form mode to Default _formMode = EnumAction.Default; //3. clear all data ResetForm(); //4. Enable and Disable controls SwitchFormMode(); #endregion } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } } } private void btnPrint_Click(object sender, EventArgs e) { if (_receiptMaster == null) { return; } if (_receiptMaster.PurchaseOrderReceiptID <= 0) { return; } ShowPOSlipReport(); } private void btnBOMShortage_Click(object sender, EventArgs e) { const string methodName = This + ".ReceiveNoText_Validating()"; try { //return if condition is not match if (!radOutside.Checked || _dataSource == null || txtProductionLine.Tag == null || _pONumber == string.Empty || PostDatePicker.Text.Trim().Equals(string.Empty) || txtOutside.Text.Trim().Equals(string.Empty) || dgrdData.RowCount <= 0) { return; } if (_dataSource.Tables[0].Rows.Count == 0) { return; } Cursor = Cursors.WaitCursor; ShowBOMShortageReport(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } finally { Cursor = Cursors.Default; } } private void btnClose_Click(object sender, EventArgs e) { Close(); } #region private methods private void ResetForm() { // clear all data _receiptMaster = new PO_PurchaseOrderReceiptMaster(); if ((_dataSource != null) && (_dataSource.Tables.Count > 0)) { _dataSource.Tables[0].Clear(); } PostDatePicker.Value = DBNull.Value; ReceiveNoText.Text = string.Empty; txtMasLoc.Text = string.Empty; ReceiveNoText.Text = string.Empty; txtVendorNo.Text = string.Empty; txtVendorName.Text = string.Empty; txtDeliverySlip.Text = string.Empty; txtInvoice.Text = string.Empty; txtOutside.Text = txtProductionLine.Text = string.Empty; _invoiceMaster = new PO_InvoiceMaster(); _receiptMaster = new PO_PurchaseOrderReceiptMaster(); cboPurpose.SelectedIndex = 0; } /// <summary> /// Enable or disable button based on receipt type /// </summary> private void EnableButtons() { bool blnBySlip = (radBySlip.Checked && radBySlip.Enabled); bool blnByInvoice = (radByInvoice.Checked && radByInvoice.Enabled); bool blnOutside = (radOutside.Checked && radOutside.Enabled); txtVendorName.Enabled = blnByInvoice; txtVendorNo.Enabled = blnByInvoice; txtDeliverySlip.Enabled = btnDeliverySlip.Enabled = blnBySlip; txtInvoice.Enabled = btnInvoice.Enabled = blnByInvoice; txtOutside.Enabled = btnOutside.Enabled = txtProductionLine.Enabled = btnProductionLine.Enabled = lblProductionLine.Enabled = blnOutside; } private bool ConfirmRadio() { if (_enmStatus != _enmOldRadioStatus) { //Confirm message: Are you sure you want to change type of receipt DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_CONFIRM_CHANGE_TYPE_OF_RECEIVING, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); switch (dlgResult) { case DialogResult.Yes: _enmOldRadioStatus = _enmStatus; return true; //break; default: _enmStatus = RadioStatus.NoChange; if (_enmOldRadioStatus == RadioStatus.BySlip) { radBySlip.Checked = true; _enmStatus = RadioStatus.BySlip; } else if (_enmOldRadioStatus == RadioStatus.ByInvoice) { radByInvoice.Checked = true; _enmStatus = RadioStatus.ByInvoice; } else if (_enmOldRadioStatus == RadioStatus.ByOutside) { radOutside.Checked = true; _enmStatus = RadioStatus.ByOutside; } return false; //break; } } return false; } /// <summary> /// This methods uses to assign default value for grid /// </summary> private void AssignDefaultValue() { // if receipt by PO then we assign default value for PO MasterID if (radBySlip.Checked && _poMaster != null && (_poMaster.PurchaseOrderMasterID > 0)) { _dataSource.Tables[0].Columns[PO_PurchaseOrderMasterTable.TABLE_NAME + PO_PurchaseOrderMasterTable.CODE_FLD].DefaultValue = _poMaster.Code; _dataSource.Tables[0].Columns[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD].DefaultValue = _poMaster.PurchaseOrderMasterID; } for (int i = 0; i < dgrdData.RowCount; i++) { if (dgrdData.AddNewMode == AddNewModeEnum.NoAddNew) { var poDetailId = (int) dgrdData[i, PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD]; // get detail information _poDetail = PurchaseOrderReceiptBO.Instance.GetPurchaseOrderDetail(poDetailId); // UMRate if (_poDetail.StockUMID != _poDetail.BuyingUMID) { // get UM Rate decimal decRate = Utilities.Instance.GetRate(_poDetail.BuyingUMID, _poDetail.StockUMID); if (decRate > 0) dgrdData[i, PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD] = decRate; else dgrdData[i, PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD] = decimal.MinusOne; } else dgrdData[i, PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD] = decimal.One; } } _dataSource.Tables[0].Columns[PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD].DefaultValue = decimal.MinusOne; } private void SwitchFormMode() { if (_formMode == EnumAction.Add) { dgrdData.AllowAddNew = true; dgrdData.AllowUpdate = true; dgrdData.AllowDelete = true; PostDatePicker.Enabled = true; CCNCombo.Enabled = true; ReceiveNoText.Enabled = true; SearchReceiveButton.Enabled = false; txtMasLoc.Enabled = true; btnSearchMasLoc.Enabled = true; radBySlip.Enabled = true; radBySlip.Enabled = true; radByInvoice.Enabled = true; radOutside.Enabled = true; txtDeliverySlip.Enabled = btnDeliverySlip.Enabled = radBySlip.Checked; txtInvoice.Enabled = btnInvoice.Enabled = radByInvoice.Checked; dgrdData.Splits[0].Locked = true; dgrdData.AllowDelete = true; btnAdd.Enabled = false; btnSave.Enabled = true; btnPrint.Enabled = false; btnDelete.Enabled = false; btnDeleteRow.Enabled = false; cboPurpose.Enabled = true; } else if (_formMode == EnumAction.Default) { dgrdData.AllowAddNew = false; dgrdData.AllowUpdate = false; dgrdData.AllowDelete = false; PostDatePicker.Enabled = false; CCNCombo.Enabled = false; ReceiveNoText.Enabled = true; SearchReceiveButton.Enabled = true; txtMasLoc.Enabled = false; btnSearchMasLoc.Enabled = false; txtOutside.Enabled = btnOutside.Enabled = txtProductionLine.Enabled = btnProductionLine.Enabled = false; radBySlip.Enabled = false; radBySlip.Enabled = false; radByInvoice.Enabled = false; radOutside.Enabled = false; txtDeliverySlip.Enabled = btnDeliverySlip.Enabled = (radBySlip.Checked && radBySlip.Enabled); txtInvoice.Enabled = btnInvoice.Enabled = (radByInvoice.Checked && radByInvoice.Enabled); foreach (C1DisplayColumn dcolCol in dgrdData.Splits[0].DisplayColumns) { dcolCol.Locked = true; } btnAdd.Enabled = true; btnSave.Enabled = false; if (_receiptMaster != null && _receiptMaster.PurchaseOrderReceiptID > 0) { btnPrint.Enabled = true; btnDelete.Enabled = true; btnDeleteRow.Enabled = true; } else { btnPrint.Enabled = false; btnDelete.Enabled = false; btnDeleteRow.Enabled = false; } cboPurpose.Enabled = false; } btnBOMShortage.Enabled = false; } /// <summary> /// Fills the master location data. /// </summary> /// <param name="masterLocationId">The master location id.</param> private void FillMasterLocationData(int masterLocationId) { if (masterLocationId > 0) { _masterLocationId = masterLocationId; _masterLocation = Utilities.Instance.GetMasterLocation(masterLocationId); // fill Master location info to form txtMasLoc.Text = _masterLocation.Code; } else { _masterLocationId = masterLocationId; _masterLocation = new MST_MasterLocation(); // fill Master location info to form txtMasLoc.Text = string.Empty; } } /// <summary> /// Fill Customer information to form /// </summary> /// <param name="partyId">Party ID</param> private void FillCustomerInfo(int partyId) { var customerInfo = Utilities.Instance.GetCustomerInfo(partyId); txtVendorName.Text = customerInfo.Name; txtVendorNo.Text = customerInfo.Code; } private void BindDataToGrid(bool pblnAddManual) { if (_dataSource != null && _dataSource.Tables.Count > 0) { // bind data if (pblnAddManual) _dataSource.Tables[0].Clear(); // fill data into grid dgrdData.DataSource = _dataSource.Tables[0]; FormControlComponents.RestoreGridLayout(dgrdData, _gridLayOut); #region restore column caption and setting display style // unlock the grid. dgrdData.Splits[0].Locked = false; foreach (C1DisplayColumn objCol in dgrdData.Splits[0].DisplayColumns) objCol.Locked = true; dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].Locked = false; dgrdData.Columns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT; dgrdData.Columns[PO_DeliveryScheduleTable.RECEIVEDQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT; dgrdData.Columns[PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT; dgrdData.Splits[0].DisplayColumns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD].Button = true; dgrdData.Splits[0].DisplayColumns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD].Locked = false; dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Button = true; dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Locked = false; dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.LOT_FLD].Locked = false; dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.QASTATUS_FLD].Locked = false; dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.SERIAL_FLD].Locked = false; #endregion AssignDefaultValue(); // if receipt by invoice if (radByInvoice.Checked) { // lock all columns first foreach (C1DisplayColumn dcolData in dgrdData.Splits[0].DisplayColumns) { dcolData.Button = false; dcolData.Locked = true; } // unlock quantity dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].Locked = false; // unlock location dgrdData.Splits[0].DisplayColumns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]. Button = true; dgrdData.Splits[0].DisplayColumns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]. Locked = false; // unlock bin dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Button = true; dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Locked = false; // unlock lot dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.LOT_FLD].Locked = false; // unlock serial dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.SERIAL_FLD].Locked = false; // not allow user to add new line or delete a line dgrdData.AllowAddNew = false; dgrdData.AllowDelete = false; } } } /// <summary> /// Fills the master data. /// </summary> /// <param name="masterId">The master id.</param> private void FillMasterData(int masterId) { // get POReceiptMasterVO object _receiptMaster = PurchaseOrderReceiptBO.Instance.GetReceiptMaster(masterId); // get data source _dataSource = PurchaseOrderReceiptBO.Instance.ListReceiptDetailByReceiptMaster(_receiptMaster.PurchaseOrderReceiptID); // fill data to form ReceiveNoText.Text = _receiptMaster.ReceiveNo; PostDatePicker.Value = _receiptMaster.PostDate; CCNCombo.SelectedValue = _receiptMaster.CCNID; FillMasterLocationData(_receiptMaster.MasterLocationID); txtInvoice.Text = txtDeliverySlip.Text = txtOutside.Text = txtProductionLine.Text = string.Empty; if (_receiptMaster.Purpose != null) cboPurpose.SelectedIndex = (int) _receiptMaster.Purpose; switch (_receiptMaster.ReceiptType) { case (int)POReceiptTypeEnum.ByInvoice: radByInvoice.Checked = true; txtInvoice.Text = _receiptMaster.RefNo; txtDeliverySlip.Text = string.Empty; // get invoice master _invoiceMaster = PurchaseOrderReceiptBO.Instance.GetInvoiceMaster(_receiptMaster.RefNo); // get vendor info _partyId = _invoiceMaster.PartyID; FillCustomerInfo(_partyId); break; case (int)POReceiptTypeEnum.ByDeliverySlip: radBySlip.Checked = true; txtInvoice.Text = string.Empty; txtDeliverySlip.Text = _receiptMaster.RefNo; _poMaster = PurchaseOrderReceiptBO.Instance.GetPurchaseOrderMaster(_receiptMaster.PurchaseOrderMasterID.GetValueOrDefault(0)); // get vendor info _partyId = _poMaster.PartyID; FillCustomerInfo(_partyId); break; case (int)POReceiptTypeEnum.ByOutside: radOutside.Checked = true; txtOutside.Text = _receiptMaster.RefNo; txtProductionLine.Tag = _receiptMaster.ProductionLineID; if (_receiptMaster.ProductionLineID.HasValue) { txtProductionLine.Text = _receiptMaster.PRO_ProductionLine.Code; // get vendor info _partyId = _receiptMaster.PO_PurchaseOrderMaster.PartyID; } FillCustomerInfo(_partyId); break; } // bind data grid BindDataToGrid(false); // turn form to Default mode for view only _formMode = EnumAction.Default; // switch form mode SwitchFormMode(); } /// <summary> /// Radio status /// </summary> internal enum RadioStatus { /// <summary> /// By Slip /// </summary> BySlip = 0, /// <summary> /// By Invoice /// </summary> ByInvoice = 1, /// <summary> /// By Outside /// </summary> ByOutside = 2, /// <summary> /// No changes /// </summary> NoChange = 3 } /// <summary> /// This method use to fill master data when select Invoice /// </summary> /// <param name="pdrowData">Data Row</param> private void FillInvoiceData(DataRow pdrowData) { if (pdrowData == null) { txtVendorName.Text = string.Empty; txtVendorNo.Text = string.Empty; if ((_dataSource != null) && (_dataSource.Tables.Count > 0)) { _dataSource.Tables[0].Clear(); } // lock grid foreach (C1DisplayColumn dcolC1 in dgrdData.Splits[0].DisplayColumns) dcolC1.Locked = true; return; } // get invoice master _invoiceMaster = PurchaseOrderReceiptBO.Instance.GetInvoiceMaster(pdrowData[PO_InvoiceMasterTable.INVOICENO_FLD].ToString()); // get data source _dataSource = PurchaseOrderReceiptBO.Instance.ListByInvoice(_invoiceMaster.InvoiceMasterID); // fill data to form txtInvoice.Text = _invoiceMaster.InvoiceNo; txtInvoice.Tag = _invoiceMaster.InvoiceMasterID; // get vendor info _partyId = _invoiceMaster.PartyID; FillCustomerInfo(_partyId); // fill to data grid if (_dataSource.Tables.Count > 0 && _dataSource.Tables[0].Rows.Count > 0) { BindDataToGrid(false); } else { if (_dataSource != null && _dataSource.Tables.Count > 0) { _dataSource.Tables[0].Clear(); } BindDataToGrid(false); // lock the grid dgrdData.Splits[0].Locked = true; } } /// <summary> /// Fills the production line. /// </summary> /// <param name="pdrowData">The pdrow data.</param> private void FillProductionLine(DataRow pdrowData) { if (pdrowData == null) { txtProductionLine.Text = string.Empty; txtProductionLine.Tag = null; btnBOMShortage.Enabled = false; } else { var productionLineId = (int) pdrowData[PRO_ProductionLineTable.PRODUCTIONLINEID_FLD]; txtProductionLine.Tag = productionLineId; txtProductionLine.Text = pdrowData[PRO_ProductionLineTable.CODE_FLD].ToString(); if (radOutside.Checked && _dataSource != null && _pONumber != string.Empty && !PostDatePicker.Text.Trim().Equals(string.Empty) && !txtOutside.Text.Trim().Equals(string.Empty) && dgrdData.RowCount > 0) { btnBOMShortage.Enabled = true; } else { btnBOMShortage.Enabled = false; } } } private void FillPOLineData(DataRow pdrowData) { dgrdData.EditActive = true; if (pdrowData != null) { // id value dgrdData[dgrdData.Row, PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD] = pdrowData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD]; // display value dgrdData[dgrdData.Row, PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD] = pdrowData[PO_PurchaseOrderDetailTable.LINE_FLD]; // receive quantity dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD] = pdrowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]; // UM dgrdData[dgrdData.Row, MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD] = pdrowData[MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD]; dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.STOCKUMID_FLD] = pdrowData[PO_PurchaseOrderDetailTable.STOCKUMID_FLD]; dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.BUYINGUMID_FLD] = pdrowData[PO_PurchaseOrderDetailTable.BUYINGUMID_FLD]; if (pdrowData[PO_PurchaseOrderDetailTable.STOCKUMID_FLD].ToString() != pdrowData[PO_PurchaseOrderDetailTable.BUYINGUMID_FLD].ToString()) { // get UM Rate decimal decUMRate = Utilities.Instance.GetRate((int)pdrowData[PO_PurchaseOrderDetailTable.BUYINGUMID_FLD], (int)pdrowData[PO_PurchaseOrderDetailTable.STOCKUMID_FLD]); if (decUMRate > 0) dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD] = decUMRate; else dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD] = decimal.MinusOne; } else dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD] = decimal.One; // if Item is not controlled by Lot, lock Lot cell var voCurrentProduct = Utilities.Instance.GetProductInfo(int.Parse(pdrowData[ITM_ProductTable.PRODUCTID_FLD].ToString())); dgrdData.Splits[0].DisplayColumns[PO_PurchaseOrderReceiptDetailTable.LOT_FLD].Locked = !voCurrentProduct.LotControl.GetValueOrDefault(false); // get default location of item if (voCurrentProduct.LocationID.GetValueOrDefault(0) > 0) { dgrdData[dgrdData.Row, MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD] = voCurrentProduct.MST_Location.Code; dgrdData[dgrdData.Row, MST_LocationTable.LOCATIONID_FLD] = voCurrentProduct.LocationID; } // get default bin of item if (voCurrentProduct.BinID.GetValueOrDefault(0) > 0) { dgrdData[dgrdData.Row, MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD] = voCurrentProduct.MST_BIN.Code; dgrdData[dgrdData.Row, MST_BINTable.LOCATIONID_FLD] = voCurrentProduct.BinID; } // temporary, we need to assign DeliveryScheduleID value when user open search form // if Receipt by schedule if (radBySlip.Checked) dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.DELIVERYSCHEDULEID_FLD] = pdrowData[PO_PurchaseOrderReceiptDetailTable.DELIVERYSCHEDULEID_FLD]; // in case of receipt by PO, we need to fill item detail when select PO detail if (radBySlip.Checked) { // code value dgrdData[dgrdData.Row, ITM_ProductTable.TABLE_NAME + ITM_ProductTable.CODE_FLD] = voCurrentProduct.Code; // description value dgrdData[dgrdData.Row, ITM_ProductTable.DESCRIPTION_FLD] = voCurrentProduct.Description; // revision value dgrdData[dgrdData.Row, ITM_ProductTable.REVISION_FLD] = voCurrentProduct.Revision; // receive quantity value dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD] = pdrowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]; // id value dgrdData[dgrdData.Row, ITM_ProductTable.PRODUCTID_FLD] = voCurrentProduct.ProductID; } } else { // id value dgrdData[dgrdData.Row, PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD] = DBNull.Value; // display value dgrdData[dgrdData.Row, PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD] = string.Empty; // receive quantity dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD] = string.Empty; // UM dgrdData[dgrdData.Row, MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD] = string.Empty; dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.STOCKUMID_FLD] = DBNull.Value; dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.BUYINGUMID_FLD] = DBNull.Value; dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD] = decimal.Zero; // location dgrdData[dgrdData.Row, MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD] = string.Empty; dgrdData[dgrdData.Row, MST_LocationTable.LOCATIONID_FLD] = DBNull.Value; // bin dgrdData[dgrdData.Row, MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD] = string.Empty; dgrdData[dgrdData.Row, MST_BINTable.LOCATIONID_FLD] = DBNull.Value; // in case of receipt by PO, we need to fill item detail when select PO detail if (radBySlip.Checked) { // code value dgrdData[dgrdData.Row, ITM_ProductTable.TABLE_NAME + ITM_ProductTable.CODE_FLD] = string.Empty; // description value dgrdData[dgrdData.Row, ITM_ProductTable.DESCRIPTION_FLD] = string.Empty; // revision value dgrdData[dgrdData.Row, ITM_ProductTable.REVISION_FLD] = string.Empty; // id value dgrdData[dgrdData.Row, ITM_ProductTable.PRODUCTID_FLD] = DBNull.Value; } } } private void FillLocationData(DataRow pdrowData) { dgrdData.EditActive = true; if (pdrowData != null) { var voLocation = Utilities.Instance.GetLocation((int)pdrowData[MST_LocationTable.LOCATIONID_FLD]); // display value dgrdData[dgrdData.Row, MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD] = voLocation.Code; // id dgrdData[dgrdData.Row, MST_LocationTable.LOCATIONID_FLD] = voLocation.LocationID; // clear bin id dgrdData[dgrdData.Row, MST_BINTable.BINID_FLD] = DBNull.Value; // clear bin code dgrdData[dgrdData.Row, MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD] = string.Empty; // clear Lot dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.LOT_FLD] = string.Empty; // clear Serial dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.SERIAL_FLD] = string.Empty; // if select Location is not controlled by bin // lock Bin cell dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Locked = !voLocation.Bin.GetValueOrDefault(false); } else { // display value dgrdData[dgrdData.Row, MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD] = string.Empty; // id dgrdData[dgrdData.Row, MST_LocationTable.LOCATIONID_FLD] = DBNull.Value; // clear bin id dgrdData[dgrdData.Row, MST_BINTable.BINID_FLD] = DBNull.Value; // clear bin code dgrdData[dgrdData.Row, MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD] = string.Empty; // clear Lot dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.LOT_FLD] = string.Empty; // clear Serial dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.SERIAL_FLD] = string.Empty; } } private void FillBinData(DataRow pdrowData) { dgrdData.EditActive = true; if (pdrowData != null) { // display value dgrdData[dgrdData.Row, MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD] = pdrowData[MST_BINTable.CODE_FLD]; // id dgrdData[dgrdData.Row, MST_BINTable.BINID_FLD] = pdrowData[MST_BINTable.BINID_FLD]; } else { // display value dgrdData[dgrdData.Row, MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD] = string.Empty; // id dgrdData[dgrdData.Row, MST_BINTable.BINID_FLD] = DBNull.Value; } // clear Lot dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.LOT_FLD] = string.Empty; // clear Serial dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.SERIAL_FLD] = string.Empty; } private void FillDataToGrid() { string strColumn = dgrdData.Columns[dgrdData.Col].DataField; string strValue = dgrdData.Columns[dgrdData.Col].Text.Trim(); DataRowView drvData = null; var htbConditions = new Hashtable(); if (dgrdData.AllowAddNew) switch (strColumn) { #region // select purchase order line case (PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD): if (radBySlip.Checked) { htbConditions.Add(v_PurchaseOrderOfItem.PO_CODE, dgrdData[dgrdData.Row, "PO_PurchaseOrderMasterCode"].ToString()); if (_slipDate != DateTime.MaxValue) { htbConditions.Add(YearFilter, _slipDate.Year); htbConditions.Add(MonthFilter, _slipDate.Month); htbConditions.Add(DayFilter, _slipDate.Day); htbConditions.Add(HourFilter, _slipDate.Hour); } drvData = FormControlComponents.OpenSearchForm(v_ReceiptBySchedule.VIEW_NAME, PO_PurchaseOrderDetailTable.LINE_FLD, strValue, htbConditions, true); } if (drvData != null) { string strExpression = PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD + Constants.EQUAL + drvData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString(); if (radBySlip.Checked) strExpression += Constants.AND + PO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD + Constants.EQUAL + drvData[PO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD].ToString(); // we need to check for exsiting PO Line and delivery line in the list DataRow[] drowExisted = _dataSource.Tables[0].Select(strExpression); if (drowExisted.Length.Equals(0)) { FillPOLineData(drvData.Row); } } else { if (strValue != string.Empty) { dgrdData.Row = dgrdData.Row; dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD]); dgrdData.Select(); return; } FillPOLineData(null); } break; #endregion #region // select location case (MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD): // user must select master location first if (_masterLocation.MasterLocationID <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SELECT_MASTERLOCATION, MessageBoxIcon.Error); txtMasLoc.Focus(); return; } htbConditions.Add(MST_LocationTable.MASTERLOCATIONID_FLD, _masterLocation.MasterLocationID); drvData = FormControlComponents.OpenSearchForm(MST_LocationTable.TABLE_NAME, MST_LocationTable.CODE_FLD, strValue, htbConditions, true); if (drvData != null) { FillLocationData(drvData.Row); } else { if (strValue != string.Empty) { dgrdData.Row = dgrdData.Row; dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]); dgrdData.Select(); return; } FillLocationData(null); } break; #endregion #region // select bin case (MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD): int intLocationID = 0; try { intLocationID = int.Parse(dgrdData[dgrdData.Row, MST_LocationTable.LOCATIONID_FLD].ToString()); // user must select location first if (intLocationID <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, MessageBoxButtons.OK,MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]); return; } } catch { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, MessageBoxButtons.OK,MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]); return; } var voLocation = Utilities.Instance.GetLocation(intLocationID); if (voLocation.Bin.GetValueOrDefault(false)) dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Locked = false; else { dgrdData.Splits[0].DisplayColumns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD].Locked = true; return; } string strWhereClause = MST_BINTable.TABLE_NAME + "." + MST_BINTable.LOCATIONID_FLD + "=" + intLocationID; if (radOutside.Checked) { strWhereClause += " AND (" + MST_BINTable.TABLE_NAME + "." + MST_BINTable.BINTYPEID_FLD + "=" + (int)BinTypeEnum.OK + " OR " + MST_BINTable.TABLE_NAME + ".BinTypeID = " + (int)BinTypeEnum.NG + ")"; } drvData = FormControlComponents.OpenSearchForm(MST_BINTable.TABLE_NAME, MST_BINTable.CODE_FLD, strValue, strWhereClause); if (drvData != null) { FillBinData(drvData.Row); } else { if (strValue != string.Empty) { dgrdData.Row = dgrdData.Row; dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD]); dgrdData.Select(); return; } FillBinData(null); } break; #endregion } } /// <summary> /// This method uses to check all madatory fields in form. /// </summary> /// <returns>True if succeed. False if failure</returns> private bool CheckMandatoryFields() { // check mandatory field if (FormControlComponents.CheckMandatory(CCNCombo)) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); CCNCombo.Focus(); return false; } if (PostDatePicker.ValueIsDbNull) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); PostDatePicker.Focus(); return false; } if (!FormControlComponents.CheckDateInCurrentPeriod((DateTime)PostDatePicker.Value)) { PCSMessageBox.Show(ErrorCode.MESSAGE_PKL_TRANSDATE_PERIOD, MessageBoxButtons.OK, MessageBoxIcon.Error); PostDatePicker.Focus(); return false; } DateTime dtmDBDate = Utilities.Instance.GetServerDate(); if (dtmDBDate < (DateTime)PostDatePicker.Value) { PCSMessageBox.Show(ErrorCode.MESSAGE_INV_TRANSACTION_CANNOT_IN_FUTURE, MessageBoxButtons.OK, MessageBoxIcon.Error); PostDatePicker.Focus(); return false; } if (FormControlComponents.CheckMandatory(ReceiveNoText)) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); ReceiveNoText.Focus(); return false; } if (FormControlComponents.CheckMandatory(txtMasLoc)) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); txtMasLoc.Focus(); return false; } // Outside if (txtOutside.Text != string.Empty) if (FormControlComponents.CheckMandatory(txtProductionLine)) { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); txtProductionLine.Focus(); return false; } //Check postdate in configuration if (!FormControlComponents.CheckPostDateInConfiguration((DateTime)PostDatePicker.Value)) { return false; } _ccnId = (int)CCNCombo.SelectedValue; if (dgrdData.RowCount <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_PORECEIPT_INPUT_DETAIL, MessageBoxIcon.Error); return false; } if (_formMode != EnumAction.Edit) { var dtmSelectedDate = (DateTime)(PostDatePicker.Value); dtmSelectedDate = new DateTime(dtmSelectedDate.Year, dtmSelectedDate.Month, dtmSelectedDate.Day, dtmSelectedDate.Hour, dtmSelectedDate.Minute, 0); for (int i = 0; i < dgrdData.RowCount; i++) { dgrdData.Row = i; decimal decReceiveQuantity = 0; int intLocationID = 0; int intPOLineID = 0; #region Purchase Order Master // purchase order master try { if (int.Parse(dgrdData[i, PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD].ToString()) <= 0) throw new Exception(); } catch { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderMasterTable.TABLE_NAME + PO_PurchaseOrderMasterTable.CODE_FLD]); dgrdData.Select(); return false; } #endregion #region Purchase Order Line // purchase order line try { intPOLineID = int.Parse(dgrdData[i, PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString()); if (intPOLineID <= 0) throw new Exception(); } catch { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderDetailTable.TABLE_NAME + PO_PurchaseOrderDetailTable.LINE_FLD]); dgrdData.Select(); return false; } #endregion #region Postdate must greater than Approved Date _poDetail = PurchaseOrderReceiptBO.Instance.GetPurchaseOrderDetail(intPOLineID); if (_poDetail.ApprovalDate != null) { var approvalDate = (DateTime) _poDetail.ApprovalDate; _poDetail.ApprovalDate = new DateTime(approvalDate.Year, approvalDate.Month, approvalDate.Day, approvalDate.Hour, approvalDate.Minute, 0); } if (dtmSelectedDate < _poDetail.ApprovalDate) { // Cannot receive this line because of Post Date < ApprovalDate PCSMessageBox.Show(ErrorCode.MESSAGE_POST_DATE_LESS_THAN_APPROVAL_DATE, MessageBoxButtons.OK,MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderMasterTable.TABLE_NAME + PO_PurchaseOrderMasterTable.CODE_FLD]); dgrdData.Select(); PostDatePicker.Focus(); return false; } #endregion #region Product // product try { if (int.Parse(dgrdData[i, ITM_ProductTable.PRODUCTID_FLD].ToString()) <= 0) throw new Exception(); } catch { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[ITM_ProductTable.TABLE_NAME + ITM_ProductTable.CODE_FLD]); dgrdData.Select(); return false; } #endregion #region Stock UM // stock um try { if (int.Parse(dgrdData[i, PO_PurchaseOrderReceiptDetailTable.STOCKUMID_FLD].ToString()) <= 0) throw new Exception(); } catch { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_UnitOfMeasureTable.TABLE_NAME + MST_UnitOfMeasureTable.CODE_FLD]); dgrdData.Select(); return false; } #endregion #region check UM rate try { decimal decUMRate = 0; try { decUMRate = decimal.Parse(dgrdData[i, PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD].ToString()); } catch { } if ((decUMRate <= 0) && (_poDetail.BuyingUMID != _poDetail.StockUMID)) { decUMRate = Utilities.Instance.GetRate(_poDetail.BuyingUMID, _poDetail.StockUMID); if (decUMRate <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SET_UMRATE, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Select(); return false; } } } catch { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Select(); return false; } #endregion #region Location // location try { intLocationID = int.Parse(dgrdData[i, MST_LocationTable.LOCATIONID_FLD].ToString()); if (intLocationID <= 0) throw new Exception(); } catch { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]); dgrdData.Select(); return false; } #endregion #region Selected Location must be in selected Master Location var voLocation = Utilities.Instance.GetLocation(intLocationID); if (voLocation.MasterLocationID != _masterLocation.MasterLocationID) { PCSMessageBox.Show(ErrorCode.MESSAGE_LOCATION_NOT_MATCH_WITH_MASLOC, MessageBoxButtons.OK,MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD]); dgrdData.Select(); return false; } #endregion #region Check Bin if Location is Bin controlled or not int intBinID = 0; if (intLocationID > 0) { try { intBinID = int.Parse(dgrdData[i, MST_BINTable.BINID_FLD].ToString()); } catch { } if (voLocation.Bin.GetValueOrDefault(false)) { // if Location is Bin controlled but user not select Bin yet if (intBinID <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_SELECT_BIN_FOR_LOCATION, MessageBoxButtons.OK,MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD]); dgrdData.Select(); return false; } } else { // if Location is not Bin controlled but user already select Bin if (intBinID > 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_MUST_CANNOT_SELECT_BIN_FOR_LOCATION,MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD]); dgrdData.Select(); return false; } } } #endregion #region Receive Quantity // receive quantity try { decReceiveQuantity = decimal.Parse(dgrdData[i, PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString()); if (decReceiveQuantity <= 0) { PCSMessageBox.Show(ErrorCode.MESSAGE_RGA_RECEIVEQTYTOZERO, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]); dgrdData.Select(); return false; } // get current receive quantity from database decimal decCurrentReceiveQuantity = 0; decimal decOrderQuantity = 0; try { decCurrentReceiveQuantity = decimal.Parse(dgrdData[dgrdData.Row, PO_DeliveryScheduleTable.RECEIVEDQUANTITY_FLD].ToString()); } catch { } try { decOrderQuantity = decimal.Parse(dgrdData[dgrdData.Row, PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD].ToString()); } catch { } // if sum of current receive quantity from database and receive quantity input by user // greater than total delivery from po detail then warn user if (decOrderQuantity < (decCurrentReceiveQuantity + decReceiveQuantity) || decOrderQuantity < decReceiveQuantity) { DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_RECEIVE_GREATER_THAN_TOTAL, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1); if (dlgResult == DialogResult.No) { dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]); dgrdData.Select(); return false; } } } catch { PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error); dgrdData.Col = dgrdData.Columns.IndexOf(dgrdData.Columns[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]); dgrdData.Select(); return false; } #endregion } } return true; } private bool SaveData() { // prepare data for Master Receipt var dtmDateOnly = (DateTime)PostDatePicker.Value; dtmDateOnly = new DateTime(dtmDateOnly.Year, dtmDateOnly.Month, dtmDateOnly.Day, dtmDateOnly.Hour, dtmDateOnly.Minute, 0); _receiptMaster.PostDate = dtmDateOnly; _receiptMaster.MasterLocationID = _masterLocationId; _receiptMaster.CCNID = int.Parse(CCNCombo.SelectedValue.ToString()); _receiptMaster.UserName = SystemProperty.UserName; _receiptMaster.LastChange = Utilities.Instance.GetServerDate(); _receiptMaster.Purpose = cboPurpose.SelectedIndex; // END: Trada 28-12-2005 if (radByInvoice.Checked) { _receiptMaster.ReceiptType = (int)POReceiptTypeEnum.ByInvoice; _receiptMaster.RefNo = txtInvoice.Text.Trim(); _receiptMaster.InvoiceMasterID = Convert.ToInt32(txtInvoice.Tag); } else if (radBySlip.Checked) { _receiptMaster.ReceiptType = (int)POReceiptTypeEnum.ByDeliverySlip; _receiptMaster.RefNo = txtDeliverySlip.Text.Trim(); _receiptMaster.InvoiceMasterID = null; } else if (radOutside.Checked) { _receiptMaster.ReceiptType = (int)POReceiptTypeEnum.ByOutside; _receiptMaster.RefNo = txtOutside.Text.Trim(); _receiptMaster.InvoiceMasterID = null; _receiptMaster.ProductionLineID = Convert.ToInt32(txtProductionLine.Tag); var locationBin = PurchaseOrderReceiptBO.Instance.GetLocationAndBin(null, (int)_receiptMaster.ProductionLineID); if (locationBin.Length == 0) { // Show message: You have to issue material to Outside before receipt finished goods. PCSMessageBox.Show(ErrorCode.MESSAGE_ISSUE_MATERIAL_TO_OUTSIDE, MessageBoxIcon.Error); btnBOMShortage.Focus(); return false; } int locationId = locationBin[0]; int binId = locationBin[1]; var cacheData = PurchaseOrderReceiptBO.Instance.GetBinCacheData(locationId, binId); if ((from DataRow drow in _dataSource.Tables[0].Rows where drow.RowState != DataRowState.Deleted let bomList = PurchaseOrderReceiptBO.Instance.GetBOM(null, (int)drow[ITM_ProductTable.PRODUCTID_FLD], true) from drowBom in bomList let availableQuantity = GetAvailableQuantity(cacheData, locationId, binId, drowBom.ComponentID) let decBOMQty = drowBom.Quantity.GetValueOrDefault(0) let decOrderQty = Convert.ToDecimal(drow[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]) where availableQuantity < decOrderQty*decBOMQty select availableQuantity).Any()) { PCSMessageBox.Show(ErrorCode.MESSAGE_ISSUE_MATERIAL_TO_OUTSIDE, MessageBoxIcon.Exclamation); btnBOMShortage.Focus(); return false; } } if (_poMaster != null && _poMaster.PurchaseOrderMasterID > 0) _receiptMaster.PurchaseOrderMasterID = _poMaster.PurchaseOrderMasterID; if (_receiptMaster.PurchaseOrderMasterID == 0) _receiptMaster.PurchaseOrderMasterID = null; _receiptMaster.ReceiveNo = ReceiveNoText.Text.Trim(); // synchronyze data FormControlComponents.SynchronyGridData(dgrdData); if (_formMode == EnumAction.Add) _receiptMaster.PurchaseOrderReceiptID = PurchaseOrderReceiptBO.Instance.AddMasterReceipt(_receiptMaster, _dataSource, _ccnId, _currentDate); return true; } private static decimal GetAvailableQuantity(List<IV_BinCache> cacheData, int locationId, int binId, int componentId) { return cacheData.Where(b => b.LocationID == locationId && b.BinID == binId && b.ProductID == componentId). Sum(b => b.OHQuantity.GetValueOrDefault(0) - b.CommitQuantity.GetValueOrDefault(0)); } private int GetCurrentRow() { int intPurchaseOrderReceiptID = 0; try { int intProductID = (int)dgrdData[dgrdData.Row, PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD]; string strCondition = PO_PurchaseOrderDetailTable.PRODUCTID_FLD + "=" + intProductID; DataRow[] arrMatchedRows = _dataSource.Tables[0].Select(strCondition); if (arrMatchedRows.Length != 0) intPurchaseOrderReceiptID = (int)arrMatchedRows[0][PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTDETAILID_FLD]; } catch { PCSMessageBox.Show(ErrorCode.MSG_VIEWTABLE_SELECT_ROW, MessageBoxIcon.Information); } return intPurchaseOrderReceiptID; } #endregion #region PO Slip Report & BOM Shortate Report: Tuan TQ. /// <summary> /// Build and show PO Slip Report /// </summary> /// <Author> Tuan TQ, 10 Apr, 2006</Author> private void ShowPOSlipReport() { const string methodName = This + ".ShowPOSlipReport()"; try { const string APPLICATION_PATH = @"PCSMain\bin\Debug"; const string REPORT_LAYOUT = "PurchasingReceiptSlip.xml"; const string REPORT_COMPANY_FLD = "fldCompany"; const string RPT_TITLE_FLD = "fldTitle"; const string RPT_INVOICE_NO_FLD = "fldInvoiceNo"; Cursor = Cursors.WaitCursor; var printPreview = new C1PrintPreviewDialog(); var boReport = new C1PrintPreviewDialogBO(); DataTable dtbResult = boReport.GetPOSlipData(_receiptMaster.PurchaseOrderReceiptID); // Check data source if (dtbResult == null) { Cursor = Cursors.Default; return; } var reportBuilder = new ReportBuilder(); //Get actual application path string strReportPath = Application.StartupPath; int intIndex = strReportPath.IndexOf(APPLICATION_PATH); if (intIndex > -1) { strReportPath = strReportPath.Substring(0, intIndex); } if (strReportPath.Substring(strReportPath.Length - 1) == @"\") { strReportPath += Constants.REPORT_DEFINITION_STORE_LOCATION; } else { strReportPath += @"\" + Constants.REPORT_DEFINITION_STORE_LOCATION; } //Set datasource and lay-out path for reports reportBuilder.SourceDataTable = dtbResult; reportBuilder.ReportDefinitionFolder = strReportPath; reportBuilder.ReportLayoutFile = REPORT_LAYOUT; //check if layout is valid if (reportBuilder.AnalyseLayoutFile()) { reportBuilder.UseLayoutFile = true; } else { Cursor = Cursors.Default; PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error); return; } reportBuilder.MakeDataTableForRender(); // And show it in preview dialog reportBuilder.ReportViewer = printPreview.ReportViewer; reportBuilder.RenderReport(); //Header information get from system params reportBuilder.DrawPredefinedField(REPORT_COMPANY_FLD, SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME)); //Hide invoice caption if no invoice if (dtbResult.Rows.Count > 0) { reportBuilder.Report.Fields[RPT_INVOICE_NO_FLD].Visible = (dtbResult.Rows[0][PO_InvoiceMasterTable.INVOICENO_FLD].ToString().Trim() != string.Empty); } reportBuilder.RefreshReport(); //Print report try { printPreview.FormTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD).Text; } catch { } printPreview.Show(); } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, methodName, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error); } } finally { Cursor = Cursors.Default; } } private DataTable GetBOMShortageData() { const string RECEIVE_QUANTITY_FLD = "ReceiveQuantity"; int intProductionLineID = int.Parse(txtProductionLine.Tag.ToString()); var boDataReport = new C1PrintPreviewDialogBO(); // build the list of item in the grid var sbItemList = new StringBuilder(); string strLastID = string.Empty; foreach (DataRow drowData in _dataSource.Tables[0].Rows) { string strProductID = drowData[PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD].ToString(); if (strLastID == strProductID) continue; strLastID = strProductID; sbItemList.Append(strProductID).Append(","); } sbItemList.Append("0"); // avoid exception var dtbResult = boDataReport.GetPOBOMShortageData(_currentDate, intProductionLineID, _pONumber, sbItemList.ToString()); if (dtbResult == null) { return null; } //Loop and fill receive quantity foreach (DataRow drow in dtbResult.Rows) { //Find in data source (data in grid) string strCondition = PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD + "=" + drow[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString(); DataRow[] arrMatchedRows = _dataSource.Tables[0].Select(strCondition); if (arrMatchedRows.Length != 0) { drow[RECEIVE_QUANTITY_FLD] = arrMatchedRows[0][RECEIVE_QUANTITY_FLD]; } } return dtbResult; } /// <summary> /// Build and show PO BOM Shortage Report /// </summary> /// <Author> Tuan TQ, 06 Apr, 2006</Author> private void ShowBOMShortageReport() { const string APPLICATION_PATH = @"PCSMain\bin\Debug"; const string REPORT_LAYOUT = "POBOMShortageReport.xml"; const string RPT_PAGE_HEADER = "PageHeader"; const string REPORT_COMPANY_FLD = "fldCompany"; const string RPT_TITLE_FLD = "fldTitle"; const string RPT_PO_NO_FLD = "P0 No."; var printPreview = new C1PrintPreviewDialog(); DataTable dtbResult = GetBOMShortageData(); // Check data source if (dtbResult == null) { Cursor = Cursors.Default; return; } var reportBuilder = new ReportBuilder(); //Get actual application path string strReportPath = Application.StartupPath; int intIndex = strReportPath.IndexOf(APPLICATION_PATH); if (intIndex > -1) { strReportPath = strReportPath.Substring(0, intIndex); } if (strReportPath.Substring(strReportPath.Length - 1) == @"\") { strReportPath += Constants.REPORT_DEFINITION_STORE_LOCATION; } else { strReportPath += @"\" + Constants.REPORT_DEFINITION_STORE_LOCATION; } //Set datasource and lay-out path for reports reportBuilder.SourceDataTable = dtbResult; reportBuilder.ReportDefinitionFolder = strReportPath; reportBuilder.ReportLayoutFile = REPORT_LAYOUT; //check if layout is valid if (reportBuilder.AnalyseLayoutFile()) { reportBuilder.UseLayoutFile = true; } else { Cursor = Cursors.Default; PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error); return; } reportBuilder.MakeDataTableForRender(); // And show it in preview dialog reportBuilder.ReportViewer = printPreview.ReportViewer; reportBuilder.RenderReport(); //Header information get from system params reportBuilder.DrawPredefinedField(REPORT_COMPANY_FLD, SystemProperty.SytemParams.Get(SystemParam.COMPANY_FULL_NAME)); //Draw parameters var arrParamAndValue = new NameValueCollection(); arrParamAndValue.Add(RPT_PO_NO_FLD, _pONumber); arrParamAndValue.Add(lblProductionLine.Text, txtProductionLine.Text); arrParamAndValue.Add(lblVenderNo.Text, txtVendorNo.Text + " ( " + txtVendorName.Text + ")"); //Anchor the Parameter drawing canvas cordinate to the fldTitle Field fldTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD); double dblStartX = fldTitle.Left; double dblStartY = fldTitle.Top + 1.3 * fldTitle.RenderHeight; reportBuilder.GetSectionByName(RPT_PAGE_HEADER).CanGrow = true; reportBuilder.DrawParameters(reportBuilder.GetSectionByName(RPT_PAGE_HEADER), dblStartX, dblStartY, arrParamAndValue, reportBuilder.Report.Font.Size); reportBuilder.RefreshReport(); //Print report try { printPreview.FormTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD).Text; } catch { } printPreview.Show(); } #endregion } }
45.875264
193
0.490325
[ "Apache-2.0" ]
dungle/pcs
MAP2013/PCSProcurement/Purchase/PurchaseOrderReceipts.cs
151,895
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using AutoMapper; using Bogsi.DatingApp.API.Data.Repositories; using Bogsi.DatingApp.API.Dtos; using Bogsi.DatingApp.API.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; namespace Bogsi.DatingApp.API.Controllers { [Route("api/[controller]")] [ApiController] public class AuthController : ControllerBase { private readonly IAuthRepository _repository; private readonly IConfiguration _configuration; private readonly IMapper _mapper; public AuthController(IAuthRepository repository, IConfiguration configuration, IMapper mapper) { _mapper = mapper; _configuration = configuration; _repository = repository; } [HttpPost("register")] public async Task<IActionResult> Register([FromBody] UserForRegisterDto userDto) { userDto.Username = userDto.Username.ToLower(); if (await this._repository.UserExists(userDto.Username)) { return BadRequest("Username already exists."); } var userToCreate = this._mapper.Map<User>(userDto); var createdUser = await this._repository.Register(userToCreate, userDto.Password); var userToReturn = this._mapper.Map<UserForDetailDto>(createdUser); return CreatedAtRoute( "GetUser", new {Controller = "Users", Id = createdUser.Id}, userToReturn); } [HttpPost("login")] public async Task<IActionResult> Login([FromBody] UserForLoginDto userDto) { var userFromRepo = await _repository.Login(userDto.Username.ToLower(), userDto.Password); if (userFromRepo == null) { return Unauthorized(); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.Username) }; var key = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = credentials }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var user = this._mapper.Map<UserForListDto>(userFromRepo); return Ok(new { token = tokenHandler.WriteToken(token), user = user }); } } }
32.55102
103
0.627273
[ "MIT" ]
simonbogaerts/learn_dotnet_angular
Bogsi.DatingApp/Bogsi.DatingApp.API/Controllers/AuthController.cs
3,192
C#
using System; using WebAssembly; namespace WebAssembly.Browser.DOM { [Export("HTMLAppletElement", typeof(JSObject))] public sealed class HTMLAppletElement : HTMLElement, IHTMLAppletElement { internal HTMLAppletElement(JSObject handle) : base(handle) { } //public HTMLAppletElement () { } [Export("align")] public string Align { get => GetProperty<string>("align"); set => SetProperty<string>("align", value); } [Export("alt")] public string Alt { get => GetProperty<string>("alt"); set => SetProperty<string>("alt", value); } [Export("altHtml")] public string AltHtml { get => GetProperty<string>("altHtml"); set => SetProperty<string>("altHtml", value); } [Export("archive")] public string Archive { get => GetProperty<string>("archive"); set => SetProperty<string>("archive", value); } [Export("BaseHref")] public string BaseHref => GetProperty<string>("BaseHref"); [Export("border")] public string Border { get => GetProperty<string>("border"); set => SetProperty<string>("border", value); } [Export("code")] public string Code { get => GetProperty<string>("code"); set => SetProperty<string>("code", value); } [Export("codeBase")] public string CodeBase { get => GetProperty<string>("codeBase"); set => SetProperty<string>("codeBase", value); } [Export("codeType")] public string CodeType { get => GetProperty<string>("codeType"); set => SetProperty<string>("codeType", value); } [Export("contentDocument")] public Document ContentDocument => GetProperty<Document>("contentDocument"); [Export("data")] public string Data { get => GetProperty<string>("data"); set => SetProperty<string>("data", value); } [Export("declare")] public bool Declare { get => GetProperty<bool>("declare"); set => SetProperty<bool>("declare", value); } [Export("form")] public HTMLFormElement Form => GetProperty<HTMLFormElement>("form"); [Export("height")] public string Height { get => GetProperty<string>("height"); set => SetProperty<string>("height", value); } [Export("hspace")] public double Hspace { get => GetProperty<double>("hspace"); set => SetProperty<double>("hspace", value); } [Export("name")] public string Name { get => GetProperty<string>("name"); set => SetProperty<string>("name", value); } [Export("object")] public string Object { get => GetProperty<string>("object"); set => SetProperty<string>("object", value); } [Export("standby")] public string Standby { get => GetProperty<string>("standby"); set => SetProperty<string>("standby", value); } [Export("type")] public string Type { get => GetProperty<string>("type"); set => SetProperty<string>("type", value); } [Export("useMap")] public string UseMap { get => GetProperty<string>("useMap"); set => SetProperty<string>("useMap", value); } [Export("vspace")] public double Vspace { get => GetProperty<double>("vspace"); set => SetProperty<double>("vspace", value); } [Export("width")] public double Width { get => GetProperty<double>("width"); set => SetProperty<double>("width", value); } } }
56.576271
121
0.618334
[ "MIT" ]
kjpou1/wasm-dom
WebAssembly.Browser/DOM/HTMLAppletElement.cs
3,340
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Model\ComplexType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type WindowsDeviceAzureADAccount. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class WindowsDeviceAzureADAccount : WindowsDeviceAccount { /// <summary> /// Initializes a new instance of the <see cref="WindowsDeviceAzureADAccount"/> class. /// </summary> public WindowsDeviceAzureADAccount() { this.ODataType = "microsoft.graph.windowsDeviceAzureADAccount"; } /// <summary> /// Gets or sets userPrincipalName. /// Not yet documented /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "userPrincipalName", Required = Newtonsoft.Json.Required.Default)] public string UserPrincipalName { get; set; } } }
36.804878
153
0.605036
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Models/Generated/WindowsDeviceAzureADAccount.cs
1,509
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a stale rule in a security group. /// </summary> public partial class StaleIpPermission { private int? _fromPort; private string _ipProtocol; private List<string> _ipRanges = new List<string>(); private List<string> _prefixListIds = new List<string>(); private int? _toPort; private List<UserIdGroupPair> _userIdGroupPairs = new List<UserIdGroupPair>(); /// <summary> /// Gets and sets the property FromPort. /// <para> /// The start of the port range for the TCP and UDP protocols, or an ICMP type number. /// A value of <code>-1</code> indicates all ICMP types. /// </para> /// </summary> public int FromPort { get { return this._fromPort.GetValueOrDefault(); } set { this._fromPort = value; } } // Check to see if FromPort property is set internal bool IsSetFromPort() { return this._fromPort.HasValue; } /// <summary> /// Gets and sets the property IpProtocol. /// <para> /// The IP protocol name (for <code>tcp</code>, <code>udp</code>, and <code>icmp</code>) /// or number (see <a href="http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml">Protocol /// Numbers)</a>. /// </para> /// </summary> public string IpProtocol { get { return this._ipProtocol; } set { this._ipProtocol = value; } } // Check to see if IpProtocol property is set internal bool IsSetIpProtocol() { return this._ipProtocol != null; } /// <summary> /// Gets and sets the property IpRanges. /// <para> /// One or more IP ranges. Not applicable for stale security group rules. /// </para> /// </summary> public List<string> IpRanges { get { return this._ipRanges; } set { this._ipRanges = value; } } // Check to see if IpRanges property is set internal bool IsSetIpRanges() { return this._ipRanges != null && this._ipRanges.Count > 0; } /// <summary> /// Gets and sets the property PrefixListIds. /// <para> /// One or more prefix list IDs for an AWS service. Not applicable for stale security /// group rules. /// </para> /// </summary> public List<string> PrefixListIds { get { return this._prefixListIds; } set { this._prefixListIds = value; } } // Check to see if PrefixListIds property is set internal bool IsSetPrefixListIds() { return this._prefixListIds != null && this._prefixListIds.Count > 0; } /// <summary> /// Gets and sets the property ToPort. /// <para> /// The end of the port range for the TCP and UDP protocols, or an ICMP type number. A /// value of <code>-1</code> indicates all ICMP types. /// </para> /// </summary> public int ToPort { get { return this._toPort.GetValueOrDefault(); } set { this._toPort = value; } } // Check to see if ToPort property is set internal bool IsSetToPort() { return this._toPort.HasValue; } /// <summary> /// Gets and sets the property UserIdGroupPairs. /// <para> /// One or more security group pairs. Returns the ID of the referenced security group /// and VPC, and the ID and status of the VPC peering connection. /// </para> /// </summary> public List<UserIdGroupPair> UserIdGroupPairs { get { return this._userIdGroupPairs; } set { this._userIdGroupPairs = value; } } // Check to see if UserIdGroupPairs property is set internal bool IsSetUserIdGroupPairs() { return this._userIdGroupPairs != null && this._userIdGroupPairs.Count > 0; } } }
32.509554
117
0.578566
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/StaleIpPermission.cs
5,104
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #define coupled #define gated using System; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; using Microsoft.ML.Probabilistic.Collections; using Microsoft.ML.Probabilistic.Distributions; using Microsoft.ML.Probabilistic.Factors; using Microsoft.ML.Probabilistic.Math; using Microsoft.ML.Probabilistic.Models; using Microsoft.ML.Probabilistic.Utilities; using Microsoft.ML.Probabilistic.Algorithms; using Microsoft.ML.Probabilistic.Models.Attributes; using Microsoft.ML.Probabilistic.Compiler; namespace Microsoft.ML.Probabilistic.Tests { using Assert = Microsoft.ML.Probabilistic.Tests.AssertHelper; using BernoulliArray = DistributionStructArray<Bernoulli, bool>; using BernoulliArrayArray = DistributionRefArray<DistributionStructArray<Bernoulli, bool>, bool[]>; using DirichletArray = DistributionRefArray<Dirichlet, Vector>; using GaussianArray = DistributionStructArray<Gaussian, double>; /// <summary> /// Tests for the modelling API /// </summary> public class ModelTests { /// <summary> /// Tests that C# compiler errors produce a CompilationFailedException. /// </summary> [Fact] public void GeneratedSourceError() { double pTrue = 0.7; bool[] data = Util.ArrayInit(100, i => (Rand.Double() < pTrue)); Variable<double> p = Variable.Beta(1, 1).Named("p"); Range item = new Range(data.Length); VariableArray<bool> x = Variable.Array<bool>(item).Named("x"); x[item] = Variable.Bernoulli(p).ForEach(item); x.ObservedValue = data; InferenceEngine engine = new InferenceEngine(); engine.Compiler.WriteSourceFiles = true; engine.Compiler.UseExistingSourceFiles = true; engine.ModelName = "src_" + DateTime.Now.ToString("MM_dd_yy_HH_mm_ss_ff"); Directory.CreateDirectory(engine.Compiler.GeneratedSourceFolder); string sourcePath = Path.Combine(engine.Compiler.GeneratedSourceFolder, engine.ModelName + "_EP.cs"); File.WriteAllText(sourcePath, "invalid"); Assert.Throws<CompilationFailedException>(() => { engine.Infer<Beta>(p); }); } /// <summary> /// Test that hoisting works correctly for a jagged array with weakly-relevant outer dimension. /// </summary> [Fact] public void HoistingTest() { Range outer = new Range(2).Named("outer"); var innerSizes = Variable.Constant(new int[] { 3, 2 }, outer).Named("innerSizes"); Range inner = new Range(innerSizes[outer]).Named("inner"); var array = Variable.Array(Variable.Array<int>(inner), outer).Named("array"); using (Variable.ForEach(outer)) { using (var innerBlock = Variable.ForEach(inner)) { array[outer][inner] = Variable.DiscreteUniform(innerBlock.Index + 1); } } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(array)); } /// <summary> /// Test that SumWhere works when arguments are array elements. /// </summary> [Fact] public void SumWhereTest() { var outer = new Range(2); var inner = new Range(2); var x = Variable.Array<double>(inner); x[inner] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(inner); var z = Variable.Array(Variable.Array<bool>(inner), outer); z[outer][inner] = Variable.Bernoulli(.5).ForEach(outer, inner); var y = Variable.Array<double>(outer); y[outer] = Variable.SumWhere(z[outer], x); Variable.ConstrainEqualRandom(y[outer], new Gaussian(2.0, .5)); var ie = new InferenceEngine(new VariationalMessagePassing()); Console.WriteLine(ie.Infer(z)); } /// <summary> /// Test that variables observed to impossible values throw an exception. /// </summary> [Fact] public void ObserveDeterministicViolationError() { Assert.Throws<ConstraintViolatedException>(() => { var b = Variable.Observed(true).Named("b"); var c = (!b).Named("c"); c.ObservedValue = true; InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(c)); }); } /// <summary> /// Test that variables observed to impossible values throw an exception. /// </summary> [Fact] public void ObserveDeterministicViolationError2() { Assert.Throws<ConstraintViolatedException>(() => { var b = Variable.Observed(true).Named("b"); var c = (!b).Named("c"); Variable.ConstrainTrue(c); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(c)); }); } /// <summary> /// Test that constraints on observed variables are enforced in the generated code. /// </summary> [Fact] public void ObservedConstraintViolationError() { Assert.Throws<ConstraintViolatedException>(() => { var c = Variable.Constant(2).Named("c"); var t = Variable.Observed(1).Named("t"); Variable.ConstrainTrue(t > c); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(t)); }); } /// <summary> /// Test that the size of a range can refer to a constant. /// </summary> [Fact] [Trait("Category", "OpenBug")] public void RangeWithConstantSizeTest() { var counts = Variable.Constant(new int[] { 2, 3 }).Named("counts"); var range = new Range(counts[0]).Named("range"); var array = Variable.Array<bool>(range).Named("array"); array.ObservedValue = new bool[2]; InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(array)); } /// <summary> /// Test for a meaningful error message when a range depends on an inner range. /// </summary> [Fact] [Trait("Category", "OpenBug")] public void JaggedRangesError() { Assert.Throws<CompilationFailedException>(() => { var outer = new Range(2).Named("outer"); var counts = Variable.Observed(new int[] { 2, 3 }, outer).Named("counts"); var inner = new Range(counts[outer]).Named("inner"); var array = Variable.Array(Variable.Array<Vector>(outer), inner).Named("array"); array.ObservedValue = new Vector[2][]; var engine = new InferenceEngine(); Console.WriteLine(engine.Infer(array)); }); } /// <summary> /// Test that Variable.Factor contains the appropriate overloads /// </summary> [Fact] public void FactorFromMethodTest() { var y = Variable<double>.Factor<double, double>(Factor.GammaFromShapeAndRate, 1, 1); var x = Variable<bool>.Factor<double, double, double>(Factor.IsBetween, 1, 1, 1); } [Fact] public void LoopMerging2dTest() { Range r = new Range(2); Range r2 = new Range(2); var array = Variable.Array<bool>(r, r2).Named("array"); array[r, r2] = Variable.Bernoulli(0.1).ForEach(r, r2); using (var fb2 = Variable.ForEach(r2)) { using (var fb = Variable.ForEach(r)) { Variable.ConstrainTrue(array[fb2.Index, fb.Index]); } } InferenceEngine engine = new InferenceEngine(); var arrayActual = engine.Infer<IArray2D<Bernoulli>>(array); var arrayExpected = Bernoulli.PointMass(true); for (int i = 0; i < arrayActual.Count; i++) { Assert.True(arrayExpected.MaxDiff(arrayActual[i]) < 1e-10); } } [Fact] public void DuplicateRangeError() { Assert.Throws<CompilationFailedException>(() => { Range r = new Range(2).Named("r"); var kernel = Variable.Array(Variable.Array<bool>(r), r).Named("kernel"); //kernel[r][r] = Variable.Bernoulli(0.1).ForEach(r); kernel.ObservedValue = Util.ArrayInit(r.SizeAsInt, i => Util.ArrayInit(r.SizeAsInt, j => false)); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(kernel)); }); } // Fails with 'compiler limit exceeded' //[Fact] internal void LargeArrayConstantTest() { var array = Variable.Constant(Util.ArrayInit(10000000, i => false)); InferenceEngine engine = new InferenceEngine(); engine.Infer(array); } // This test should throw an exception explaining that r2 depends on r1 so it cannot be used with r1Clone. // Currently it fails when compiling the generated code. [Fact] [Trait("Category", "OpenBug")] public void CloneRangeWithBadInnerRangeError() { Assert.Throws<InvalidOperationException>(() => { var r1 = (new Range(1)).Named("r1"); var len = (Variable.Observed<int>(new[] { 1 }, r1)).Named("len"); var r2 = (new Range(len[r1])).Named("r2"); var v = (Variable.Array(Variable.Array<double>(r2), r1)).Named("var1"); v[r1][r2] = Variable.GaussianFromMeanAndPrecision(0.0, 1.0).ForEach(r1, r2); #if true var r1Clone = (r1.Clone()).Named("r1Clone"); var constraint = (Variable.Array(Variable.Array<double>(r2), r1Clone)).Named("constraint"); #else var constraint = (Variable.Array(Variable.Array<double>(r2), r1)).Named("constraint"); #endif constraint.ObservedValue = new[] { new[] { 1.0 } }; using (Variable.ForEach(r1)) { Variable.ConstrainEqual<double>(constraint[r1][r2], Variable.GaussianFromMeanAndPrecision(v[r1][r2], 1.0)); } var e = new InferenceEngine(new ExpectationPropagation()); e.Infer(v); }); } [Fact] public void RandomPointMassTest() { var v = Variable.Random(new PointMass<double>(42.0)).Named("v"); var x = Variable.GaussianFromMeanAndVariance(v, 1).Named("x"); Variable.ConstrainPositive(x); var engine = new InferenceEngine(); //engine.OptimiseForVariables = new List<IVariable>() { x, v }; Console.WriteLine(engine.Infer(x)); Console.WriteLine(engine.Infer(v)); } /// <summary> /// Message transform used to fail, saying that Gaussian is not assignable from double. /// </summary> [Fact] public void MixtureOfPointMassesTest() { const double SelectorProbTrue = 0.3; Variable<double> v = Variable.New<double>().Named("v"); Variable<bool> c = Variable.Bernoulli(SelectorProbTrue).Named("c"); using (Variable.If(c)) { v.SetTo(Variable.Random(Gaussian.PointMass(1))); } using (Variable.IfNot(c)) { v.SetTo(Variable.Random(Gaussian.PointMass(2))); } InferenceEngine engine = new InferenceEngine(); Gaussian vPosterior = engine.Infer<Gaussian>(v); } [Fact] public void NullConstantTest() { var evidence = Variable.Bernoulli(0.5).Named("evidence"); var block = Variable.If(evidence); Range item = new Range(0).Named("item"); var array = Variable.Array<bool>(item).Named("array"); array.ObservedValue = null; array.IsReadOnly = true; var c = Variable.AllTrue(array).Named("c"); var array2 = Variable.Array<bool>(item).Named("array2"); array2[item] = !array[item]; block.CloseBlock(); InferenceEngine engine = new InferenceEngine(); engine.OptimiseForVariables = new IVariable[] { evidence }; Console.WriteLine(engine.Infer(evidence)); } // scheduler duplicates work if KeepFresh=true internal void NevenaTest() { int dimX = 2; int numX = 1; int numN = 2; int numU = 2; int dimU = 2; // # variables var nX = Variable.Observed<int>(numX).Named("nX"); Range D = new Range(nX).Named("D"); var nU = Variable.Observed<int>(numU).Named("nU"); Range rG = new Range(nU).Named("rG"); // # observations var nN = Variable.Observed<int>(numN).Named("nN"); Range N = new Range(nN).Named("N"); // variable dimension var dX = Variable.Observed<int>(dimX).Named("dX"); Range rX = new Range(dX).Named("rX"); var dU = Variable.Observed<int>(dimU).Named("dU"); Range rU = new Range(dU).Named("rU"); // Latent variables // U latent var definition & init var U = Variable.Array(Variable.Array<int>(N), rG).Named("U"); U[rG][N] = Variable.DiscreteUniform(rU).ForEach(rG, N); // G structure var definition & init var G = Variable.Array<int>(D).Named("G"); G[D] = Variable.DiscreteUniform(rG).ForEach(D); // pT: prior for T var priorObs = new Dirichlet[numX][]; for (int i = 0; i < numX; i++) { priorObs[i] = new Dirichlet[dimU]; for (int j = 0; j < dimU; j++) priorObs[i][j] = Dirichlet.Symmetric(dimX, 1 / (double)dimU / (double)dimX); } var pT = Variable.Array(Variable.Array<Dirichlet>(rU), D).Named("pT"); pT.ObservedValue = priorObs; // T: cpt for X conditioned on U var T = Variable.Array(Variable.Array<Vector>(rU), D).Named("T"); // X: observed variables var X = Variable.Array(Variable.Array<int>(N), D).Named("X"); X.ObservedValue = Util.ArrayInit(numX, d => Util.ArrayInit(numN, n => n)); // Model using (Variable.ForEach(D)) { T[D][rU] = Variable<Vector>.Random(pT[D][rU]); T[D].SetValueRange(rX); X[D].SetValueRange(rX); using (Variable.Switch(G[D])) using (Variable.ForEach(N)) using (Variable.Switch(U[G[D]][N])) X[D][N] = Variable.Discrete(T[D][U[G[D]][N]]); } T.AddAttribute(new DivideMessages(false)); U.AddAttribute(new DivideMessages(false)); G.AddAttribute(new DivideMessages(false)); // Random init var initU = new Discrete[numU][]; for (int i = 0; i < numU; i++) { initU[i] = new Discrete[numN]; for (int j = 0; j < numN; j++) initU[i][j] = Discrete.PointMass(Rand.Int(dimU), dimU); } U.InitialiseTo(Distribution<int>.Array(initU)); var initG = new Discrete[numX]; for (int i = 0; i < numX; i++) initG[i] = Discrete.PointMass(Rand.Int(numU), numU); G.InitialiseTo(Distribution<int>.Array(initG)); // Inference // ie.Compiler.WriteSourceFiles = false; // ie.ModelName = "OneParent24"; var ie = new InferenceEngine(new ExpectationPropagation()); //ie.ShowSchedule = true; for (int iter = 1; iter < 100; iter++) { ie.NumberOfIterations = iter; var Gout = ie.Infer<Discrete[]>(G); for (int i = 0; i < numX; i++) { double[] probs = Gout[i].GetProbs().ToArray(); for (int j = 0; j < probs.Length; j++) Console.Write(" {0:F2}", probs[j]); } Console.WriteLine(); } } [Fact] [Trait("Category", "OpenBug")] public void DefinitionBeforeDeclarationError() { Assert.Throws<CompilationFailedException>(() => { var r = new Range(2); // execute the body var b1 = Variable.ForEach(r); var r2 = new Range(2); var item = Variable.Array<int>(r2); item[r2].SetTo(Variable.DiscreteUniform(3).ForEach(r2)); b1.CloseBlock(); // figure out item range and create the result array with correct ranges var rItem = item.Range; var proto = Variable.Array<int>(rItem); var x = Variable.Array<int>(proto, r).Named("x"); // assign the result var b2 = Variable.ForEach(r); x[r].SetTo(item); //x[r].SetTo(Variable.Copy(item)); b2.CloseBlock(); var ie = new InferenceEngine(); ie.ShowMsl = true; var D = ie.Infer(x); Console.WriteLine("x = {0}", D); }); } [Fact] public void NullVariableError() { Variable<double> x; try { x = Variable.Random<double, Gamma>(null); } catch (ArgumentNullException ex) { Console.WriteLine("Exception correctly thrown: " + ex.Message); // Exception correctly thrown return; } Assert.True(false, "Null variable was not detected."); } [Fact] public void NullVariableError2() { Variable<bool> x; try { x = Variable.Bernoulli(null); } catch (ArgumentNullException ex) { Console.WriteLine("Exception correctly thrown: " + ex.Message); // Exception correctly thrown return; } Assert.True(false, "Null variable was not detected."); } [Fact] public void NullVariableError3() { Variable<bool> x = null; try { Variable.ConstrainTrue(x); } catch (ArgumentNullException ex) { Console.WriteLine("Exception correctly thrown: " + ex.Message); // Exception correctly thrown return; } Assert.True(false, "Null variable was not detected."); } [Fact] [Trait("Category", "OpenBug")] public void GibbsArrayUsedTwiceInFactorTest() { ArrayUsedTwiceInFactor(new GibbsSampling()); } [Fact] public void ArrayUsedTwiceInFactorTest() { ArrayUsedTwiceInFactor(new ExpectationPropagation()); ArrayUsedTwiceInFactor(new VariationalMessagePassing()); } private void ArrayUsedTwiceInFactor(IAlgorithm algorithm) { Range item = new Range(2); VariableArray<double> x = Variable.Array<double>(item).Named("x"); x[item] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(item); var y = x[0] + x[1]; y.Name = "y"; InferenceEngine engine = new InferenceEngine(); engine.Algorithm = algorithm; double tolerance = 1e-8; Gaussian yActual = engine.Infer<Gaussian>(y); Gaussian yExpected = new Gaussian(0, 2); Console.WriteLine("y = {0} should be {1}", yActual, yExpected); Assert.True(yExpected.MaxDiff(yActual) < tolerance); } [Fact] public void VectorFromArrayError() { Assert.Throws<CompilationFailedException>(() => { Range r = new Range(3); var probs = Variable.Array<double>(r).Named("probs"); var b0 = Variable.Bernoulli(0.5).Named("b0"); using (Variable.If(b0)) { probs[0] = 1.0; } using (Variable.IfNot(b0)) { probs[0] = 0.0; } probs[1] = 1.0; probs[2] = 0.0; var probsVec = Variable.Vector(probs); var x = Variable.Discrete(probsVec); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(x)); }); } #if SUPPRESS_UNREACHABLE_CODE_WARNINGS #pragma warning disable 162 #endif internal void PoissonRegressionTest() { Rand.Restart(0); Vector wTrue = Vector.FromArray(10, -1); int n = 10; Vector[] xData = Util.ArrayInit(n, j => Vector.FromArray(Rand.Double(), Rand.Double())); int[] yData = Util.ArrayInit(n, j => Rand.Poisson(System.Math.Exp(wTrue.Inner(xData[j])))); double wVariance = 1; if (false) { // test on data from Matt Wand //TODO: change path using (StreamReader reader = new StreamReader(@"c:\users\minka\Desktop\TMinkaChk.csv")) { bool gotHeader = false; List<Vector> xList = new List<Vector>(); List<int> yList = new List<int>(); while (!reader.EndOfStream) { string line = reader.ReadLine(); if (!gotHeader) { gotHeader = true; continue; } string[] fields = line.Split(','); int yi = int.Parse(fields[0]); yList.Add(yi); Vector xi = Vector.FromArray(Util.ArrayInit(fields.Length, j => (j == 0) ? 1.0 : double.Parse(fields[j]))); xList.Add(xi); } n = yList.Count; yData = yList.ToArray(); xData = xList.ToArray(); } wVariance = 1000; } Range i = new Range(yData.Length).Named("i"); int dim = xData[0].Count; Variable<Vector> w = Variable.VectorGaussianFromMeanAndVariance(Vector.Zero(dim), PositiveDefiniteMatrix.IdentityScaledBy(dim, wVariance)).Named("w"); // must initialise to a reasonable variance since ExpOp explodes with large variance if (wVariance > 1) //w.InitialiseTo(new VectorGaussian(Vector.Zero(dim), PositiveDefiniteMatrix.Identity(dim))); w.InitialiseTo(new VectorGaussian(wTrue, PositiveDefiniteMatrix.Identity(dim))); VariableArray<Vector> x = Variable.Array<Vector>(i).Named("x"); x.ObservedValue = xData; VariableArray<int> y = Variable.Array<int>(i).Named("y"); y[i] = Variable.Poisson(Variable.Exp(Variable.InnerProduct(w, x[i]).Named("c")).Named("d")); y.ObservedValue = yData; InferenceEngine engine = new InferenceEngine(); Console.WriteLine("EP"); Console.WriteLine(engine.Infer<VectorGaussian>(w)); //engine.ShowFactorGraph = true; // VMP is very similar to EP in this model because there is only one stochastic variable engine.Algorithm = new VariationalMessagePassing(); engine.NumberOfIterations = 1000; ExpOp.UseRandomDamping = false; Console.WriteLine("VMP"); //engine.Compiler.GivePriorityTo(typeof(ExpOp_Laplace)); // modified Laplace is identical to EP with n=100 // works with either ExpectationPropagation (default) or VariationalMessagePassing //engine.Algorithm = new VariationalMessagePassing(); // EP result should be: // VectorGaussian(1.852 -0.6617, 0.01701 -0.01764) // -0.01764 0.03279 // VMP result should be: // VectorGaussian(1.852 -0.6617, 0.017 -0.01763) // -0.01763 0.03278 if (false) { for (int iter = 1; iter < 1000; iter++) { engine.NumberOfIterations = iter; Console.WriteLine(StringUtil.JoinColumns(iter.ToString(), ": ", engine.Infer<VectorGaussian>(w))); } } VectorGaussian wActual = engine.Infer<VectorGaussian>(w); Console.WriteLine(wActual); Console.WriteLine("wTrue = {0}", wTrue); } #if SUPPRESS_UNREACHABLE_CODE_WARNINGS #pragma warning restore 162 #endif // model provided by Jan Luts for testing internal void NormalZeroMixtureTest() { double sigsq_beta = 1e2; Variable<double> beta0 = Variable.GaussianFromMeanAndVariance(0.0, sigsq_beta).Named("beta0"); Variable<double> nu = Variable.GaussianFromMeanAndVariance(0.0, sigsq_beta).Named("nu"); double rho = 0.5; double A = 0.01; double B = 0.01; Variable<bool> gamma = Variable.Bernoulli(rho); Variable<double> beta1 = Variable.New<double>(); using (Variable.IfNot(gamma)) { beta1.SetTo(Variable<double>.Random(Gaussian.PointMass(0))); } using (Variable.If(gamma)) { //beta1.SetTo(Variable.GaussianFromMeanAndVariance(0.0, sigsq_beta)); beta1.SetTo(Variable.Copy(nu)); } Variable<double> tau = Variable.GammaFromShapeAndScale(A, 1 / B).Named("tau"); Range item = new Range(2); VariableArray<double> meany = Variable.Array<double>(item).Named("meany"); VariableArray<double> x = Variable.Array<double>(item).Named("x"); VariableArray<double> y = Variable.Array<double>(item).Named("y"); meany[item] = beta0 + beta1 * x[item]; y[item] = Variable.GaussianFromMeanAndPrecision(meany[item], tau); InferenceEngine engine = new InferenceEngine(); engine.Algorithm = new GibbsSampling(); //engine.Algorithm = new VariationalMessagePassing(); x.ObservedValue = new double[] { 1, 2 }; y.ObservedValue = new double[] { 1, 2 }; Console.WriteLine(engine.Infer(beta0)); Console.WriteLine(engine.Infer(beta1)); } [Fact] public void RatingModelTest() { double[][] ratings = new double[5][] { new double[] {4, 5, 5}, new double[] {4, 2, 1}, new double[] {3, 2, 4}, new double[] {4, 4}, new double[] {2, 1, 3, 5} }; int[][] items = new int[5][] { new int[] {0, 2, 3}, new int[] {0, 1, 2}, new int[] {0, 2, 3}, new int[] {0, 1}, new int[] {0, 1, 2, 3} }; Range Y = new Range(4).Named("Y"); Range K = new Range(2).Named("K"); var Means = Variable.Array<double>(Y, K).Named("Means"); Means[Y, K] = Variable.GaussianFromMeanAndVariance(5, 5).ForEach(Y, K); var Precs = Variable.Array<double>(Y, K).Named("Precs"); Precs[Y, K] = Variable.GammaFromShapeAndScale(1, 1).ForEach(Y, K); Range U = new Range(items.Length); VariableArray<int> RatedItemsCount = Variable.Observed(Util.ArrayInit(items.Length, i => items[i].Length), U); Range RatedItems = new Range(RatedItemsCount[U]); var Ratings = Variable.Array(Variable.Array<double>(RatedItems), U).Named("Ratings"); Ratings.ObservedValue = ratings; var Items = Variable.Array(Variable.Array<int>(RatedItems), U).Named("Items"); Items.ObservedValue = items; var Theta = Variable.Array<Vector>(U); // For each user using (Variable.ForEach(U)) { Theta[U] = Variable.DirichletUniform(K); // For each rating of that user using (Variable.ForEach(RatedItems)) { // Choose a topic var attitude = Variable.Discrete(Theta[U]).Named("attitude"); using (Variable.Switch(attitude)) { Ratings[U][RatedItems] = Variable.GaussianFromMeanAndPrecision(Means[Items[U][RatedItems], attitude], Precs[Items[U][RatedItems], attitude]); } } } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(Theta)); Console.WriteLine(engine.Infer(Means)); } [Fact] public void ArrayFromVectorTest() { var q = new Range(2).Named("q"); var n = new Range(3).Named("n"); var f = Variable.Array<Vector>(q).Named("f"); f[q] = Variable.VectorGaussianFromMeanAndVariance(Vector.Zero(n.SizeAsInt), PositiveDefiniteMatrix.Identity(n.SizeAsInt)).ForEach(q); var s = Variable.Array(Variable.Array<double>(n), q).Named("s"); s[q] = Variable.ArrayFromVector(f[q], n); } /// <summary> /// Has same problem as CloneRangeSwitchTest /// </summary> [Fact] [Trait("Category", "OpenBug")] public void CloneRangeSwitchTest2() { Range i = new Range(2).Named("i"); Range j = i.Clone().Named("j"); var n = Variable.Array<int>(i).Named("n"); Range vi = new Range(n[i]).Named("vi"); var A = Variable.Array<Vector>(i).Named("A"); var index = Variable.Array<int>(i).Named("index"); var bools = Variable.Array<bool>(i).Named("bools"); // Fails because the inner Dirichlet is implicitly indexed by Site_i using (Variable.ForEach(i)) { A[i] = Variable.DirichletUniform(vi); index[i] = Variable.Discrete(A[i]); bools[i] = Variable.Bernoulli(0.1); } n.ObservedValue = new int[] { 4, 3 }; var obs = Variable.Observed(new Vector[] { Vector.Constant(4, 0.25), Vector.Constant(3, 1.0 / 3) }, j); //using (Variable.ForEach(i)) { using (Variable.ForEach(j)) { using (Variable.Switch(index[j])) { Variable.ConstrainTrue(bools[j]); } } } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(A)); } /// <summary> /// This tests passes but it demonstrates a compiler problem that happens to be hidden by PruningTransform. /// index[j] has a different dimension for each j, but Hoisting creates a single variable to hold messages for all j. /// </summary> [Fact] [Trait("Category", "OpenBug")] public void CloneRangeSwitchTest() { Range i = new Range(2).Named("i"); Range j = i.Clone().Named("j"); var n = Variable.Array<int>(i).Named("n"); Range vi = new Range(n[i]).Named("vi"); var index = Variable.Array<int>(i).Named("index"); var bools = Variable.Array<bool>(i).Named("bools"); using (Variable.ForEach(i)) { index[i] = Variable.DiscreteUniform(vi); bools[i] = Variable.Bernoulli(0.1); } n.ObservedValue = new int[] { 4, 3 }; using (Variable.ForEach(j)) { using (Variable.Switch(index[j])) { Variable.ConstrainTrue(bools[j]); } } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(index)); } /// <summary> /// Test for a bug found in HoistingTransform /// </summary> [Fact] public void CloneDependentRangeTest() { Range game = new Range(3).Named("game"); VariableArray<int> teamsPerGame = Variable.Array<int>(game).Named("teamsPerGame"); teamsPerGame.ObservedValue = new[] { 2, 2, 3 }; Range team = new Range(teamsPerGame[game]).Named("team"); Range teamClone = team.Clone(); var b = Variable.Bernoulli(0.6); using (Variable.ForEach(game)) { using (ForEachBlock outer = Variable.ForEach(team)) { using (ForEachBlock inner = Variable.ForEach(teamClone)) { using (Variable.If(inner.Index != outer.Index)) { Variable.ConstrainEqualRandom(b, new Bernoulli(0.4)); } } } } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(b)); } internal void IntChainTest() { Range J = new Range(3).Named("J"); Range N = new Range(2).Named("N"); var objectNumber = Variable.Array<int>(N).Named("objectNumber"); var objectNumberPrior = Variable.Array<Vector>(N).Named("objectNumberPrior"); objectNumberPrior.ObservedValue = Util.ArrayInit(N.SizeAsInt, i => Vector.Constant(J.SizeAsInt, 1.0)); using (var f = Variable.ForEach(N)) { using (Variable.If(f.Index == 0)) { objectNumber[N] = Variable.Discrete(J, objectNumberPrior[N]).Named("objNumber"); // todo: make non-uniform } using (Variable.If(f.Index > 0)) { var b = objectNumber[f.Index - 1] > 0; using (Variable.If(b)) { objectNumber[N] = Variable.Discrete(J, objectNumberPrior[N]).Named("objNumber"); // todo: make non-uniform } using (Variable.IfNot(b)) { objectNumber[N] = Variable.Discrete(J, objectNumberPrior[N]).Named("objNumber"); // todo: make non-uniform } } } Variable.ConstrainEqualRandom(objectNumber[0], new Discrete(0.1, 0.2, 0.3)); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(objectNumber)); } [Fact] public void ModuloTest() { Range unwrappedValue = new Range(4).Named("unwrappedValue"); Variable<int> unwrapped = Variable.DiscreteUniform(unwrappedValue).Named("unwrapped"); Range wrappedValue = new Range(2).Named("wrappedValue"); Variable<int> wrapped = Variable.New<int>().Named("wrapped"); VariableArray<int> modulo2 = Variable.Observed(new int[] { 0, 1, 0, 1 }, unwrappedValue).Named("modulo2"); modulo2.SetValueRange(wrappedValue); using (Variable.Switch(unwrapped)) { wrapped.SetTo(modulo2[unwrapped]); } wrapped.ObservedValue = 1; InferenceEngine engine = new InferenceEngine(); engine.NumberOfIterations = 1; var unwrappedPost1 = engine.Infer(unwrapped); engine.NumberOfIterations = 2; Console.WriteLine(engine.Infer(unwrapped)); // test resetting inference engine.NumberOfIterations = 1; var unwrappedPost2 = engine.Infer<Diffable>(unwrapped); Assert.True(unwrappedPost2.MaxDiff(unwrappedPost1) < 1e-10); } [Fact] public void ModuloTest2() { Range unwrappedValue = new Range(4).Named("unwrappedValue"); Variable<int> unwrapped = Variable.DiscreteUniform(unwrappedValue).Named("unwrapped"); Variable<int> wrapped = Variable.New<int>().Named("wrapped"); Variable<bool> lessThan2 = (unwrapped < 2); using (Variable.If(lessThan2)) { wrapped.SetTo(Variable.Copy(unwrapped)); } using (Variable.IfNot(lessThan2)) { // integer subtraction is not implemented //wrapped.SetTo(unwrapped-2); wrapped.SetTo(unwrapped + (-2)); } wrapped.ObservedValue = 1; InferenceEngine engine = new InferenceEngine(); engine.NumberOfIterations = 1; var unwrappedPost1 = engine.Infer(unwrapped); engine.NumberOfIterations = 2; Console.WriteLine(engine.Infer(unwrapped)); // test resetting inference engine.NumberOfIterations = 1; var unwrappedPost2 = engine.Infer<Diffable>(unwrapped); Assert.True(unwrappedPost2.MaxDiff(unwrappedPost1) < 1e-10); } [Fact] public void DeepJaggedArrayTest() { int depth = 5; Range[] ranges = new Range[depth]; for (int i = 0; i < depth; i++) { ranges[i] = new Range(2); } var a = Variable<bool>.Array(ranges[0]); var b = Variable.Array(a, ranges[1]); var c = Variable.Array(b, ranges[2]); var d = Variable.Array(c, ranges[3]); var e = Variable.Array(d, ranges[4]); var f = Variable.Array(d, ranges[4]); e[ranges[4]][ranges[3]][ranges[2]][ranges[1]][ranges[0]] = Variable.Bernoulli(0.1).ForEach(ranges[4], ranges[3], ranges[2], ranges[1], ranges[0]); f[ranges[4]][ranges[3]][ranges[2]][ranges[1]][ranges[0]] = Variable.Bernoulli(0.1).ForEach(ranges[4]).ForEach(ranges[3]).ForEach(ranges[2]).ForEach(ranges[1]).ForEach(ranges[0]); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(e)); Console.WriteLine(engine.Infer(f)); } [Fact] public void DeepJaggedArrayTest2() { int depth = 5; Range[] ranges = new Range[depth]; for (int i = 0; i < depth; i++) { ranges[i] = new Range(2); } var a = Variable<bool>.Array(ranges[0]); var b = Variable.Array(a, ranges[1]); var c = Variable.Array(b, ranges[2]); var d = Variable.Array(c, ranges[3]); var e = Variable.Array(d, ranges[4]); Stack<ForEachBlock> blocks = new Stack<ForEachBlock>(); for (int i = depth - 1; i >= 0; i--) { blocks.Push(Variable.ForEach(ranges[i])); } e[ranges[4]][ranges[3]][ranges[2]][ranges[1]][ranges[0]] = Variable.Bernoulli(0.1); while (blocks.Count > 0) { blocks.Pop().CloseBlock(); } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(e)); } [Fact] public void ArrayUsedAtManyDepths() { double boolsPrior = 0.1; double boolsLike = 0.15; double boolsLike2 = 0.2; double boolsLike3 = 0.25; double boolsLike4 = 0.3; double boolsLike5 = 0.35; Range outer = new Range(2).Named("outer"); VariableArray<int> middleSizes = Variable.Constant(new int[] { 2, 3 }, outer).Named("middleSizes"); Range middle = new Range(middleSizes[outer]).Named("middle"); var innerSizes = Variable.Constant(new int[][] { new int[] { 1, 2 }, new int[] { 1, 2, 3 } }, outer, middle).Named("innerSizes"); Range inner = new Range(innerSizes[outer][middle]).Named("inner"); var bools = Variable.Array(Variable.Array(Variable.Array<bool>(inner), middle), outer).Named("bools"); using (Variable.ForEach(outer)) { using (Variable.ForEach(middle)) { using (Variable.ForEach(inner)) { bools[outer][middle][inner] = Variable.Bernoulli(boolsPrior); Variable.ConstrainEqualRandom(bools[outer][middle][inner], new Bernoulli(boolsLike)); } } } Variable.ConstrainEqualRandom(bools, (Sampleable<bool[][][]>)Distribution<bool>.Array(Util.ArrayInit(outer.SizeAsInt, i => Util.ArrayInit(middleSizes.ObservedValue[i], j => Util.ArrayInit( innerSizes.ObservedValue[i] [j], k => new Bernoulli(boolsLike2)))))); VariableArray<int> innerIndices = Variable.Constant(new int[] { 0 }).Named("innerIndices"); var bools_inner = Variable.Subarray(bools[0][0], innerIndices).Named("bools_inner"); Variable.ConstrainEqualRandom(bools_inner[innerIndices.Range], new Bernoulli(boolsLike3)); if (true) { VariableArray<int> middleIndices = Variable.Constant(new int[] { 0 }).Named("middleIndices"); middleIndices.SetValueRange(middle); var bools_middle = Variable.Subarray(bools[0], middleIndices).Named("bools_middle"); //Range inner2 = new Range(innerSizes[0][middleIndices[middleIndices.Range]]).Named("inner2"); Range inner2 = bools_middle[bools_middle.Range].Range; Variable.ConstrainEqualRandom(bools_middle[middleIndices.Range][inner2], new Bernoulli(boolsLike4)); } if (true) { VariableArray<int> outerIndices = Variable.Constant(new int[] { 0 }).Named("outerIndices"); outerIndices.SetValueRange(outer); var bools_outer = Variable.Subarray(bools, outerIndices).Named("bools_outer"); //Range middle3 = new Range(middleSizes[outerIndices[outerIndices.Range]]); //Range inner3 = new Range(innerSizes[outerIndices[outerIndices.Range]][middle3]); Range middle3 = bools_outer[bools_outer.Range].Range; Range inner3 = bools_outer[bools_outer.Range][middle3].Range; Variable.ConstrainEqualRandom(bools_outer[outerIndices.Range][middle3][inner3], new Bernoulli(boolsLike5)); } InferenceEngine engine = new InferenceEngine(); double z = boolsPrior * boolsLike * boolsLike2 + (1 - boolsPrior) * (1 - boolsLike) * (1 - boolsLike2); double boolsPost = boolsPrior * boolsLike * boolsLike2 / z; double z000 = boolsPrior * boolsLike * boolsLike2 * boolsLike3 + (1 - boolsPrior) * (1 - boolsLike) * (1 - boolsLike2) * (1 - boolsLike3); double boolsPost000 = boolsPrior * boolsLike * boolsLike2 * boolsLike3 / z000; //double z00 = boolsPrior*boolsLike Bernoulli[][][] boolsExpectedArray = new Bernoulli[outer.SizeAsInt][][]; for (int i = 0; i < boolsExpectedArray.Length; i++) { boolsExpectedArray[i] = new Bernoulli[middleSizes.ObservedValue[i]][]; for (int j = 0; j < boolsExpectedArray[i].Length; j++) { boolsExpectedArray[i][j] = new Bernoulli[innerSizes.ObservedValue[i][j]]; for (int k = 0; k < boolsExpectedArray[i][j].Length; k++) { double probTrue = boolsPrior * boolsLike * boolsLike2; double probFalse = (1 - boolsPrior) * (1 - boolsLike) * (1 - boolsLike2); if (i == 0) { probTrue *= boolsLike5; probFalse *= 1 - boolsLike5; if (j == 0) { probTrue *= boolsLike4; probFalse *= 1 - boolsLike4; if (k == 0) { probTrue *= boolsLike3; probFalse *= 1 - boolsLike3; } } } boolsExpectedArray[i][j][k] = new Bernoulli(probTrue / (probTrue + probFalse)); } } } IDistribution<bool[][][]> boolsExpected = Distribution<bool>.Array(boolsExpectedArray); object boolsActual = engine.Infer(bools); Console.WriteLine(StringUtil.JoinColumns("bools = ", boolsActual, " should be ", boolsExpected)); Assert.True(boolsExpected.MaxDiff(boolsActual) < 1e-10); } [Fact] public void ArrayUsedAtManyDepths2() { double boolsPrior = 0.1; double boolsLike = 0.15; double boolsLike2 = 0.2; double boolsLike3 = 0.25; double boolsLike4 = 0.3; double boolsLike5 = 0.35; Range outer = new Range(2).Named("outer"); VariableArray<int> middleSizes = Variable.Constant(new int[] { 2, 3 }, outer).Named("middleSizes"); Range middle = new Range(middleSizes[outer]).Named("middle"); var innerSizes = Variable.Constant(new int[][] { new int[] {1, 2}, new int[] {1, 2, 3} }, outer, middle).Named("innerSizes"); Range inner = new Range(innerSizes[outer][middle]).Named("inner"); var bools = Variable.Array(Variable.Array(Variable.Array<bool>(inner), middle), outer).Named("bools"); using (Variable.ForEach(outer)) { using (Variable.ForEach(middle)) { using (Variable.ForEach(inner)) { bools[outer][middle][inner] = Variable.Bernoulli(boolsPrior); Variable.ConstrainEqualRandom(bools[outer][middle][inner], new Bernoulli(boolsLike)); } } } Variable.ConstrainEqualRandom(bools, (Sampleable<bool[][][]>)Distribution<bool>.Array(Util.ArrayInit(outer.SizeAsInt, i => Util.ArrayInit(middleSizes.ObservedValue[i], j => Util.ArrayInit( innerSizes.ObservedValue[i] [j], k => new Bernoulli(boolsLike2)))))); VariableArray<int> innerIndices = Variable.Constant(new int[] { 0 }).Named("innerIndices"); var bools_inner = Variable.GetItems(bools[0][0], innerIndices).Named("bools_inner"); Variable.ConstrainEqualRandom(bools_inner[innerIndices.Range], new Bernoulli(boolsLike3)); if (true) { VariableArray<int> middleIndices = Variable.Constant(new int[] { 0 }).Named("middleIndices"); middleIndices.SetValueRange(middle); var bools_middle = Variable.GetItems(bools[0], middleIndices).Named("bools_middle"); //Range inner2 = new Range(innerSizes[0][middleIndices[middleIndices.Range]]).Named("inner2"); Range inner2 = bools_middle[bools_middle.Range].Range; Variable.ConstrainEqualRandom(bools_middle[middleIndices.Range][inner2], new Bernoulli(boolsLike4)); } if (true) { VariableArray<int> outerIndices = Variable.Constant(new int[] { 0 }).Named("outerIndices"); outerIndices.SetValueRange(outer); var bools_outer = Variable.GetItems(bools, outerIndices).Named("bools_outer"); //Range middle3 = new Range(middleSizes[outerIndices[outerIndices.Range]]); //Range inner3 = new Range(innerSizes[outerIndices[outerIndices.Range]][middle3]); Range middle3 = bools_outer[bools_outer.Range].Range; Range inner3 = bools_outer[bools_outer.Range][middle3].Range; Variable.ConstrainEqualRandom(bools_outer[outerIndices.Range][middle3][inner3], new Bernoulli(boolsLike5)); } InferenceEngine engine = new InferenceEngine(); double z = boolsPrior * boolsLike * boolsLike2 + (1 - boolsPrior) * (1 - boolsLike) * (1 - boolsLike2); double boolsPost = boolsPrior * boolsLike * boolsLike2 / z; double z000 = boolsPrior * boolsLike * boolsLike2 * boolsLike3 + (1 - boolsPrior) * (1 - boolsLike) * (1 - boolsLike2) * (1 - boolsLike3); double boolsPost000 = boolsPrior * boolsLike * boolsLike2 * boolsLike3 / z000; //double z00 = boolsPrior*boolsLike Bernoulli[][][] boolsExpectedArray = new Bernoulli[outer.SizeAsInt][][]; for (int i = 0; i < boolsExpectedArray.Length; i++) { boolsExpectedArray[i] = new Bernoulli[middleSizes.ObservedValue[i]][]; for (int j = 0; j < boolsExpectedArray[i].Length; j++) { boolsExpectedArray[i][j] = new Bernoulli[innerSizes.ObservedValue[i][j]]; for (int k = 0; k < boolsExpectedArray[i][j].Length; k++) { double probTrue = boolsPrior * boolsLike * boolsLike2; double probFalse = (1 - boolsPrior) * (1 - boolsLike) * (1 - boolsLike2); if (i == 0) { probTrue *= boolsLike5; probFalse *= 1 - boolsLike5; if (j == 0) { probTrue *= boolsLike4; probFalse *= 1 - boolsLike4; if (k == 0) { probTrue *= boolsLike3; probFalse *= 1 - boolsLike3; } } } boolsExpectedArray[i][j][k] = new Bernoulli(probTrue / (probTrue + probFalse)); } } } IDistribution<bool[][][]> boolsExpected = Distribution<bool>.Array(boolsExpectedArray); object boolsActual = engine.Infer(bools); Console.WriteLine(StringUtil.JoinColumns("bools = ", boolsActual, " should be ", boolsExpected)); Assert.True(boolsExpected.MaxDiff(boolsActual) < 1e-10); } [Fact] public void ArrayUsedAtManyDepths3() { var evidence = Variable.Bernoulli(0.5).Named("evidence"); var block = Variable.If(evidence); // Define the range over features var featureCount = Variable.Observed(3).Named("FeatureCount"); var featureRange = new Range(featureCount).Named("FeatureRange"); // Define the range over classes var classCount = Variable.Observed(2).Named("ClassCount"); var classRange = new Range(classCount).Named("ClassRange"); // Define the weights var Weights = Variable.Array(Variable.Array<double>(featureRange), classRange).Named("Weights"); // The distributions over weights Weights[classRange][featureRange] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(classRange, featureRange); // we apply two constraints, at different levels of indexing Variable.ConstrainEqualRandom(Weights[classRange][featureRange], new Gaussian(0, 1)); Variable.ConstrainEqualRandom(Weights[classRange], new GaussianArray(featureCount.ObservedValue, i => new Gaussian(0, 1))); block.CloseBlock(); Gaussian prior = new Gaussian(0, 1); double evExpected = prior.GetLogAverageOf(prior) + (prior * prior).GetLogAverageOf(prior); evExpected *= featureCount.ObservedValue * classCount.ObservedValue; var engine = new InferenceEngine(); double evActual = engine.Infer<Bernoulli>(evidence).LogOdds; Console.WriteLine("evidence = {0} should be {1}", evActual, evExpected); Assert.Equal(evExpected, evActual, 1e-8); } [Fact] public void JaviOliver() { int ObservedNode = 2; // = 1 (Node1 is observed) or = 2 (Node2 is observed) Range k = new Range(2).Named("k"); Range d = new Range(3).Named("d"); /////////////////////// // Node 1 /////////////////////// // Mixture component means var means1 = Variable.Array(Variable.Array<double>(d), k); means1[k][d] = Variable.GaussianFromMeanAndPrecision(2.0, 0.01).ForEach(k, d); VariableArray<Vector> vmeans1 = Variable.Array<Vector>(k).Named("vmeans1"); vmeans1[k] = Variable.Vector(means1[k]); // Mixture component precisions VariableArray<PositiveDefiniteMatrix> precs = Variable.Array<PositiveDefiniteMatrix>(k).Named("precs"); precs[k] = Variable.WishartFromShapeAndScale(100.0, PositiveDefiniteMatrix.IdentityScaledBy(d.SizeAsInt, 0.01)).ForEach(k); //precs.InitialiseTo(Distribution<PositiveDefiniteMatrix>.Array(Util.ArrayInit(k.SizeAsInt, i => Wishart.FromShapeAndScale(100.0, PositiveDefiniteMatrix.IdentityScaledBy(d.SizeAsInt, 0.01))))); // Mixture weights Variable<Vector> weights = Variable.Dirichlet(k, new double[] { 1, 1 }).Named("weights"); // Create a variable array which will hold the data Range n = new Range(100).Named("n"); VariableArray<Vector> data = Variable.Array<Vector>(n).Named("x"); // Create latent indicator variable for each data point VariableArray<int> z = Variable.Array<int>(n).Named("z"); // The mixture of Gaussians model using (Variable.ForEach(n)) { z[n] = Variable.Discrete(weights); using (Variable.Switch(z[n])) { data[n] = Variable.VectorGaussianFromMeanAndPrecision(vmeans1[z[n]], precs[z[n]]); } } // Attach some generated data if (ObservedNode == 1) data.ObservedValue = GenerateData(n.SizeAsInt); // Initialise messages randomly so as to break symmetry Discrete[] zinit = new Discrete[n.SizeAsInt]; for (int i = 0; i < zinit.Length; i++) zinit[i] = Discrete.PointMass(Rand.Int(k.SizeAsInt), k.SizeAsInt); z.InitialiseTo(Distribution<int>.Array(zinit)); ///////////////////////////// // Node 2 ///////////////////////////// // Mixture component means var means2 = Variable.Array(Variable.Array<double>(d), k).Named("mean2"); // Set the relation among variables // means2[k][d] = means1[k][d] + 1.0; // This works! means2[0][0] = means1[0][0] + 1.0; // This not... means2[0][1] = means1[0][1] + 1.0; means2[0][2] = means1[0][2] + 1.0; means2[1][0] = means1[1][0] + 1.0; means2[1][1] = means1[1][1] + 1.0; means2[1][2] = means1[1][2] + 1.0; VariableArray<Vector> vmeans2 = Variable.Array<Vector>(k).Named("vmeans2"); vmeans2[k] = Variable.Vector(means2[k]); // Mixture component precisions VariableArray<PositiveDefiniteMatrix> precs2 = Variable.Array<PositiveDefiniteMatrix>(k).Named("precs2"); precs2[k] = Variable.WishartFromShapeAndScale(100.0, PositiveDefiniteMatrix.IdentityScaledBy(d.SizeAsInt, 0.01)).ForEach(k); // Mixture weights Variable<Vector> weights2 = Variable.Dirichlet(k, new double[] { 1, 1 }).Named("weights2"); // Create a variable array which will hold the data Range n2 = new Range(100).Named("n2"); VariableArray<Vector> data2 = Variable.Array<Vector>(n2).Named("x2"); // Create latent indicator variable for each data point VariableArray<int> z2 = Variable.Array<int>(n2).Named("z2"); // The mixture of Gaussians model using (Variable.ForEach(n2)) { z2[n2] = Variable.Discrete(weights2); using (Variable.Switch(z2[n2])) { data2[n2] = Variable.VectorGaussianFromMeanAndPrecision(vmeans2[z2[n2]], precs2[z2[n2]]); } } // Attach some generated data if (ObservedNode == 2) data2.ObservedValue = GenerateData(n2.SizeAsInt); // Initialise messages randomly so as to break symmetry Discrete[] zinit2 = new Discrete[n2.SizeAsInt]; for (int i = 0; i < zinit2.Length; i++) zinit2[i] = Discrete.PointMass(Rand.Int(k.SizeAsInt), k.SizeAsInt); z2.InitialiseTo(Distribution<int>.Array(zinit2)); ///////////////////////////// // The inference InferenceEngine ie = new InferenceEngine(new VariationalMessagePassing()); ie.NumberOfIterations = 50; //ie.Compiler.GenerateInMemory = false; //ie.Compiler.WriteSourceFiles = true; //ie.Compiler.IncludeDebugInformation = true; Console.WriteLine("Dist over pi=" + ie.Infer(weights)); Console.WriteLine("Dist over means=\n" + ie.Infer(vmeans1)); Console.WriteLine("Dist over precs=\n" + ie.Infer(precs)); Console.WriteLine("Dist over pi=" + ie.Infer(weights2)); Console.WriteLine("Dist over means=\n" + ie.Infer(vmeans2)); Console.WriteLine("Dist over precs=\n" + ie.Infer(precs2)); IList<Wishart> precs2Actual = ie.Infer<IList<Wishart>>(precs2); double[] shapeExpected = new double[] { 116, 133 }; int j = (precs2Actual[0].Shape < precs2Actual[1].Shape) ? 0 : 1; Assert.True(System.Math.Abs(precs2Actual[0].Shape - shapeExpected[j]) < 1); Assert.True(System.Math.Abs(precs2Actual[1].Shape - shapeExpected[1 - j]) < 1); } /// <summary> /// Generates a data set from a particular true model. /// </summary> public Vector[] GenerateData(int nData) { Vector trueM1 = Vector.FromArray(2.0, 3.0, 4.0); Vector trueM2 = Vector.FromArray(7.0, 5.0, 5.0); double[] auxP1 = { 3.0, 0.2, 0.2, 0.2, 2.0, 0.3, 0.2, 0.3, 2.5 }; double[] auxP2 = { 2.0, 0.4, 0.4, 0.4, 1.5, 0.1, 0.4, 0.1, 2.0 }; Matrix MatrixP1 = new Matrix(3, 3, auxP1); Matrix MatrixP2 = new Matrix(3, 3, auxP2); PositiveDefiniteMatrix trueP1 = new PositiveDefiniteMatrix(MatrixP1); PositiveDefiniteMatrix trueP2 = new PositiveDefiniteMatrix(MatrixP2); VectorGaussian trueVG1 = VectorGaussian.FromMeanAndPrecision(trueM1, trueP1); VectorGaussian trueVG2 = VectorGaussian.FromMeanAndPrecision(trueM2, trueP2); double truePi = 0.6; Bernoulli trueB = new Bernoulli(truePi); // Restart the infer.NET random number generator Rand.Restart(12347); Vector[] data = new Vector[nData]; for (int j = 0; j < nData; j++) { bool bSamp = trueB.Sample(); data[j] = bSamp ? trueVG1.Sample() : trueVG2.Sample(); } return data; } [Fact] public void ConstantAndStochasticArrayElementsError() { try { Range item = new Range(2).Named("item"); var x = Variable.Array<double>(item).Named("x"); x[0] = Variable.Constant(0.0); x[1] = Variable.GaussianFromMeanAndPrecision(0, 1); InferenceEngine engine = new InferenceEngine(); object xActual = engine.Infer(x); IDistribution<double[]> xExpected = Distribution<double>.Array(new Gaussian[] { Gaussian.PointMass(0), Gaussian.FromMeanAndVariance(0, 1) }); Assert.True(xExpected.MaxDiff(xActual) < 1e-10); } catch (CompilationFailedException ex) { Console.WriteLine("Correctly threw exception: " + ex); } } [Fact] public void VariableUsedTwiceInFactorError() { Assert.Throws<CompilationFailedException>(() => { Variable<bool> x = Variable.Bernoulli(0.1).Named("x"); Variable<bool> y = x & x; InferenceEngine engine = new InferenceEngine(); Console.WriteLine("y = {0}", engine.Infer(y)); }); } [Fact] public void LiteralIndexingLocalConditionTest() { double bPrior = 0.2; double bLike = 0.6; Range i = new Range(2).Named("i"); Range j = new Range(2).Named("j"); VariableArray2D<bool> bools = Variable.Array<bool>(i, j).Named("bools"); bools[i, j] = Variable.Bernoulli(bPrior).ForEach(i, j); VariableArray2D<bool> condition = Variable.Array<bool>(i, j).Named("condition"); condition.ObservedValue = new bool[,] { { false, false }, { false, true } }; using (ForEachBlock fbi = Variable.ForEach(i)) { using (Variable.If(fbi.Index > 0)) { using (ForEachBlock fbj = Variable.ForEach(j)) { using (Variable.If(condition[fbi.Index, fbj.Index])) { Variable.ConstrainEqualRandom(bools[fbi.Index - 1, 1], new Bernoulli(bLike)); } } } } //Variable.ConstrainEqualRandom(bools[1, 1], new Bernoulli(bLike)); InferenceEngine engine = new InferenceEngine(); double sumT = bPrior * bLike + (1 - bPrior) * (1 - bLike); double Z = sumT; double bExpected01 = bPrior * (bLike) / Z; IDistribution<bool[,]> bExpected = Distribution<bool>.Array(new Bernoulli[,] { {new Bernoulli(bPrior), new Bernoulli(bExpected01)}, {new Bernoulli(bPrior), new Bernoulli(bPrior)}, }); object bActual = engine.Infer(bools); Console.WriteLine(StringUtil.JoinColumns("b = ", bActual, " should be ", bExpected)); Assert.True(bExpected.MaxDiff(bActual) < 1e-10); } [Fact] public void LiteralIndexingLocalConditionTest2() { double bPrior = 0.2; double bLike = 0.6; Range i = new Range(2).Named("i"); Range j = new Range(2).Named("j"); VariableArray2D<bool> bools = Variable.Array<bool>(i, j).Named("bools"); bools[i, j] = Variable.Bernoulli(bPrior).ForEach(i, j); VariableArray2D<bool> condition = Variable.Array<bool>(i, j).Named("condition"); condition.ObservedValue = new bool[,] { { false, false }, { false, true } }; using (ForEachBlock fbi = Variable.ForEach(i)) { using (ForEachBlock fbj = Variable.ForEach(j)) { using (Variable.If(fbi.Index > 0)) { using (Variable.If(condition[fbi.Index, fbj.Index])) { Variable.ConstrainEqualRandom(bools[fbi.Index - 1, 1], new Bernoulli(bLike)); } } } } //Variable.ConstrainEqualRandom(bools[1, 1], new Bernoulli(bLike)); InferenceEngine engine = new InferenceEngine(); double sumT = bPrior * bLike + (1 - bPrior) * (1 - bLike); double Z = sumT; double bExpected01 = bPrior * (bLike) / Z; IDistribution<bool[,]> bExpected = Distribution<bool>.Array(new Bernoulli[,] { {new Bernoulli(bPrior), new Bernoulli(bExpected01)}, {new Bernoulli(bPrior), new Bernoulli(bPrior)}, }); object bActual = engine.Infer(bools); Console.WriteLine(StringUtil.JoinColumns("b = ", bActual, " should be ", bExpected)); Assert.True(bExpected.MaxDiff(bActual) < 1e-10); } [Fact] public void ReplicationLocalConditionTest() { double bPrior = 0.2; double bLike = 0.6; Range i = new Range(2).Named("i"); Range j = new Range(3).Named("j"); Range i2 = new Range(2).Named("i2"); VariableArray<bool> bools = Variable.Array<bool>(i2).Named("bools"); bools[i2] = Variable.Bernoulli(bPrior).ForEach(i2); VariableArray2D<bool> condition = Variable.Array<bool>(i, j).Named("condition"); condition.ObservedValue = new bool[,] { { true, false, false }, { true, true, true } }; using (ForEachBlock fbi = Variable.ForEach(i)) { using (ForEachBlock fbj = Variable.ForEach(j)) { using (ForEachBlock fbi2 = Variable.ForEach(i2)) { using (Variable.If(fbi2.Index == 0)) { using (Variable.If(fbi.Index < 1)) { using (Variable.If(condition[fbi.Index, fbj.Index])) { Variable.ConstrainEqualRandom(bools[fbi.Index], new Bernoulli(bLike)); } } } } } } InferenceEngine engine = new InferenceEngine(); double sumT = bPrior * bLike + (1 - bPrior) * (1 - bLike); double Z = sumT; double bExpected01 = bPrior * (bLike) / Z; IDistribution<bool[]> bExpected = Distribution<bool>.Array(new Bernoulli[] { new Bernoulli(bExpected01), new Bernoulli(bPrior), }); object bActual = engine.Infer(bools); Console.WriteLine(StringUtil.JoinColumns("b = ", bActual, " should be ", bExpected)); Assert.True(bExpected.MaxDiff(bActual) < 1e-10); } internal void CardTest() { int numPlayers = 3; int numCards = 6; int cardsPerPlayer = numCards / numPlayers; Variable<bool>[][] hasCard = new Variable<bool>[numPlayers][]; for (int p = 0; p < numPlayers; p++) { hasCard[p] = new Variable<bool>[numCards]; for (int c = 0; c < numCards; c++) { hasCard[p][c] = Variable.Bernoulli(1.0 / numPlayers); } } // Each player has a fixed number of cards for (int p = 0; p < numPlayers; p++) { Variable<int> playerCards = Variable.DiscreteUniform(1); //Variable<int> playerCards = Variable.Observed<int>(0); for (int c = 0; c < numCards; c++) { Variable<int> nextSum = Variable.New<int>(); using (Variable.If(hasCard[p][c])) nextSum.SetTo(playerCards + 1); using (Variable.IfNot(hasCard[p][c])) nextSum.SetTo(playerCards + 0); playerCards = nextSum; } Variable.ConstrainTrue(playerCards == cardsPerPlayer); } // Every card is with one player for (int c = 0; c < numCards; c++) { Variable<int> numPlayersWithCard = Variable.DiscreteUniform(1); // Count how many players have this card for (int p = 0; p < numPlayers; p++) { Variable<int> nextSum = Variable.New<int>(); using (Variable.If(hasCard[p][c])) nextSum.SetTo(numPlayersWithCard + 1); using (Variable.IfNot(hasCard[p][c])) nextSum.SetTo(numPlayersWithCard + 0); numPlayersWithCard = nextSum; } // Must be equal to 1 Variable.ConstrainTrue(numPlayersWithCard == 1); } InferenceEngine ie = new InferenceEngine(); Console.WriteLine("Card distribution:\n{0}", ie.Infer(hasCard[0][0])); } internal void CardTest2() { int numPlayers = 3; int numCards = 6; int cardsPerPlayer = numCards / numPlayers; Variable<bool>[][] hasCard = new Variable<bool>[numPlayers][]; for (int p = 0; p < numPlayers; p++) { hasCard[p] = new Variable<bool>[numCards]; for (int c = 0; c < numCards; c++) { hasCard[p][c] = Variable.Bernoulli(1.0 / numPlayers); } } // Each player has a fixed number of cards for (int p = 0; p < numPlayers; p++) { Variable<int> playerCards = TrueCount(hasCard[p], cardsPerPlayer); Variable.ConstrainTrue(playerCards == cardsPerPlayer); } // Run! InferenceEngine ie = new InferenceEngine(); Console.WriteLine("Card distribution:\n{0}", ie.Infer(hasCard[0][0])); } public Variable<int> TrueCount(IList<Variable<bool>> bools, int maximumCount) { int threshold = maximumCount + 1; Range r = new Range(threshold + 1); Variable<int> count = Variable.Observed(0); count.SetValueRange(r); foreach (Variable<bool> b in bools) { Variable<int> nextCount = Variable.New<int>(); using (Variable.If(b)) { for (int i = 0; i <= threshold; i++) { using (Variable.Case(count, i)) { nextCount.SetTo(System.Math.Min(i + 1, threshold)); } } } using (Variable.IfNot(b)) { nextCount.SetTo(Variable.Copy(count)); } count = nextCount; } return count; } [Fact] public void CardTest3() { int numPlayers = 4; int numCards = 6; int cardsPerPlayer = numCards / numPlayers; Variable<bool>[][] hasCard = new Variable<bool>[numPlayers][]; for (int p = 0; p < numPlayers; p++) { hasCard[p] = new Variable<bool>[numCards]; for (int c = 0; c < numCards; c++) { hasCard[p][c] = Variable.Bernoulli(1.0 / numPlayers); } } // Each player has a fixed number of cards //Variable<int>[] playerCards = new Variable<int>[numPlayers]; for (int p = 0; p < numPlayers; p++) { Variable<int> playerCards = Variable.DiscreteUniform(1); // Count how many cards player p has for (int c = 0; c < numCards; c++) { playerCards.Name = "playerCards" + p + "_" + c; //playerCards.AddAttribute(new DivideMessages(false)); Variable<int> nextSum = Variable.New<int>(); var mustIncrement = hasCard[p][c] & playerCards < cardsPerPlayer + 1; using (Variable.If(mustIncrement)) nextSum.SetTo(playerCards + 1); using (Variable.IfNot(mustIncrement)) nextSum.SetTo(playerCards + 0); playerCards = nextSum; } playerCards.Name = "playerCards" + p; // Must be correct Variable.ConstrainEqualRandom(playerCards == cardsPerPlayer, new Bernoulli(0.9999)); } // Every card is with one player for (int c = 0; c < numCards; c++) { Variable<int> numPlayersWithCard = Variable.DiscreteUniform(1); // Count how many players have this card for (int p = 0; p < numPlayers; p++) { numPlayersWithCard.Name = "numPlayersWithCard" + c + "_" + p; //numPlayersWithCard.AddAttribute(new DivideMessages(false)); Variable<int> nextSum = Variable.New<int>(); var mustIncrement = hasCard[p][c] & numPlayersWithCard < 2; using (Variable.If(mustIncrement)) nextSum.SetTo(numPlayersWithCard + 1); using (Variable.IfNot(mustIncrement)) nextSum.SetTo(numPlayersWithCard + 0); numPlayersWithCard = nextSum; } numPlayersWithCard.Name = "numPlayersWithCard" + c; // Must be equal to 1 Variable.ConstrainEqualRandom(numPlayersWithCard == 1, new Bernoulli(0.9999)); } // Player 1 has card 1 hasCard[1][1].ObservedValue = true; InferenceEngine ie = new InferenceEngine(); // What is the probability of me having card 0? Console.WriteLine("Card distribution:\n{0}", ie.Infer(hasCard[0][0])); } [Fact] public void LocalIndexTest() { Range item = new Range(2).Named("item"); VariableArray<bool> x = Variable.Array<bool>(item).Named("x"); VariableArray<bool> y = Variable.Array<bool>(item).Named("y"); using (Variable.ForEach(item)) { x[item] = Variable.Bernoulli(0.1); Variable<int> index = Variable.Constant(0) + Variable.Constant(0); index.Name = "index"; y[item] = !x[index]; } InferenceEngine engine = new InferenceEngine(); object yActual = engine.Infer(y); IDistribution<bool[]> yExpected = Distribution<bool>.Array(new Bernoulli[] { new Bernoulli(0.9), new Bernoulli(0.9) }); Console.WriteLine(StringUtil.JoinColumns("y = ", yActual, " should be ", yExpected)); Assert.True(yExpected.MaxDiff(yActual) < 1e-10); } [Fact] public void BuildTwiceTest() { Variable<double> const1 = Variable.Constant(1.0).Named("const1"); Variable<double> const2 = Variable.Constant(1.0).Named("const2"); Variable<double> zero = Variable.Constant(0.0).Named("zero"); Variable<double> x = Variable.GaussianFromMeanAndPrecision(zero, const1).Named("x"); //Variable<double> y = Variable.GaussianFromMeanAndPrecision(x, const2).Named("y"); InferenceEngine engine = new InferenceEngine(); Gaussian xPost = engine.Infer<Gaussian>(x); Variable<double> z = Variable.GaussianFromMeanAndPrecision(zero, const2).Named("z"); Variable.ConstrainPositive(z - x); InferenceEngine engine2 = new InferenceEngine(); Gaussian xPost2 = engine2.Infer<Gaussian>(z); } [Fact] public void CloneRangeFibonacciTest() { int n = 10; Range row = new Range(n); VariableArray<double> x = Variable.Array<double>(row).Named("x"); x[row] = Variable.GaussianFromMeanAndPrecision(0, 0).ForEach(row); Variable.ConstrainEqual(x[0], 1); Variable.ConstrainEqual(x[1], 1); using (ForEachBlock fb1 = Variable.ForEach(row)) { using (ForEachBlock fb2 = Variable.ForEach(row.Clone())) { using (ForEachBlock fb3 = Variable.ForEach(row.Clone())) { using (Variable.If((fb2.Index == fb1.Index + 1) & (fb3.Index == fb2.Index + 1))) { Variable.ConstrainEqual(x[fb3.Index], x[fb1.Index] + x[fb2.Index]); } } } } InferenceEngine engine = new InferenceEngine(); IList<Gaussian> xActual = engine.Infer<IList<Gaussian>>(x); Console.WriteLine(xActual); Assert.True(xActual[9].Point == 55); } // This test only works if you disable the check for duplicate definitions. //[Fact] internal void CloneRangeFibonacciTest2() { int n = 10; Range row = new Range(n); VariableArray<double> x = Variable.Array<double>(row).Named("x"); x[0] = Variable.Constant(1.0); x[1] = Variable.Constant(1.0); using (ForEachBlock fb1 = Variable.ForEach(row)) { using (ForEachBlock fb2 = Variable.ForEach(row.Clone())) { using (ForEachBlock fb3 = Variable.ForEach(row.Clone())) { using (Variable.If((fb2.Index == fb1.Index + 1) & (fb3.Index == fb2.Index + 1))) { x[fb3.Index] = x[fb1.Index] + x[fb2.Index]; } } } } InferenceEngine engine = new InferenceEngine(); double[] xActual = engine.Infer<double[]>(x); Console.WriteLine(StringUtil.ArrayToString(xActual)); Assert.True(xActual[9] == 55); } [Fact] public void CloneRangeBlockModelTest() { CloneRangeBlockModel(true); CloneRangeBlockModel(false); } // TODO: Lack of optimization: z2_cond_z1_B is not being substituted by CopyProp because the rhs is a different array type (Discrete[]) private void CloneRangeBlockModel(bool initialise) { // Observed interaction matrix var YObs = new bool[5][]; bool useDataSet1 = true; if (useDataSet1) { YObs[0] = new bool[] { false, true, true, false, false }; YObs[1] = new bool[] { true, false, true, false, false }; YObs[2] = new bool[] { true, true, false, false, false }; YObs[3] = new bool[] { false, false, false, false, true }; YObs[4] = new bool[] { false, false, false, true, false }; } else { YObs[0] = new bool[] { true, true, true, false, false }; YObs[1] = new bool[] { true, true, true, false, false }; YObs[2] = new bool[] { true, true, true, false, false }; YObs[3] = new bool[] { false, false, false, true, true }; YObs[4] = new bool[] { false, false, false, true, true }; } int K = 2; // Number of blocks int N = YObs.Length; // Number of nodes // Ranges Range p = new Range(N).Named("p"); // Range for initiator Range q = p.Clone().Named("q"); // Range for receiver Range kp = new Range(K).Named("kp"); // Range for initiator group membership Range kq = kp.Clone().Named("kq"); // Range for receiver group membership // The model var Y = Variable.Array(Variable.Array<bool>(q), p); // Interaction matrix var pi = Variable.Array<Vector>(p).Named("pi"); // Block-membership probability vector pi[p] = Variable.DirichletUniform(kp).ForEach(p); var B = Variable.Array<double>(kp, kq).Named("B"); // Link probability matrix B[kp, kq] = Variable.Beta(1, 1).ForEach(kp, kq); using (Variable.ForEach(p)) { using (Variable.ForEach(q)) { var z1 = Variable.Discrete(pi[p]).Named("z1"); // Draw initiator membership indicator var z2 = Variable.Discrete(pi[q]).Named("z2"); // Draw receiver membership indicator z2.SetValueRange(kq); using (Variable.Switch(z1)) using (Variable.Switch(z2)) Y[p][q] = Variable.Bernoulli(B[z1, z2]); // Sample interaction value } } if (initialise) { // Initialise to break symmetry Rand.Restart(12347); var piInit = new Dirichlet[N]; for (int i = 0; i < N; i++) { Vector v = Vector.Zero(K); for (int j = 0; j < K; j++) v[j] = 1 + Rand.Double(); piInit[i] = new Dirichlet(v); } pi.InitialiseTo((DirichletArray)Distribution<Vector>.Array(piInit)); } //B.InitialiseTo((DistributionArray2D<Beta,double>)Distribution<double>.Array(new Beta[,] { { new Beta(10,1), new Beta(1,10) }, { new Beta(1,10), new Beta(10,1) } })); // Hook up the data Y.ObservedValue = YObs; // Infer var engine = new InferenceEngine(new VariationalMessagePassing()); var posteriorPi = engine.Infer<IList<Dirichlet>>(pi); var posteriorB = engine.Infer(B); var piExpected = Distribution<Vector>.Array(new Dirichlet[] { new Dirichlet(6.334, 5.666), new Dirichlet(6.333, 5.667), new Dirichlet(6.345, 5.655), new Dirichlet(4.291, 7.709), new Dirichlet(4.302, 7.698) }); Console.WriteLine(StringUtil.JoinColumns("pi = ", posteriorPi, " should be ", piExpected)); Console.WriteLine(StringUtil.JoinColumns("B = ", posteriorB)); int indexOfMax1 = posteriorPi[0].PseudoCount.IndexOfMaximum(); Assert.Equal(posteriorPi[1].PseudoCount.IndexOfMaximum(), indexOfMax1); Assert.Equal(posteriorPi[2].PseudoCount.IndexOfMaximum(), indexOfMax1); int indexOfMax2 = posteriorPi[3].PseudoCount.IndexOfMaximum(); Assert.Equal(posteriorPi[4].PseudoCount.IndexOfMaximum(), indexOfMax2); } [Fact] public void CopyLocalVariable() { Range item = new Range(2).Named("item"); VariableArray<bool> array = Variable.Array<bool>(item).Named("array"); using (Variable.ForEach(item)) { Variable<bool> b = Variable.Bernoulli(0.1).Named("b"); Variable<bool> c = Variable.Copy(b).Named("c"); array[item] = Variable.Copy(c); } InferenceEngine engine = new InferenceEngine(); IDistribution<bool[]> arrayExpected = Distribution<bool>.Array(new Bernoulli[] { new Bernoulli(0.1), new Bernoulli(0.1) }); object arrayActual = engine.Infer(array); Console.WriteLine(StringUtil.JoinColumns("array = ", arrayActual, " should be ", arrayExpected)); Assert.True(arrayExpected.MaxDiff(arrayActual) < 1e-10); } [Fact] public void JaggedRandomTest() { JaggedRandom(new ExpectationPropagation()); JaggedRandom(new VariationalMessagePassing()); } [Fact] public void GibbsJaggedRandomTest() { JaggedRandom(new GibbsSampling()); } private void JaggedRandom(IAlgorithm algorithm) { Range outer = new Range(2).Named("outer"); Range inner = new Range(1).Named("inner"); var priors = Variable.Array<BernoulliArray>(outer).Named("priors"); priors.ObservedValue = Util.ArrayInit(outer.SizeAsInt, i => new BernoulliArray(inner.SizeAsInt, j => new Bernoulli(0.1 * (j + i + 1)))); var array = Variable.Array(Variable.Array<bool>(inner), outer).Named("array"); array[outer].SetTo(Variable<bool[]>.Random(priors[outer])); InferenceEngine engine = new InferenceEngine(algorithm); object actual = engine.Infer(array); BernoulliArrayArray expected = new BernoulliArrayArray(priors.ObservedValue); Console.WriteLine(StringUtil.JoinColumns("array = ", actual, " should be ", expected)); Assert.True(expected.MaxDiff(actual) < 1e-10); } [Fact] public void RangeUsedAsArgumentInsideForEach() { Range item = new Range(2).Named("item"); VariableArray<int> x = Variable.Array<int>(item).Named("x"); using (Variable.ForEach(item)) { x[item] = Variable.DiscreteUniform(item); } InferenceEngine engine = new InferenceEngine(); Console.WriteLine("x = {0}", engine.Infer(x)); } [Fact] public void FriendGraph() { Range uRange = new Range(1).Named("u"); ; Range fVaryRange = new Range(1).Named("fVary"); Range sRange = new Range(1).Named("s"); Range eRange = new Range(1).Named("e"); Range cRange = new Range(1).Named("c"); var edgeLabel2 = Variable.Array<int>(eRange).Named("edgeLabel2"); edgeLabel2[eRange] = Variable.Discrete(1.0).ForEach(eRange); var cArray = Variable.Array<bool>(cRange).Named("cArray"); cArray[cRange] = Variable.Bernoulli(0.3).ForEach(cRange); var edgeIndexData = Variable.Constant(new int[][] { new int[] { 0 } }, uRange, fVaryRange).Named("edgeIndexData"); var f = Variable.Array(Variable.Array<int>(sRange), uRange).Named("f"); var psi = Variable.Array<Vector>(uRange).Named("psi"); psi.ObservedValue = new Vector[] { Vector.FromArray(1.0) }; using (Variable.ForEach(uRange)) { using (Variable.ForEach(sRange)) { f[uRange][sRange] = Variable.Discrete(psi[uRange]).Attrib(new ValueRange(fVaryRange)); var currentFriend = f[uRange][sRange]; using (Variable.Switch(currentFriend)) { var currentEdge = (edgeIndexData[uRange][currentFriend]).Attrib(new ValueRange(eRange)); using (Variable.Switch(currentEdge)) { var currentLabel = ((edgeLabel2[currentEdge])).Attrib(new ValueRange(cRange)); using (Variable.Switch(currentLabel)) { Variable.ConstrainTrue(cArray[currentLabel]); } } } } } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(edgeLabel2)); } [Fact] public void SetToError() { Assert.Throws<InvalidOperationException>(() => { Variable<bool> temp = Variable.Bernoulli(0.1).Named("temp"); Variable<bool> x = Variable.New<bool>().Named("x"); x.SetTo(temp); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(temp)); // illegal }); } [Fact] public void SetToConstraintError() { Assert.Throws<InvalidOperationException>(() => { Variable<bool> temp = Variable.Bernoulli(0.1).Named("temp"); Variable.ConstrainTrue(temp); Variable<bool> x = Variable.New<bool>().Named("x"); x.SetTo(temp); // illegal InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(x)); }); } [Fact] public void SetToConstraintError2() { Assert.Throws<InvalidOperationException>(() => { var R = new Range(2); var array = Variable.Array<double>(R); using (Variable.ForEach(R)) { var x = Variable.GaussianFromMeanAndPrecision(0.0, 1.0); Variable.ConstrainTrue(x > 0); array[R] = x; } var ie = new InferenceEngine(); // ie.ShowFactorGraph = true; // ie.ShowMsl = true; Console.WriteLine("array = " + ie.Infer(array)); }); } [Fact] public void SetToError2() { Assert.Throws<InvalidOperationException>(() => { Variable<bool> a = Variable.Bernoulli(1).Named("a"); Variable<bool> x = Variable.New<bool>().Named("x"); Variable<bool> temp = Variable.New<bool>().Named("temp"); using (Variable.If(a)) { temp.SetTo(Variable.Bernoulli(0.1)); x.SetTo(temp); } using (Variable.IfNot(a)) { x.SetTo(Variable.Bernoulli(0.2)); } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(temp)); // illegal }); } [Fact] public void SetToTest() { Variable<bool> temp = Variable.Bernoulli(0.5); Variable<bool> b = Variable.Bernoulli(0.1); Variable<bool> x = Variable.New<bool>(); Variable.ConstrainTrue(temp); // this should not fail since Variable.Copy is inserted automatically using (Variable.If(b)) x.SetTo(temp); using (Variable.IfNot(b)) x.SetTo(!temp); var engine = new InferenceEngine(); Console.WriteLine(engine.Infer(temp)); } [Fact] public void ImplicitForEachTest() { Range r = new Range(2); var v = Variable.Constant(true); var va = Variable.Array<bool>(r); using (Variable.ForEach(r)) { va[r] = v; } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(va)); } [Fact] public void DiscreteVariableSizeError2() { Assert.Throws<InvalidOperationException>(() => { Variable<int> size = Variable.New<int>().Named("size"); Range item = new Range(size).Named("item"); Variable<int> index = Variable.Discrete(item, 0.2, 0.8).Named("index"); size.ObservedValue = 3; InferenceEngine engine = new InferenceEngine(); Discrete indexActual = engine.Infer<Discrete>(index); }); } [Fact] public void DiscreteVariableSizeError() { Assert.Throws<ArgumentException>(() => { Variable<int> index = Variable.Discrete(new Range(3), 0.2, 0.8).Named("index"); InferenceEngine engine = new InferenceEngine(); Discrete indexActual = engine.Infer<Discrete>(index); }); } [Fact] public void DiscreteValueRangeError() { Assert.Throws<ArgumentException>(() => { Range i = new Range(2); Variable<Vector> probs = Variable.Dirichlet(i, new double[] { 1, 1 }).Named("probs"); Range j = new Range(2); Variable<int> index = Variable.Discrete(j, probs).Named("index"); InferenceEngine engine = new InferenceEngine(); Discrete indexActual = engine.Infer<Discrete>(index); }); } [Fact] public void DiscreteVariableSizeTest() { Variable<int> size = Variable.New<int>().Named("size"); Range item = new Range(size).Named("item"); Variable<int> index = Variable.DiscreteUniform(item).Named("index"); size.ObservedValue = 3; InferenceEngine engine = new InferenceEngine(); Discrete indexActual = engine.Infer<Discrete>(index); Discrete indexExpected = Discrete.Uniform(size.ObservedValue); Console.WriteLine("index = {0} should be {1}", indexActual, indexExpected); Assert.True(indexExpected.MaxDiff(indexActual) < 1e-10); } [Fact] public void DiscreteSizeError() { Assert.Throws<ArgumentException>(() => { Variable<int> index = Variable.Discrete(6).Named("index"); InferenceEngine engine = new InferenceEngine(); Discrete indexActual = engine.Infer<Discrete>(index); Discrete indexExpected = Discrete.Uniform(6); Console.WriteLine("index = {0} should be {1}", indexActual, indexExpected); Assert.True(indexExpected.MaxDiff(indexActual) < 1e-10); }); } [Fact] public void DirichletVariableSizeTest() { Variable<int> size = Variable.New<int>().Named("size"); Range item = new Range(size).Named("item"); Variable<Vector> probs = Variable.DirichletUniform(item).Named("probs"); size.ObservedValue = 3; InferenceEngine engine = new InferenceEngine(); Dirichlet probsActual = engine.Infer<Dirichlet>(probs); Dirichlet probsExpected = Dirichlet.Uniform(size.ObservedValue); Console.WriteLine("probs = {0} should be {1}", probsActual, probsExpected); Assert.True(probsExpected.MaxDiff(probsActual) < 1e-10); } [Fact] public void SetToArrayError() { Assert.Throws<ArgumentException>(() => { Range item = new Range(1).Named("item"); VariableArray<double> probs = Variable.Constant(new double[] { 0.3 }, item).Named("probs"); Variable<bool> x = Variable.New<bool>().Named("x"); x.SetTo(Variable.Bernoulli(probs[item])); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(x)); }); } [Fact] public void JaggedForEachBlockError() { Assert.Throws<InvalidOperationException>(() => { Range outer = new Range(3).Named("outer"); VariableArray<int> innerSizes = Variable.Constant(new int[] { 1, 2, 3 }, outer).Named("innerSizes"); Range inner = new Range(innerSizes[outer]).Named("inner"); var bools = Variable.Array<bool>(Variable.Array<bool>(inner), outer).Named("bools"); using (Variable.ForEach(inner)) { using (Variable.ForEach(outer)) { bools[outer][inner] = Variable.Bernoulli(0.3); } } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(bools)); }); } [Fact] public void JaggedForEachBlockError2() { Assert.Throws<InvalidOperationException>(() => { Range outer = new Range(3).Named("outer"); VariableArray<int> innerSizes = Variable.Constant(new int[] { 1, 2, 3 }, outer).Named("innerSizes"); Range inner = new Range(innerSizes[outer]).Named("inner"); var bools = Variable.Array<bool>(Variable.Array<bool>(inner), outer).Named("bools"); using (Variable.ForEach(inner)) { bools[outer][inner] = Variable.Bernoulli(0.3).ForEach(outer); } InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(bools)); }); } [Fact] public void JaggedForEachError() { Assert.Throws<InvalidOperationException>(() => { Range outer = new Range(3).Named("outer"); VariableArray<int> innerSizes = Variable.Constant(new int[] { 1, 2, 3 }, outer).Named("innerSizes"); Range inner = new Range(innerSizes[outer]).Named("inner"); var bools = Variable.Array<bool>(inner).Named("bools"); bools[inner] = Variable.Bernoulli(0.3).ForEach(inner); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(bools)); }); } [Fact] public void RandomToGivenToConstantToGivenToRandom() { Variable<double> prob = Variable.Beta(2, 1).Named("prob"); Variable<bool> b = Variable.Bernoulli(prob).Named("b"); InferenceEngine engine = new InferenceEngine(); engine.ShowMsl = true; Bernoulli bActual = engine.Infer<Bernoulli>(b); Bernoulli bExpected = new Bernoulli(2.0 / 3); Assert.True(bExpected.MaxDiff(bActual) < 1e-10); prob.ObservedValue = 0.4; bActual = engine.Infer<Bernoulli>(b); bExpected = new Bernoulli(prob.ObservedValue); Assert.True(bExpected.MaxDiff(bActual) < 1e-10); prob.IsReadOnly = true; bActual = engine.Infer<Bernoulli>(b); bExpected = new Bernoulli(prob.ObservedValue); Assert.True(bExpected.MaxDiff(bActual) < 1e-10); prob.IsReadOnly = false; prob.ObservedValue = 0.3; bActual = engine.Infer<Bernoulli>(b); bExpected = new Bernoulli(prob.ObservedValue); Assert.True(bExpected.MaxDiff(bActual) < 1e-10); prob.ClearObservedValue(); bActual = engine.Infer<Bernoulli>(b); bExpected = new Bernoulli(2.0 / 3); Assert.True(bExpected.MaxDiff(bActual) < 1e-10); } [Fact] public void RedefineForEachError() { Assert.Throws<InvalidOperationException>(() => { Range r = new Range(1).Named("r"); Variable<bool> bools = Variable.Bernoulli(0.1).ForEach(r).Named("bools"); bools.SetTo(Variable.Bernoulli(0.2).ForEach(r).Named("bools2")); InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; engine.Infer<DistributionArray<Bernoulli>>(bools); }); } [Fact] public void ObserveForEach() { Range r = new Range(1).Named("r"); Variable<double> x = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(r).Named("x"); x.ArrayVariable.ObservedValue = new double[] { 3 }; VariableArray<double> y = Variable.Array<double>(r).Named("y"); y[r] = Variable.GaussianFromMeanAndVariance(x, 1); InferenceEngine engine = new InferenceEngine(); DistributionArray<Gaussian> yActual = engine.Infer<DistributionArray<Gaussian>>(y); IDistribution<double[]> yExpected = Distribution<double>.Array(new Gaussian[] { new Gaussian(3, 1) }); Assert.True(yExpected.MaxDiff(yActual) < 1e-10); } [Fact] public void ObserveForEachBlockError() { Assert.Throws<NullReferenceException>(() => { Range r = new Range(1).Named("r"); Variable<double> x; using (Variable.ForEach(r)) { x = Variable.GaussianFromMeanAndVariance(0, 1).Named("x"); } x.ArrayVariable.ObservedValue = new double[] { 3 }; VariableArray<double> y = Variable.Array<double>(r).Named("y"); y[r] = Variable.GaussianFromMeanAndVariance(x, 1).ForEach(r); InferenceEngine engine = new InferenceEngine(); DistributionArray<Gaussian> yActual = engine.Infer<DistributionArray<Gaussian>>(y); IDistribution<double[]> yExpected = Distribution<double>.Array(new Gaussian[] { new Gaussian(3, 1) }); Assert.True(yExpected.MaxDiff(yActual) < 1e-10); }); } [Fact] public void ObserveInsideForEachBlock() { Range r = new Range(1).Named("r"); Variable<double> x; using (Variable.ForEach(r)) { x = Variable.New<double>().Named("x"); x.ObservedValue = 3; } //x.IsReadOnly = true; VariableArray<double> y = Variable.Array<double>(r).Named("y"); y[r] = Variable.GaussianFromMeanAndVariance(x, 1).ForEach(r); InferenceEngine engine = new InferenceEngine(); DistributionArray<Gaussian> yActual = engine.Infer<DistributionArray<Gaussian>>(y); IDistribution<double[]> yExpected = Distribution<double>.Array(new Gaussian[] { new Gaussian(3, 1) }); Assert.True(yExpected.MaxDiff(yActual) < 1e-10); } [Fact] public void ObserveInsideForEachBlock2() { Range r = new Range(1).Named("r"); Variable<double> x; using (Variable.ForEach(r)) { x = Variable.Observed(3.0).Named("x"); } //x.IsReadOnly = true; VariableArray<double> y = Variable.Array<double>(r).Named("y"); y[r] = Variable.GaussianFromMeanAndVariance(x, 1).ForEach(r); InferenceEngine engine = new InferenceEngine(); DistributionArray<Gaussian> yActual = engine.Infer<DistributionArray<Gaussian>>(y); IDistribution<double[]> yExpected = Distribution<double>.Array(new Gaussian[] { new Gaussian(3, 1) }); Assert.True(yExpected.MaxDiff(yActual) < 1e-10); } [Fact] public void ObserveOutsideForEachBlock() { Range r = new Range(1).Named("r"); Variable<double> x; using (Variable.ForEach(r)) { x = Variable.GaussianFromMeanAndVariance(0, 1).Named("x"); } x.ObservedValue = 3; //x.IsReadOnly = true; VariableArray<double> y = Variable.Array<double>(r).Named("y"); y[r] = Variable.GaussianFromMeanAndVariance(x, 1).ForEach(r); InferenceEngine engine = new InferenceEngine(); DistributionArray<Gaussian> yActual = engine.Infer<DistributionArray<Gaussian>>(y); IDistribution<double[]> yExpected = Distribution<double>.Array(new Gaussian[] { new Gaussian(3, 1) }); Assert.True(yExpected.MaxDiff(yActual) < 1e-10); } [Fact] public void ObserveForEachError() { Assert.Throws<InvalidOperationException>(() => { Range r = new Range(1).Named("r"); Variable<double> x = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(r).Named("x"); x.ObservedValue = 3; VariableArray<double> y = Variable.Array<double>(r).Named("y"); y[r] = Variable.GaussianFromMeanAndVariance(x, 1); InferenceEngine engine = new InferenceEngine(); engine.Infer<DistributionArray<Gaussian>>(y); }); } [Fact] public void CircularDefinitionError() { Assert.Throws<CompilationFailedException>(() => { Variable<bool> x = Variable.New<bool>().Named("x"); Variable<bool> y = !x; y.Named("y"); Variable<bool> z = !y; x.SetTo(z); InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(x)); }); } [Fact] public void RedefineConstantError() { Assert.Throws<InvalidOperationException>(() => { Variable<int> size = Variable.Constant<int>(4).Named("size"); Range r = new Range(size).Named("r"); VariableArray<double> x = Variable.Array<double>(r).Named("x"); x[r] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(r); size.ObservedValue = 3; InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; DistributionArray<Gaussian> xActual = engine.Infer<DistributionArray<Gaussian>>(x); }); } [Fact] public void GivenNotDefinedError() { Assert.Throws<InferCompilerException>(() => { Variable<int> size = Variable.New<int>().Named("size"); Range r = new Range(size).Named("r"); VariableArray<double> x = Variable.Array<double>(r).Named("x"); x[r] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(r); InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; DistributionArray<Gaussian> xActual = engine.Infer<DistributionArray<Gaussian>>(x); }); } [Trait("Category", "OpenBug")] [Fact] public void RedefineVariableError() { Assert.Throws<InferCompilerException>(() => { var x = Variable.New<bool>(); var c1 = Variable.Bernoulli(0.1).Named("c1"); using (Variable.If(c1)) { x.SetTo(true); } using (Variable.IfNot(c1)) { x.SetTo(false); } var c2 = Variable.Bernoulli(0.2).Named("c2"); using (Variable.If(c2)) { x.SetTo(true); } using (Variable.IfNot(c2)) { x.SetTo(false); } InferenceEngine engine = new InferenceEngine(); var xActual = engine.Infer(x); }); } [Fact] public void RedefineArrayError() { Assert.Throws<InvalidOperationException>(() => { Range r = new Range(1).Named("r"); VariableArray<double> array = Variable.Constant(new double[] { 1.2 }).Named("array"); VariableArray<int> indices = Variable.Constant(new int[] { 0 }).Named("indices"); VariableArray<double> x = Variable.GetItems(array, indices).Named("x"); // redefinition of x x[r] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(r); InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; DistributionArray<Gaussian> xActual = engine.Infer<DistributionArray<Gaussian>>(x); }); } [Trait("Category", "OpenBug")] [Fact] public void RedefineArrayError2() { Assert.Throws<InferCompilerException>(() => { Range timeRange = new Range(2); var sum = Variable.Array<double>(timeRange).Named("sum"); var x = Variable.Array<double>(timeRange).Named("x"); // for each time step using (var block = Variable.ForEach(timeRange)) { var t = block.Index; using (Variable.If(t == 0)) { sum[t] = Variable.GaussianFromMeanAndVariance(0, 0); x[t] = Variable.GaussianFromMeanAndVariance(0, 1.0); } using (Variable.If(t > 0)) { sum[t] = sum[t - 1] + x[t - 1]; } // order iff below minimum Variable<bool> mustOrder = Variable.Bernoulli(0.1); using (Variable.If(mustOrder)) { x[t].SetTo(0.0); } using (Variable.IfNot(mustOrder)) { x[t].SetTo(0.0); } } // end ForEach block InferenceEngine ie = new InferenceEngine(); var xActual = ie.Infer<IList<Gaussian>>(x); }); } [Fact] public void ArrayNotDefinedError() { Assert.Throws<InferCompilerException>(() => { Range r = new Range(1).Named("r"); VariableArray<double> x = Variable.Array<double>(r).Named("x"); InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; DistributionArray<Gaussian> xActual = engine.Infer<DistributionArray<Gaussian>>(x); }); } [Fact] public void ArrayOfGivenLength() { Variable<int> size = Variable.New<int>().Named("size"); Range r = new Range(size).Named("r"); VariableArray<double> x = Variable.Array<double>(r).Named("x"); x[r] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(r); InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; size.ObservedValue = 1; DistributionArray<Gaussian> xActual = engine.Infer<DistributionArray<Gaussian>>(x); IDistribution<double[]> xExpected = Distribution<double>.Array(size.ObservedValue, delegate (int i) { return new Gaussian(0, 1); }); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xActual.MaxDiff(xExpected) < 1e-10); } [Fact] public void ArrayOfConstantLength() { Variable<int> size = Variable.Constant<int>(1).Named("size"); Range r = new Range(size).Named("r"); VariableArray<double> x = Variable.Array<double>(r).Named("x"); x[r] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(r); InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; DistributionArray<Gaussian> xActual = engine.Infer<DistributionArray<Gaussian>>(x); IDistribution<double[]> xExpected = Distribution<double>.Array(size.ObservedValue, i => new Gaussian(0, 1)); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xActual.MaxDiff(xExpected) < 1e-10); } [Fact] public void Array2DSizeError() { Range r = new Range(1).Named("r"); Range r2 = new Range(2).Named("r2"); VariableArray2D<bool> y = Variable.Array<bool>(r, r2).Named("y"); VariableArray2D<bool> x = Variable.Array<bool>(r, r2).Named("x"); x[r, r2] = !y[r, r2]; InferenceEngine engine = new InferenceEngine(); y.ObservedValue = Util.ArrayInit(1, 1, (i, j) => true); try { object xActual = engine.Infer(x); Assert.True(false, "Did not throw exception"); IDistribution<bool[]> xExpected = Distribution<bool>.Array(r.SizeAsInt, i => new Bernoulli(0)); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xExpected.MaxDiff(xActual) < 1e-10); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with " + ex); } } [Fact] public void ArraySizeError() { Range r = new Range(1).Named("r"); VariableArray<bool> y = Variable.Array<bool>(r).Named("y"); VariableArray<bool> x = Variable.Array<bool>(r).Named("x"); x[r] = !y[r]; InferenceEngine engine = new InferenceEngine(); y.ObservedValue = Util.ArrayInit(2, i => true); try { object xActual = engine.Infer(x); Assert.True(false, "Did not throw exception"); IDistribution<bool[]> xExpected = Distribution<bool>.Array(r.SizeAsInt, i => new Bernoulli(0)); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xExpected.MaxDiff(xActual) < 1e-10); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with " + ex); } } [Fact] public void ArraySizeError2() { Variable<int> size = Variable.Constant<int>(1).Named("size"); Range r = new Range(size).Named("r"); VariableArray<bool> y = Variable.Array<bool>(r).Named("y"); VariableArray<bool> x = Variable.Array<bool>(r).Named("x"); x[r] = !y[r]; InferenceEngine engine = new InferenceEngine(); y.ObservedValue = Util.ArrayInit(2, i => true); try { object xActual = engine.Infer(x); Assert.True(false, "Did not throw exception"); IDistribution<bool[]> xExpected = Distribution<bool>.Array(size.ObservedValue, i => new Bernoulli(0)); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xExpected.MaxDiff(xActual) < 1e-10); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with " + ex); } } [Fact] public void ArraySizeError3() { Variable<int> size = Variable.Observed(1).Named("size"); Range r = new Range(size).Named("r"); VariableArray<bool> y = Variable.Array<bool>(r).Named("y"); VariableArray<bool> x = Variable.Array<bool>(r).Named("x"); x[r] = !y[r]; InferenceEngine engine = new InferenceEngine(); y.ObservedValue = Util.ArrayInit(2, i => true); try { object xActual = engine.Infer(x); Assert.True(false, "Did not throw exception"); IDistribution<bool[]> xExpected = Distribution<bool>.Array(size.ObservedValue, i => new Bernoulli(0)); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xExpected.MaxDiff(xActual) < 1e-10); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with " + ex); } } [Fact] [Trait("Category", "BadTest")] public void ImplicitArrayOfGivenLength() { Variable<int> size = Variable.New<int>().Named("size"); Range r = new Range(size).Named("r"); Variable<double> x; using (Variable.ForEach(r)) { x = Variable.GaussianFromMeanAndVariance(0, 1).Named("x"); } InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; size.ObservedValue = 1; DistributionArray<Gaussian> xActual = engine.Infer<DistributionArray<Gaussian>>(x); IDistribution<double[]> xExpected = Distribution<double>.Array(size.ObservedValue, delegate (int i) { return new Gaussian(0, 1); }); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xActual.MaxDiff(xExpected) < 1e-10); } [Fact] [Trait("Category", "BadTest")] public void ImplicitArrayOfConstantLength() { Variable<int> size = Variable.Constant<int>(1).Named("size"); Range r = new Range(size).Named("r"); Variable<double> x; using (Variable.ForEach(r)) { x = Variable.GaussianFromMeanAndVariance(0, 1).Named("x"); } InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Always; DistributionArray<Gaussian> xActual = engine.Infer<DistributionArray<Gaussian>>(x); IDistribution<double[]> xExpected = Distribution<double>.Array(size.ObservedValue, delegate (int i) { return new Gaussian(0, 1); }); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xActual.MaxDiff(xExpected) < 1e-10); } [Fact] public void VariableOfGenericType() { Variable<List<double>> a = Variable.Constant(new List<double>(new double[] { 5 })); Variable<double> y = Variable<double>.Factor(Factor.GetItem, a, 0); Variable<double> x = Variable.GaussianFromMeanAndVariance(y, 1); InferenceEngine engine = new InferenceEngine(); Gaussian xActual = engine.Infer<Gaussian>(x); Gaussian xExpected = new Gaussian(5, 1); Console.WriteLine("x = {0} (should be {1})", xActual, xExpected); Assert.True(xActual.MaxDiff(xExpected) < 1e-10); } [Fact] public void RandomArray() { Bernoulli[] boolsPriorArray = new Bernoulli[] { new Bernoulli(0.2) }; Variable<bool[]> bools = Variable<bool[]>.Random(Distribution<bool>.Array(boolsPriorArray)); InferenceEngine engine = new InferenceEngine(); Bernoulli[] boolsActual = engine.Infer<Bernoulli[]>(bools); Assert.True(boolsPriorArray[0].MaxDiff(boolsActual[0]) < 1e-10); } [Fact] public void ForEachBooleanTest() { VariableArray<double> probTrue = Variable.Constant(new double[] { 0.1, 0.8 }).Named("probTrue"); Range n = probTrue.Range; VariableArray<bool> noisyBools = Variable.Array<bool>(n).Named("noisyBools"); noisyBools[n] = Variable.Bernoulli(probTrue[n]).Named("bools") == Variable.Bernoulli(0.75).ForEach(n); VariableArray<bool> sameNoise = Variable.Array<bool>(n).Named("sameNoise"); sameNoise[n] = Variable.Bernoulli(probTrue[n]).Named("sameNoiseBools") == Variable.Bernoulli(0.75); InferenceEngine engine = new InferenceEngine(new ExpectationPropagation()); Console.WriteLine("noisyBools = "); Console.WriteLine(engine.Infer(noisyBools)); Console.WriteLine("sameNoise = "); Console.WriteLine(engine.Infer(sameNoise)); } [Fact] public void ForEachConstantError() { Assert.Throws<ArgumentException>(() => { Range n = new Range(1).Named("n"); VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[n] = Variable.Bernoulli(Variable.Constant(0.9).ForEach(n)); InferenceEngine engine = new InferenceEngine(new ExpectationPropagation()); DistributionArray<Bernoulli> d = engine.Infer<DistributionArray<Bernoulli>>(bools); Console.WriteLine("bools = "); Console.WriteLine(d); //Assert.True(d[0].MaxDiff(new Bernoulli(0.9)) < 1e-10); }); } [Fact] public void ForEachGivenTest() { Range item = new Range(1).Named("item"); Variable<double> p = Variable.New<double>().Named("p").ForEach(item); VariableArray<bool> bools = Variable.Array<bool>(item).Named("bools"); bools[item] = Variable.Bernoulli(p); InferenceEngine engine = new InferenceEngine(new ExpectationPropagation()); p.ArrayVariable.ObservedValue = new double[] { 0.9 }; DistributionArray<Bernoulli> d = engine.Infer<DistributionArray<Bernoulli>>(bools); Console.WriteLine("bools = "); Console.WriteLine(d); Assert.True(d[0].MaxDiff(new Bernoulli(0.9)) < 1e-10); } [Fact] public void ForEachGivenInitialError() { Assert.Throws<ArgumentException>(() => { Variable<double> p = Variable.Observed(0.9).Named("p"); Range item = new Range(1).Named("item"); VariableArray<bool> bools = Variable.Array<bool>(item).Named("bools"); bools[item] = Variable.Bernoulli(p.ForEach(item)); InferenceEngine engine = new InferenceEngine(new ExpectationPropagation()); DistributionArray<Bernoulli> d = engine.Infer<DistributionArray<Bernoulli>>(bools); Console.WriteLine("bools = "); Console.WriteLine(d); //Assert.True(d[0].MaxDiff(new Bernoulli(0.9)) < 1e-10); }); } [Fact] public void ForEachGivenNotSetTest() { Assert.Throws<InvalidOperationException>(() => { Variable<double> p = Variable.New<double>().Named("p"); Range item = new Range(1).Named("item"); VariableArray<bool> bools = Variable.Array<bool>(item).Named("bools"); bools[item] = Variable.Bernoulli(p.ForEach(item)); InferenceEngine engine = new InferenceEngine(new ExpectationPropagation()); p.ObservedValue = 0.9; // must use p.Array.Value Console.WriteLine(engine.Infer(bools)); }); } [Fact] public void ForEachGivenReplicationError() { Assert.Throws<ArgumentException>(() => { Variable<double> p = Variable.Observed(0.9).Named("p"); Variable<int> size = Variable.New<int>().Named("size"); Range n = new Range(size).Named("n"); VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[n] = Variable.Bernoulli(p.ForEach(n)); InferenceEngine engine = new InferenceEngine(new ExpectationPropagation()); size.ObservedValue = 1; Console.WriteLine(engine.Infer(bools)); }); } [Fact] public void ArrayIndexingErrors() { Range i = new Range(2).Named("i"); Range n = new Range(2).Named("n"); try { VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[n] = Variable.Bernoulli(0.5); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[n] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[n] = Variable.Bernoulli(0.5).ForEach(i, n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[i] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[i] = Variable.Bernoulli(0.5).ForEach(n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } if (true) { VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[n] = Variable.Bernoulli(0.5).ForEach(n); } try { VariableArray<bool> constBools = Variable.Constant(new bool[] { true, false }, n).Named("constBools"); constBools[n] = Variable.Bernoulli(0.5); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> constBools = Variable.Constant(new bool[] { true, false }, n).Named("constBools"); constBools[n] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> constBools = Variable.Constant(new bool[] { true, false }, n).Named("constBools"); constBools[n] = Variable.Bernoulli(0.5).ForEach(i, n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> constBools = Variable.Constant(new bool[] { true, false }, n).Named("constBools"); constBools[i] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> constBools = Variable.Constant(new bool[] { true, false }, n).Named("constBools"); constBools[i] = Variable.Bernoulli(0.5).ForEach(n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } if (true) { VariableArray<bool> constBools = Variable.Constant(new bool[] { true, false }, n).Named("constBools"); constBools[n] = Variable.Bernoulli(0.5).ForEach(n); } try { VariableArray<bool> givenBools = Variable.Observed(new bool[] { true, false }, n).Named("givenBools"); givenBools[n] = Variable.Bernoulli(0.5); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> givenBools = Variable.Observed(new bool[] { true, false }, n).Named("givenBools"); givenBools[n] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> givenBools = Variable.Observed(new bool[] { true, false }, n).Named("givenBools"); givenBools[n] = Variable.Bernoulli(0.5).ForEach(i, n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> givenBools = Variable.Observed(new bool[] { true, false }, n).Named("givenBools"); givenBools[i] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray<bool> givenBools = Variable.Observed(new bool[] { true, false }, n).Named("givenBools"); givenBools[i] = Variable.Bernoulli(0.5).ForEach(n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } if (true) { VariableArray<bool> givenBools = Variable.Observed(new bool[] { true, false }, n).Named("givenBools"); givenBools[n] = Variable.Bernoulli(0.5).ForEach(n); } } [Fact] public void Array2dIndexingErrors() { Range i = new Range(2).Named("i"); Range n = new Range(2).Named("n"); Range m = new Range(2).Named("m"); try { VariableArray2D<bool> bools = Variable.Array<bool>(n, m).Named("bools"); bools[n, m] = Variable.Bernoulli(0.5); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> bools = Variable.Array<bool>(n, m).Named("bools"); bools[n, m] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> bools = Variable.Array<bool>(n, m).Named("bools"); bools[n, m] = Variable.Bernoulli(0.5).ForEach(i, n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> bools = Variable.Array<bool>(n, m).Named("bools"); bools[n, m] = Variable.Bernoulli(0.5).ForEach(i, n, m); Assert.True(false, "Did not throw exception"); } catch (NotSupportedException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> bools = Variable.Array<bool>(n, m).Named("bools"); bools[i, m] = Variable.Bernoulli(0.5).ForEach(i, m); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> bools = Variable.Array<bool>(n, m).Named("bools"); bools[i, m] = Variable.Bernoulli(0.5).ForEach(n, m); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } if (true) { VariableArray2D<bool> bools = Variable.Array<bool>(n, m).Named("bools"); bools[n, m] = Variable.Bernoulli(0.5).ForEach(n, m); } bool[,] init2d = new bool[,] { { true, false }, { true, false } }; try { VariableArray2D<bool> constBools = Variable.Constant(init2d, n, m).Named("constBools"); constBools[n, m] = Variable.Bernoulli(0.5); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> constBools = Variable.Constant(init2d, n, m).Named("constBools"); constBools[n, m] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> constBools = Variable.Constant(init2d, n, m).Named("constBools"); constBools[n, m] = Variable.Bernoulli(0.5).ForEach(i, n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> constBools = Variable.Constant(init2d, n, m).Named("constBools"); constBools[n, m] = Variable.Bernoulli(0.5).ForEach(i, n, m); Assert.True(false, "Did not throw exception"); } catch (NotSupportedException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> constBools = Variable.Constant(init2d, n, m).Named("constBools"); constBools[i, m] = Variable.Bernoulli(0.5).ForEach(i, m); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> constBools = Variable.Constant(init2d, n, m).Named("constBools"); constBools[i, m] = Variable.Bernoulli(0.5).ForEach(n, m); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } if (true) { VariableArray2D<bool> constBools = Variable.Constant(init2d, n, m).Named("constBools"); constBools[n, m] = Variable.Bernoulli(0.5).ForEach(n, m); } try { VariableArray2D<bool> givenBools = Variable.Observed(init2d, n, m).Named("givenBools"); givenBools[n, m] = Variable.Bernoulli(0.5); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> givenBools = Variable.Observed(init2d, n, m).Named("givenBools"); givenBools[n, m] = Variable.Bernoulli(0.5).ForEach(i); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> givenBools = Variable.Observed(init2d, n, m).Named("givenBools"); givenBools[n, m] = Variable.Bernoulli(0.5).ForEach(i, n); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> givenBools = Variable.Observed(init2d, n, m).Named("givenBools"); givenBools[n, m] = Variable.Bernoulli(0.5).ForEach(i, n, m); Assert.True(false, "Did not throw exception"); } catch (NotSupportedException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> givenBools = Variable.Observed(init2d, n, m).Named("givenBools"); givenBools[i, m] = Variable.Bernoulli(0.5).ForEach(i, m); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { VariableArray2D<bool> givenBools = Variable.Observed(init2d, n, m).Named("givenBools"); givenBools[i, m] = Variable.Bernoulli(0.5).ForEach(n, m); Assert.True(false, "Did not throw exception"); } catch (ArgumentException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } if (true) { VariableArray2D<bool> givenBools = Variable.Observed(init2d, n, m).Named("givenBools"); givenBools[n, m] = Variable.Bernoulli(0.5).ForEach(n, m); } } [Fact] public void Array2dIndexing() { Range n = new Range(2).Named("n"); Range m = new Range(2).Named("m"); VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); bools[n] = Variable.Bernoulli(0.9).ForEach(n); bool[] init = new bool[] { true, false }; VariableArray<bool> constBools = Variable.Constant<bool>(init, n).Named("constBools"); VariableArray<bool> givenBools = Variable.Observed(init, n).Named("givenBools"); VariableArray2D<bool> bools2d = Variable.Array<bool>(n, m).Named("bools2d"); bools2d[n, m] = (!bools[n]).ForEach(m); VariableArray2D<bool> bools2dFromConst = Variable.Array<bool>(n, m).Named("bools2dFromConst"); bools2dFromConst[n, m] = (!constBools[n]).ForEach(m); VariableArray2D<bool> bools2dFromGiven = Variable.Array<bool>(n, m).Named("bools2dFromGiven"); bools2dFromGiven[n, m] = (!givenBools[n]).ForEach(m); VariableArray<bool> boolsFromConst = Variable.Array<bool>(n).Named("boolsFromConst"); boolsFromConst[n] = Variable.Bernoulli(0.9).ForEach(n); bool[,] init2d = new bool[,] { { true, true }, { false, false } }; VariableArray2D<bool> constBools2d = Variable.Constant<bool>(init2d, n, m); constBools2d[n, m] = (!boolsFromConst[n]).ForEach(m); VariableArray<bool> boolsFromGiven = Variable.Array<bool>(n).Named("boolsFromGiven"); boolsFromGiven[n] = Variable.Bernoulli(0.9).ForEach(n); VariableArray2D<bool> givenBools2d = Variable.Observed<bool>(init2d, n, m).Named("givenBools2d"); givenBools2d[n, m] = (!boolsFromGiven[n]).ForEach(m); InferenceEngine engine = new InferenceEngine(); DistributionArray<Bernoulli> bools_Marginal = engine.Infer<DistributionArray<Bernoulli>>(bools); bools_Marginal.ForEach(delegate (Bernoulli item) { Assert.True(item.MaxDiff(new Bernoulli(0.9)) < 1e-10); }); #if false // cannot infer derived constants or givens DistributionArray<Bernoulli> bools2dFromConst_Marginal = engine.Infer<DistributionArray<Bernoulli>>(bools2dFromConst); for (int i = 0; i < bools2dFromConst_Marginal.GetLength(0); i++) { for (int j = 0; j < bools2dFromConst_Marginal.GetLength(1); j++) { Assert.True(bools2dFromConst_Marginal[i, j].MaxDiff(Bernoulli.PointMass(!init[i])) < 1e-10); } } DistributionArray<Bernoulli> bools2dFromGiven_Marginal = engine.Infer<DistributionArray<Bernoulli>>(bools2dFromGiven); for (int i = 0; i < bools2dFromGiven_Marginal.GetLength(0); i++) { for (int j = 0; j < bools2dFromGiven_Marginal.GetLength(1); j++) { Assert.True(bools2dFromGiven_Marginal[i, j].MaxDiff(Bernoulli.PointMass(!init[i])) < 1e-10); } } #endif DistributionArray<Bernoulli> boolsFromConst_Marginal = engine.Infer<DistributionArray<Bernoulli>>(boolsFromConst); for (int i = 0; i < boolsFromConst_Marginal.Count; i++) { Assert.True(boolsFromConst_Marginal[i].MaxDiff(Bernoulli.PointMass(!init[i])) < 1e-10); } DistributionArray<Bernoulli> boolsFromGiven_Marginal = engine.Infer<DistributionArray<Bernoulli>>(boolsFromGiven); for (int i = 0; i < boolsFromGiven_Marginal.Count; i++) { Assert.True(boolsFromGiven_Marginal[i].MaxDiff(Bernoulli.PointMass(!init[i])) < 1e-10); } } [Fact] public void DuplicateForEachError() { Assert.Throws<InvalidOperationException>(() => { Range item = new Range(2).Named("item"); VariableArray<bool> bools = Variable.Array<bool>(item).Named("bools"); using (Variable.ForEach(item)) { using (Variable.ForEach(item)) { bools[item] = Variable.Bernoulli(0.1); } } }); } [Fact] public void DuplicateForEachError2() { Assert.Throws<InvalidOperationException>(() => { Range item = new Range(2).Named("item"); VariableArray<bool> bools = Variable.Array<bool>(item).Named("bools"); using (Variable.ForEach(item)) { bools[item] = Variable.Bernoulli(0.1).ForEach(item); } }); } [Fact] public void DanglingBlockError() { Assert.Throws<InvalidOperationException>((Action)(() => { Range item = new Range(2).Named("item"); try { ForEachBlock block = Variable.ForEach(item); Variable<bool> b = Variable.Bernoulli(0.5); InferenceEngine engine = new InferenceEngine(); engine.Infer(b); } finally { StatementBlock.CloseAllBlocks(); } })); } [Fact] public void ForEachBlockLhsError() { Assert.Throws<ArgumentException>(() => { Range item = new Range(2).Named("item"); Range feature = new Range(2).Named("feature"); VariableArray<bool> b = Variable.Array<bool>(feature); using (Variable.ForEach(item)) { b[feature] = Variable.Bernoulli(0.5).ForEach(feature); } }); } [Fact] public void ForEachBlockLocalArrayTest() { Range item = new Range(2).Named("item"); Range feature = new Range(2).Named("feature"); VariableArray2D<bool> a = Variable.Array<bool>(item, feature); using (Variable.ForEach(item)) { VariableArray<bool> b = Variable.Array<bool>(feature); b[feature] = Variable.Bernoulli(0.9).ForEach(feature); a[item, feature] = !b[feature]; } InferenceEngine engine = new InferenceEngine(); DistributionArray2D<Bernoulli> actual = engine.Infer<DistributionArray2D<Bernoulli>>(a); Bernoulli expected = new Bernoulli(0.1); foreach (Bernoulli dist in actual) { Assert.True(dist.MaxDiff(expected) < 1e-10); } } // This functionality is no longer supported. //[Fact] internal void ForEachBlockVariableArrayTest() { Range item = new Range(1).Named("item"); Range feature = new Range(1).Named("feature"); VariableArray2D<bool> b = Variable.Array<bool>(item, feature).Named("b"); VariableArray<double> p; using (Variable.ForEach(item)) { p = Variable.Array<double>(feature).Named("p"); b[item, feature] = Variable.Bernoulli(p[feature]); } InferenceEngine engine = new InferenceEngine(); p.ArrayVariable.ObservedValue = new double[][] { new double[] { 0.9 } }; DistributionArray2D<Bernoulli> actual = engine.Infer<DistributionArray2D<Bernoulli>>(b); IDistribution<bool[,]> expected = Distribution<bool>.Array(new Bernoulli[,] { { new Bernoulli(0.9) } }); Assert.True(expected.MaxDiff(actual) < 1e-10); } [Fact] [Trait("Category", "BadTest")] public void ForEachSetToTest() { Range item = new Range(1).Named("item"); Variable<bool> x; using (Variable.ForEach(item)) { Variable<bool> c = Variable.Bernoulli(0.1).Named("c"); x = Variable.New<bool>().Named("x"); using (Variable.If(c)) { x.SetTo(Variable.Bernoulli(0.3)); } using (Variable.IfNot(c)) { x.SetTo(Variable.Bernoulli(0.4)); } } InferenceEngine engine = new InferenceEngine(); DistributionArray<Bernoulli> actual = engine.Infer<DistributionArray<Bernoulli>>(x); IDistribution<bool[]> expected = Distribution<bool>.Array(new Bernoulli[] { new Bernoulli(0.1 * 0.3 + 0.9 * 0.4) }); Assert.True(expected.MaxDiff(actual) < 1e-10); } [Fact] public void ForEachBlockTest() { Range n = new Range(2).Named("n"); Range m = new Range(2).Named("m"); bool[] init = new bool[] { true, false }; bool[,] init2d = new bool[,] { { true, true }, { false, false } }; VariableArray<bool> bools = Variable.Array<bool>(n).Named("bools"); VariableArray<bool> constBools = Variable.Constant<bool>(init, n).Named("constBools"); VariableArray<bool> givenBools = Variable.Observed(init, n).Named("givenBools"); VariableArray<bool> boolsFromConst = Variable.Array<bool>(n).Named("boolsFromConst"); VariableArray<bool> boolsFromGiven = Variable.Array<bool>(n).Named("boolsFromGiven"); VariableArray2D<bool> bools2d = Variable.Array<bool>(n, m).Named("bools2d"); VariableArray2D<bool> bools2dFromConst = Variable.Array<bool>(n, m).Named("bools2dFromConst"); VariableArray2D<bool> bools2dFromGiven = Variable.Array<bool>(n, m).Named("bools2dFromGiven"); VariableArray2D<bool> constBools2d = Variable.Constant<bool>(init2d, n, m); VariableArray2D<bool> givenBools2d = Variable.Observed<bool>(init2d, n, m).Named("givenBools2d"); using (Variable.ForEach(n)) { bools[n] = Variable.Bernoulli(0.9); boolsFromConst[n] = Variable.Bernoulli(0.9); boolsFromGiven[n] = Variable.Bernoulli(0.9); using (Variable.ForEach(m)) { bools2d[n, m] = !bools[n]; } bools2dFromConst[n, m] = (!constBools[n]).ForEach(m); } using (Variable.ForEach(m)) { bools2dFromGiven[n, m] = (!givenBools[n]); constBools2d[n, m] = (!boolsFromConst[n]); givenBools2d[n, m] = (!boolsFromGiven[n]); } InferenceEngine engine = new InferenceEngine(); engine.Compiler.ReturnCopies = false; DistributionArray<Bernoulli> bools_Marginal = engine.Infer<DistributionArray<Bernoulli>>(bools); bools_Marginal.ForEach(delegate (Bernoulli item) { Assert.True(item.MaxDiff(new Bernoulli(0.9)) < 1e-10); }); DistributionArray2D<Bernoulli> bools2dFromConst_Marginal = engine.Infer<DistributionArray2D<Bernoulli>>(bools2dFromConst); for (int i = 0; i < bools2dFromConst_Marginal.GetLength(0); i++) { for (int j = 0; j < bools2dFromConst_Marginal.GetLength(1); j++) { Assert.True(bools2dFromConst_Marginal[i, j].MaxDiff(Bernoulli.PointMass(!init[i])) < 1e-10); } } DistributionArray2D<Bernoulli> bools2dFromGiven_Marginal = engine.Infer<DistributionArray2D<Bernoulli>>(bools2dFromGiven); for (int i = 0; i < bools2dFromGiven_Marginal.GetLength(0); i++) { for (int j = 0; j < bools2dFromGiven_Marginal.GetLength(1); j++) { Assert.True(bools2dFromGiven_Marginal[i, j].MaxDiff(Bernoulli.PointMass(!init[i])) < 1e-10); } } DistributionArray<Bernoulli> boolsFromConst_Marginal = engine.Infer<DistributionArray<Bernoulli>>(boolsFromConst); for (int i = 0; i < boolsFromConst_Marginal.Count; i++) { Assert.True(boolsFromConst_Marginal[i].MaxDiff(Bernoulli.PointMass(!init[i])) < 1e-10); } DistributionArray<Bernoulli> boolsFromGiven_Marginal = engine.Infer<DistributionArray<Bernoulli>>(boolsFromGiven); for (int i = 0; i < boolsFromGiven_Marginal.Count; i++) { Assert.True(boolsFromGiven_Marginal[i].MaxDiff(Bernoulli.PointMass(!init[i])) < 1e-10); } } /// This test now does not compile, as desired, since Variable.Random /// has additional static type checks which pick up on this error. /*[Fact] public void RandomRequiresDistributionError() { try { Given<double> d = Variable.Given<double>("d", 0.0); Variable<double> x = Variable.Random<double,double>(d); Assert.True(false, "Did not throw exception"); } catch (Exception ex) { Console.WriteLine("Correctly failed with exception: "+ex); } //InferenceEngine engine = new InferenceEngine(); //engine.BrowserMode = BrowserMode.Never; //Console.WriteLine(engine.Infer<Gaussian>(x)); }*/ /// <summary> /// Checks to ensure that using variable names that are not valid identifiers doesn't cause errors. /// </summary> [Fact] public void VariableNamingTest() { InferenceEngine engine = new InferenceEngine(); string[] names = { "this", "a,b", "00hello", "test name", "hello!world", "fred0", " x ", "x`~!@#$%^&*()-+=[]\\{}|;:'\",./<>?", "", "for", "typeof" }; foreach (string name in names) { Variable<double> mean = Variable.Observed(5.6).Named("given" + name); Variable<double> prec = Variable.Constant(1.0).Named("const" + name); Variable<double> x = Variable.GaussianFromMeanAndPrecision(mean, prec).Named(name); Console.WriteLine("result = {0}", engine.Infer(x)); } } [Fact] public void ModelNamingTest() { InferenceEngine engine = new InferenceEngine(); string[] names = { "this", "a,b", "00hello", "test name", "hello!world", "fred0", " x ", "x`~!@#$%^&*()-+=[]\\{}|;:'\",./<>?", "", "for", "typeof" }; foreach (string name in names) { engine.ModelName = name; var b = Variable<bool>.Bernoulli(0.5); Console.WriteLine(engine.Infer(b)); } } [Fact] public void RangeNamingTest() { InferenceEngine engine = new InferenceEngine(); string[] names = { "this", "a,b", "00hello", "test name", "hello!world", "fred0", " i ", "x`~!@#$%^&*()-+=[]\\{}|;:'\",./<>?", "", "for", "typeof" }; foreach (string name in names) { Range item = new Range(1).Named(name); var x = Variable.Array<bool>(item).Named("x"); x[item] = Variable.Bernoulli(0.1).ForEach(item); Console.WriteLine(engine.Infer(x)); } } [Fact] public void RangeNameClashTest() { Assert.Throws<InferCompilerException>(() => { Range item = new Range(2).Named("item"); Range item2 = new Range(3).Named("item"); VariableArray2D<bool> bools = Variable.Array<bool>(item, item2).Named("bools"); bools[item, item2] = Variable.Bernoulli(0.1).ForEach(item, item2); InferenceEngine engine = new InferenceEngine(); engine.Infer(bools); }); } [Fact] public void RangeNameClashTest2() { Assert.Throws<InferCompilerException>(() => { Range item = new Range(2).Named("item"); VariableArray<bool> bools = Variable.Array<bool>(item).Named("item"); bools[item] = Variable.Bernoulli(0.1).ForEach(item); InferenceEngine engine = new InferenceEngine(); engine.Infer(bools); }); } [Fact] public void RangeNameClashTest3() { Assert.Throws<InferCompilerException>(() => { Range item = new Range(2).Named("emptyString"); Range item2 = new Range(3).Named(""); VariableArray2D<bool> bools = Variable.Array<bool>(item, item2).Named("bools"); bools[item, item2] = Variable.Bernoulli(0.1).ForEach(item, item2); InferenceEngine engine = new InferenceEngine(); engine.Infer(bools); }); } /*public void MyTest() { Range i = new Range(10); VariableArray<double> array = Variable.Array<double>(i); }*/ [Fact] public void BooleanConstantTest() { VariableArray<bool> const0 = Variable.Constant(new bool[] { false, true }).Named("c0"); Range n = const0.Range.Named("n"); VariableArray<bool> const1 = Variable.Array<bool>(n).Named("c1"); const1[n] = !const0[n]; VariableArray<bool> x = Variable.Array<bool>(n).Named("x"); x[n] = Variable.Bernoulli(0.5).ForEach(n); VariableArray<bool> y = Variable.Array<bool>(n).Named("y"); y[n] = x[n] | const1[n]; InferenceEngine engine = new InferenceEngine(new ExpectationPropagation()); //engine.BrowserMode = BrowserMode.Always; Console.WriteLine(engine.Infer(y)); DistributionArray<Bernoulli> yActual = engine.Infer<DistributionArray<Bernoulli>>(y); IDistribution<bool[]> yExpected = Distribution<bool>.Array(new Bernoulli[] { new Bernoulli(1), new Bernoulli(0.5) }); Assert.True(yExpected.MaxDiff(yActual) < 1e-10); } [Fact] public void ArrayOperatorTest() { Range item = new Range(2).Named("item"); Range feature = new Range(3).Named("feature"); VariableArray<double> array = Variable.Array<double>(item).Named("array"); array[item] = Variable.GaussianFromMeanAndVariance(0, 1).ForEach(item); VariableArray2D<double> array2D = Variable.Constant(new double[,] { { 1, 2, 3 }, { 4, 5, 6 } }, item, feature).Named("array2D"); VariableArray2D<double> product = Variable.Array<double>(item, feature).Named("product"); product[item, feature] = array[item] * array2D[item, feature]; InferenceEngine engine = new InferenceEngine(); Console.WriteLine(engine.Infer(product)); } /// <summary> /// Tests when building MSL that the uses of a variable come after its definition. /// </summary> [Fact] public void DeclarationOrderTest() { Variable<bool> x = Variable.Bernoulli(0.1).Named("x"); Variable<bool> y = (!x).Named("y"); Variable<bool> z = (x | y).Named("z"); InferenceEngine engine = new InferenceEngine(new ExpectationPropagation()); //engine.ShowSchedule = true; Bernoulli yActual = engine.Infer<Bernoulli>(y); Bernoulli yExpected = new Bernoulli(0.9); Console.WriteLine("y = {0}", yActual); Assert.True(yExpected.MaxDiff(yActual) < 1e-10); } public static T[] Replicate<T>(T value, int length) { T[] result = new T[length]; for (int i = 0; i < length; i++) { result[i] = value; } return result; } [Fact] public void ClickChainTest() { try { // observation[rank][user] //bool[][] observation = { new bool[] { false }, new bool[] { false }, new bool[] { true } }; bool[][] observation = new bool[2][]; observation[0] = Replicate(true, 12); observation[1] = Replicate(false, 12); int nRanks = observation.Length; int nUsers = observation[0].Length; Range user = new Range(nUsers).Named("user"); Variable<bool>[] rel = new Variable<bool>[nRanks]; Variable<double>[] summary = new Variable<double>[nRanks]; // examine[rank][user] VariableArray<bool>[] examine = new VariableArray<bool>[nRanks]; VariableArray<bool>[] click = new VariableArray<bool>[nRanks]; // user independent variables for (int rank = 0; rank < nRanks; rank++) { summary[rank] = Variable.Beta(1, 1).Named("Summary" + rank); rel[rank] = (Variable.Bernoulli(summary[rank]) == Variable.Bernoulli(0.8)).Named("Rel" + rank); } //user specific variables for (int rank = 0; rank < nRanks; rank++) { examine[rank] = Variable.Array<bool>(user).Named("Examine" + rank); click[rank] = Variable.Constant(observation[rank], user).Named("Click" + rank); if (rank == 0) { examine[rank][user] = Variable.Bernoulli(1).ForEach(user); //Variable.ConstrainEqual(examine[rank][user], true); } else { using (Variable.ForEach(user)) { Variable<bool> examineIfClick = Variable.New<bool>().Named("examineIfClick" + rank); using (Variable.If(rel[rank - 1])) examineIfClick.SetTo(Variable.Bernoulli(0.2)); using (Variable.IfNot(rel[rank - 1])) examineIfClick.SetTo(Variable.Bernoulli(0.9)); examine[rank][user] = examine[rank - 1][user] & ((!click[rank - 1][user] & Variable.Bernoulli(.8)) | (click[rank - 1][user] & examineIfClick)); } } click[rank][user] = examine[rank][user] & Variable.Bernoulli(summary[rank]).ForEach(user); } InferenceEngine ie = new InferenceEngine(); //ie.BrowserMode = BrowserMode.Always; for (int i = 0; i < nRanks; i++) { // Console.WriteLine("Relevance of document " +i +": "+ ie.Infer(rel)); Console.WriteLine("Relevance of document {0}: {1}", i, ie.Infer(rel[i])); } } catch (CompilationFailedException ex) { Console.WriteLine("Correctly threw " + ex); } } /// <summary> /// Click chain with unrolled users /// </summary> [Fact] public void ClickChainTest2() { // observation[rank][user] //bool[][] observation = { new bool[] { false }, new bool[] { false }, new bool[] { true } }; bool[][] observation = new bool[2][]; observation[0] = Replicate(true, 12); observation[1] = Replicate(false, 12); int nRanks = observation.Length; int nUsers = observation[0].Length; Variable<bool>[] rel = new Variable<bool>[nRanks]; Variable<double>[] summary = new Variable<double>[nRanks]; // examine[rank][user] Variable<bool>[][] examine = new Variable<bool>[nRanks][]; Variable<bool>[][] click = new Variable<bool>[nRanks][]; // user independent variables for (int rank = 0; rank < nRanks; rank++) { summary[rank] = Variable.Beta(1, 1).Named("Summary" + rank); rel[rank] = (Variable.Bernoulli(summary[rank]) == Variable.Bernoulli(0.8)).Named("Rel" + rank); } //user specific variables for (int rank = 0; rank < nRanks; rank++) { examine[rank] = new Variable<bool>[nUsers]; click[rank] = new Variable<bool>[nUsers]; for (int user = 0; user < nUsers; user++) { click[rank][user] = Variable.Constant(observation[rank][user]).Named("Click" + rank + user); if (rank == 0) { examine[rank][user] = Variable.Bernoulli(1); //Variable.ConstrainEqual(examine[rank][user], true); } else { Variable<bool> examineIfClick = Variable.New<bool>().Named("examineIfClick" + rank + user); using (Variable.If(rel[rank - 1])) examineIfClick.SetTo(Variable.Bernoulli(0.2)); using (Variable.IfNot(rel[rank - 1])) examineIfClick.SetTo(Variable.Bernoulli(0.9)); examine[rank][user] = examine[rank - 1][user] & ((!click[rank - 1][user] & Variable.Bernoulli(.8)) | (click[rank - 1][user] & examineIfClick)); } examine[rank][user].Name = "Examine" + rank + user; Variable.ConstrainEqual(click[rank][user], examine[rank][user] & Variable.Bernoulli(summary[rank])); } } InferenceEngine ie = new InferenceEngine(); //ie.BrowserMode = BrowserMode.Always; for (int i = 0; i < nRanks; i++) { // Console.WriteLine("Relevance of document " +i +": "+ ie.Infer(rel)); Console.WriteLine("Relevance of document {0}: {1}", i, ie.Infer(rel[i])); } } [Fact] public void BetaConstructionFromMeanAndVarianceTest() { var b = Variable.BetaFromMeanAndVariance(Variable.Constant(0.5), Variable.Constant(1.0)); Console.WriteLine(new InferenceEngine().Infer(b)); } [Fact] public void BetaConstructionTest() { var b = Variable.Beta(Variable.Constant(1.0), Variable.Constant(1.0)); Console.WriteLine(new InferenceEngine().Infer(b)); } [Fact] public void GammaConstructionFromMeanAndVarianceTest() { var g = Variable.GammaFromMeanAndVariance(Variable.Constant(0.5), Variable.Constant(1.0)); Console.WriteLine(new InferenceEngine().Infer(g)); } [Fact] public void GammaConstructionFromShapeAndScaleTest() { var g = Variable.GammaFromShapeAndScale(Variable.Constant(1.0), Variable.Constant(1.0)); Console.WriteLine(new InferenceEngine().Infer(g)); } [Fact] public void WishartConstructionFromShapeAndScaleTest() { var w = Variable.WishartFromShapeAndScale(Variable.Constant(1.0), Variable.Constant(PositiveDefiniteMatrix.Identity(5))); Console.WriteLine(new InferenceEngine().Infer(w)); } [Fact] public void WishartConstructionFromShapeAndRateTest() { var w = Variable.WishartFromShapeAndRate(Variable.Constant(1.0), Variable.Constant(PositiveDefiniteMatrix.Identity(5))); Console.WriteLine(new InferenceEngine().Infer(w)); } [Fact] public void VectorGaussianConstructionTest() { var mean = Vector.Zero(10); var cov = PositiveDefiniteMatrix.Identity(mean.Count); var v = Variable.VectorGaussianFromMeanAndVariance(Variable.Constant(mean), Variable.Constant(cov)); Console.WriteLine(new InferenceEngine().Infer(v)); } [Fact] public void CoupledHmmTest() { Diffable previous = default(Diffable); for (int i = 0; i < 3; i++) { Diffable result = CoupledHmmHelper(i); Console.WriteLine(result); if (i == 0) previous = result; else Assert.True(previous.MaxDiff(result) < 1e-10); } } private Diffable CoupledHmmHelper(int modelType) { // Emissions for two sites at 3 time steps (single sequence) int[][] emissions = new int[][] { new int[] {1, 2}, new int[] {0, 1}, new int[] {1, 2} }; CoupledHmm model = new CoupledHmm(); model.CreateModel(emissions.Length, modelType); // Observe the data: for (int t = 0; t < emissions.Length; t++) model.X[t].ObservedValue = emissions[t]; // Number of state values and output values per site: int[] numStatesPerSite = new int[] { 4, 3 }; int[] numOutputsPerSite = new int[] { 2, 3 }; int numSites = numStatesPerSite.Length; model.Sites.ObservedValue = numSites; model.StatesPerSite.ObservedValue = numStatesPerSite; model.OutputsPerSite.ObservedValue = numOutputsPerSite; model.Aprior.ObservedValue = Util.ArrayInit(numSites, site => Dirichlet.Uniform(numStatesPerSite[site])); model.engine.Compiler.OptimiseInferenceCode = false; return model.engine.Infer<Diffable>(model.A); } private class CoupledHmm { public Variable<int> Sites; public VariableArray<int> StatesPerSite; public VariableArray<int> OutputsPerSite; public VariableArray<VariableArray<VariableArray<Vector>, Vector[][]>, Vector[][][]> A; public VariableArray<Dirichlet> Aprior; public VariableArray<VariableArray<Vector>, Vector[][]> C; public VariableArray<int>[] Z; public VariableArray<int>[] X; public InferenceEngine engine = new InferenceEngine(new VariationalMessagePassing()); public void CreateModel(int numTimeSteps, int type = 0) { // Number of sites (observed) Sites = Variable.New<int>().Named("Sites"); // Range for current site Range Site_i = new Range(Sites).Named("Site_i"); // Range for influnecing site Range Site_j = Site_i.Clone().Named("Site_j"); // Number of discrete states per site (observed) StatesPerSite = Variable.Array<int>(Site_i).Named("StatesPerSite"); // Range for state in current site Range State_i = new Range(StatesPerSite[Site_i]).Named("State_i"); // State for current site // Range for state in influencing site Range State_j = new Range(StatesPerSite[Site_j]).Named("State_j"); //Range State_j = State_i.Clone().Named("State_j"); // Number of discrete outputs per site (observed) OutputsPerSite = Variable.Array<int>(Site_i).Named("OutputsPerSite"); // Range for output in current site Range Output = new Range(OutputsPerSite[Site_i]).Named("Output"); // Each (current site, influencing site) pair have a set of probability // vectors which determine the state transition from the influencing site // to the current site. A = Variable.Array(Variable.Array(Variable.Array<Vector>(State_j), Site_j), Site_i).Named("A"); Aprior = Variable.Array<Dirichlet>(Site_i).Named("Aprior"); if (type == 2) { using (Variable.ForEach(Site_i)) using (Variable.ForEach(Site_j)) using (Variable.ForEach(State_j)) A[Site_i][Site_j][State_j] = Variable.DirichletUniform(State_i); } else if (type == 1) { using (Variable.ForEach(Site_i)) A[Site_i][Site_j][State_j] = Variable.DirichletUniform(State_i).ForEach(Site_j, State_j); } else { using (Variable.ForEach(Site_i)) using (Variable.ForEach(Site_j)) using (Variable.ForEach(State_j)) A[Site_i][Site_j][State_j] = Variable<Vector>.Random(Aprior[Site_i]); A.SetValueRange(State_i); } // The probability vectors determining the emission variable for the current site // conditional on the current state at the current sit C = Variable.Array(Variable.Array<Vector>(State_i), Site_i).Named("C"); using (Variable.ForEach(Site_i)) //using (Variable.ForEach(State_i)) C[Site_i][State_i] = Variable.DirichletUniform(Output).ForEach(State_i); // The influence matrix - determines the influencing site given the current site. // Priors should be non-uniform, typically favouring the current site. VariableArray<Vector> Influence = Variable.Array<Vector>(Site_i).Named("Influence"); Influence[Site_i] = Variable.DirichletUniform(Site_j).ForEach(Site_i); // Z are the states, X the emissions // The VariableArray is over sites Z = new VariableArray<int>[numTimeSteps]; X = new VariableArray<int>[numTimeSteps]; for (int t = 0; t < numTimeSteps; t++) { Z[t] = Variable.Array<int>(Site_i).Named("Z" + t); X[t] = Variable.Array<int>(Site_i).Named("X" + t); } Z[0][Site_i] = Variable.DiscreteUniform(State_i); using (Variable.ForEach(Site_i)) using (Variable.Switch(Z[0][Site_i])) X[0][Site_i] = Variable.Discrete(C[Site_i][Z[0][Site_i]]); for (int t = 1; t < numTimeSteps; t++) { using (Variable.ForEach(Site_i)) { // Infuencing site is randomly chosen from the influence matrix var influencingSite = Variable.Discrete(Influence[Site_i]).Named("InfSite" + t); //influencingSite.SetValueRange(Site_j); // Switch on the influencing site using (Variable.Switch(influencingSite)) { // Switch on the influencing state // Must make a copy so we don't change Z's ValueRange var influencingState = Variable.Copy(Z[t - 1][influencingSite]).Named("InfState" + t); influencingState.SetValueRange(State_j); using (Variable.Switch(influencingState)) { // Switch on the current state Z[t][Site_i] = Variable.Discrete(A[Site_i][influencingSite][influencingState]); // Switch on the current state using (Variable.Switch(Z[t][Site_i])) { // Emission X[t][Site_i] = Variable.Discrete(C[Site_i][Z[t][Site_i]]); } } } } } } } /// <summary> /// Unrolled HMM with gated CPT. If 'coupled' and/or 'gated' are not defined /// this model compiles fine. If they are both defined, the scheduler chokes /// </summary> private class HMMWithGatedP { #if gated public Variable<bool> useScheme1; #endif // CPT for state transition scheme 1 public Variable<double> P1_z1T_cond_z1T; public Variable<double> P1_z1T_cond_z1F; public Variable<double> P1_z2T_cond_z2T; public Variable<double> P1_z2T_cond_z2F; // CPT for state transition scheme 2 public Variable<double> P2_z1T_cond_z1T; public Variable<double> P2_z1T_cond_z1F; #if coupled public Variable<double> P2_z2T_cond_z1T_z2T; public Variable<double> P2_z2T_cond_z1T_z2F; public Variable<double> P2_z2T_cond_z1F_z2T; public Variable<double> P2_z2T_cond_x1F_z2F; #else public Variable<double> P2_z2T_cond_z2T; public Variable<double> P2_z2T_cond_z2F; #endif // Emissions for the GP public Variable<double> R_x1T_cond_z1T; public Variable<double> R_x1T_cond_z1F; public Variable<double> R_x2T_cond_z2T; public Variable<double> R_x2T_cond_z2F; // State variables public Variable<bool>[] z1; public Variable<bool>[] z2; // Emission variables public Variable<bool>[] x1; public Variable<bool>[] x2; // Use EP for HMM for accuracy public InferenceEngine engine = new InferenceEngine(); public HMMWithGatedP(int numTimeSteps) { #if gated useScheme1 = Variable<bool>.Bernoulli(0.5).Named("useScheme1"); #endif // CPTs for state transition scheme1 P1_z1T_cond_z1T = Variable.Beta(1, 1).Named("P1_z1T_cond_z1T"); P1_z1T_cond_z1F = Variable.Beta(1, 1).Named("P1_z1T_cond_z1F"); P1_z2T_cond_z2T = Variable.Beta(1, 1).Named("P1_z2T_cond_z2T"); P1_z2T_cond_z2F = Variable.Beta(1, 1).Named("P1_z2T_cond_z2F"); P1_z1T_cond_z1T.ObservedValue = 0.5; P1_z1T_cond_z1F.ObservedValue = 0.5; P1_z2T_cond_z2T.ObservedValue = 0.5; P1_z2T_cond_z2F.ObservedValue = 0.5; // CPTs for state transition scheme2 P2_z1T_cond_z1T = Variable.Beta(1, 1).Named("P2_z1T_cond_z1T"); P2_z1T_cond_z1F = Variable.Beta(1, 1).Named("P2_z1T_cond_z1F"); P2_z1T_cond_z1T.ObservedValue = 0.5; P2_z1T_cond_z1F.ObservedValue = 0.5; #if coupled P2_z2T_cond_z1T_z2T = Variable.Beta(1, 1).Named("P2_z2T_cond_z1T_z2T"); P2_z2T_cond_z1T_z2F = Variable.Beta(1, 1).Named("P2_z2T_cond_z1T_z2F"); P2_z2T_cond_z1F_z2T = Variable.Beta(1, 1).Named("P2_z2T_cond_z1F_z2T"); P2_z2T_cond_x1F_z2F = Variable.Beta(1, 1).Named("P2_z2T_cond_x1F_z2F"); P2_z2T_cond_z1T_z2T.ObservedValue = 0.5; P2_z2T_cond_z1T_z2F.ObservedValue = 0.5; P2_z2T_cond_z1F_z2T.ObservedValue = 0.5; P2_z2T_cond_x1F_z2F.ObservedValue = 0.5; #else P2_z2T_cond_z2T = Variable.Beta(1, 1).Named("P2_z2T_cond_z2T"); P2_z2T_cond_z2F = Variable.Beta(1, 1).Named("P2_z2T_cond_z2F"); #endif // CPTs for GP emissions R_x1T_cond_z1T = Variable.Beta(1, 1).Named("R_x1T_cond_z1T"); R_x1T_cond_z1F = Variable.Beta(1, 1).Named("R_x1T_cond_z1F"); R_x2T_cond_z2T = Variable.Beta(1, 1).Named("R_x2T_cond_z2T"); R_x2T_cond_z2F = Variable.Beta(1, 1).Named("R_x2T_cond_z2F"); R_x1T_cond_z1T.ObservedValue = 0.5; R_x1T_cond_z1F.ObservedValue = 0.5; R_x2T_cond_z2T.ObservedValue = 0.5; //R_x2T_cond_z2F.ObservedValue = 0.5; z1 = new Variable<bool>[numTimeSteps]; z2 = new Variable<bool>[numTimeSteps]; x1 = new Variable<bool>[numTimeSteps]; x2 = new Variable<bool>[numTimeSteps]; for (int t = 0; t < numTimeSteps; t++) { z1[t] = Variable.New<bool>().Named("z1_" + t); //z1[t].InitialiseTo(new Bernoulli(0.5)); //if(t==0) z1[t].AddAttribute(new InitialiseBackward()); z2[t] = Variable.New<bool>().Named("z2_" + t); //z2[t].InitialiseTo(new Bernoulli(0.5)); //if(t==0) z2[t].AddAttribute(new InitialiseBackward()); x1[t] = Variable.New<bool>().Named("x1_" + t); x2[t] = Variable.New<bool>().Named("x2_" + t); } for (int t = 0; t < numTimeSteps; t++) { if (t == 0) { z1[t].SetTo(Variable.Bernoulli(.5)); z2[t].SetTo(Variable.Bernoulli(.5)); } else { #if gated using (Variable.If(useScheme1)) { FromSingleParent(z1[t], z1[t - 1], P1_z1T_cond_z1T, P1_z1T_cond_z1F); FromSingleParent(z2[t], z2[t - 1], P1_z2T_cond_z2T, P1_z2T_cond_z2F); } using (Variable.IfNot(useScheme1)) { #endif FromSingleParent(z1[t], z1[t - 1], P2_z1T_cond_z1T, P2_z1T_cond_z1F); #if coupled FromTwoParents(z2[t], z1[t - 1], z2[t - 1], P2_z2T_cond_z1T_z2T, P2_z2T_cond_z1T_z2F, P2_z2T_cond_z1F_z2T, P2_z2T_cond_x1F_z2F); #else FromSingleParent(z2[t], z2[t - 1], P2_z2T_cond_z2T, P2_z2T_cond_z2F); #endif #if gated } #endif } // Emissions FromSingleParent(x1[t], z1[t], R_x1T_cond_z1T, R_x1T_cond_z1F); FromSingleParent(x2[t], z2[t], R_x2T_cond_z2T, R_x2T_cond_z2F); } engine = new InferenceEngine(); engine.Compiler.ShowProgress = true; engine.ShowProgress = false; engine.Compiler.GivePriorityTo(typeof(ReplicateOp_NoDivide)); //engine.Compiler.OptimiseInferenceCode = false; } public void Train() { int numTimeSteps = z1.Length; for (int t = 0; t < numTimeSteps; t++) { x1[t].ObservedValue = true; x2[t].ObservedValue = true; } engine.NumberOfIterations = 1; // Variables to infer IList<IVariable> variablesToInfer = new List<IVariable>() { #if gated useScheme1, #endif P1_z1T_cond_z1T, P1_z1T_cond_z1F, P1_z2T_cond_z2T, P1_z2T_cond_z2F, P2_z1T_cond_z1T, P2_z1T_cond_z1F, #if coupled P2_z2T_cond_z1T_z2T, P2_z2T_cond_z1T_z2F, P2_z2T_cond_z1F_z2T, P2_z2T_cond_x1F_z2F, #else P2_z2T_cond_z2T, P2_z2T_cond_z2F, #endif R_x1T_cond_z1T, R_x1T_cond_z1F, }; for (int t = 0; t < numTimeSteps; t++) { variablesToInfer.Add(z1[t]); variablesToInfer.Add(z2[t]); } engine.GetCompiledInferenceAlgorithm(variablesToInfer.ToArray()); } public static T[][] Transpose<T>(T[][] array) { int numRows = array.Length; int numCols = array[0].Length; T[][] result = new T[numCols][]; for (int j = 0; j < numCols; j++) { result[j] = new T[numRows]; for (int i = 0; i < numRows; i++) { result[j][i] = array[i][j]; } } return result; } } [Fact] public void HMMWithGatedPTest() { // Fails because RepairSchedule causes schedule length to explode // seems related to KeepFresh (attached to cases arrays and selectors) //DependencyAnalysisTransform.KeepFresh = false; // numTimeSteps=2: schedule should have 84 nodes after repair //HMMWithGatedP model = new HMMWithGatedP(2); HMMWithGatedP model = new HMMWithGatedP(12); model.Train(); } private static void FromSingleParent( Variable<bool> result, Variable<bool> condition, Variable<double> condTrueProb, Variable<double> condFalseProb) { using (Variable.If(condition)) { result.SetTo(Variable.Bernoulli(condTrueProb)); } using (Variable.IfNot(condition)) { result.SetTo(Variable.Bernoulli(condFalseProb)); } } private static void FromTwoParents( Variable<bool> result, Variable<bool> condition1, Variable<bool> condition2, Variable<double> condTrueTrueProb, Variable<double> condTrueFalseProb, Variable<double> condFalseTrueProb, Variable<double> condFalseFalseProb) { using (Variable.If(condition1)) { using (Variable.If(condition2)) { result.SetTo(Variable.Bernoulli(condTrueTrueProb)); } using (Variable.IfNot(condition2)) { result.SetTo(Variable.Bernoulli(condTrueFalseProb)); } } using (Variable.IfNot(condition1)) { using (Variable.If(condition2)) { result.SetTo(Variable.Bernoulli(condFalseTrueProb)); } using (Variable.IfNot(condition2)) { result.SetTo(Variable.Bernoulli(condFalseFalseProb)); } } } [Fact] public void HMMWithObservationScore() { var numChildren = 2; var numClusters = 2; var numTimes = 2; var n = new Range(numChildren).Named("n"); var k = new Range(numClusters).Named("k"); var t = new Range(numTimes).Named("t"); var z = Variable.Array(Variable.Array<bool>(t), n).Named("z"); var x = Variable.Array(Variable.Array<bool>(t), n).Named("x"); var P_T = Variable.Array<double>(k).Named("PT"); var P_F = Variable.Array<double>(k).Named("PF"); P_T[k] = Variable.Beta(1, 1).ForEach(k); P_F[k] = Variable.Beta(1, 1).ForEach(k); var cluster = Variable.Array<int>(n).Named("cluster"); var mixingCoeffs = Variable.DirichletSymmetric(k, 0.1).Named("Pi"); using (Variable.ForEach(n)) { cluster[n] = Variable.Discrete(mixingCoeffs); using (Variable.Switch(cluster[n])) { using (ForEachBlock tBlock = Variable.ForEach(t)) { using (Variable.If(tBlock.Index == 0)) { z[n][tBlock.Index] = Variable.Bernoulli(0.5); } using (Variable.If(tBlock.Index > 0)) { FromSingleParent( z[n][tBlock.Index], z[n][tBlock.Index - 1], P_T[cluster[n]], P_F[cluster[n]]); } } } // Score-based observation model using (Variable.ForEach(t)) { using (Variable.If(z[n][t])) { x[n][t] = Variable.GaussianFromMeanAndPrecision(-1, 1.0).Named("scoreT") > 0; } using (Variable.IfNot(z[n][t])) { x[n][t] = Variable.GaussianFromMeanAndPrecision(1, 1.0).Named("scoreF") > 0; } } } var engine = new InferenceEngine(); // This prevents a serial schedule when UseSerialSchedules=true //engine.Compiler.GivePriorityTo(typeof (ReplicateOp_NoDivide)); x.ObservedValue = Util.ArrayInit(numChildren, i => Util.ArrayInit(numTimes, j => Bernoulli.Sample(0.5))); engine.Infer(z); } } }
42.739714
208
0.511758
[ "MIT" ]
0xflotus/infer
test/Tests/ModelTests.cs
194,252
C#
using DNTProfiler.Common.Models; using DNTProfiler.Infrastructure.Core; using DNTProfiler.Infrastructure.Models; using DNTProfiler.PluginsBase; namespace DNTProfiler.ContextInMultipleThreads.Core { public class CallbacksManager : CallbacksManagerBase { public CallbacksManager(ProfilerPluginBase pluginContext, GuiModelBase guiModelData) : base(pluginContext, guiModelData) { } public void CheckObjectContextsInMultipleThreads(Command item) { var context = GetContext(item); if (context == null) return; if (context.ManagedThreadId == item.ManagedThreadId) return; if (item.ApplicationIdentity.Equals(GuiModelData.SelectedApplicationIdentity)) { GuiModelData.RelatedCommands.Add(item); } GuiModelData.LocalCommands.Add(item); PluginContext.NotifyPluginsHost(NotificationType.Update, 1); UpdateAppIdentityNotificationsCount(item); } } }
32.363636
92
0.65824
[ "Apache-2.0" ]
Mohsenbahrzadeh/DNTProfiler
Plugins/DNTProfiler.ContextInMultipleThreads/Core/CallbacksManager.cs
1,070
C#
var count = 0; var searchColor = Color.FromName("SlateBlue"); for (var x = 0; x < pictureBox1.Image.Width; x++) { for (var y = 0; y < pictureBox1.Image.Height; y++) { Color pixelColor = pictureBox1.Image.GetPixel(x, y); if (pixelColor == searchColor) count++; } } //https://pt.stackoverflow.com/q/105693/101
30.272727
60
0.630631
[ "MIT" ]
Everton75/estudo
CSharp/Drawing/PixelCount.cs
333
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { static Program() { TestList = new Dictionary<string, Action>() { ["RoundToNearestScalar.Vector64.Double"] = RoundToNearestScalar_Vector64_Double, ["RoundToNearestScalar.Vector64.Single"] = RoundToNearestScalar_Vector64_Single, ["RoundToNegativeInfinity.Vector64.Single"] = RoundToNegativeInfinity_Vector64_Single, ["RoundToNegativeInfinity.Vector128.Single"] = RoundToNegativeInfinity_Vector128_Single, ["RoundToNegativeInfinityScalar.Vector64.Double"] = RoundToNegativeInfinityScalar_Vector64_Double, ["RoundToNegativeInfinityScalar.Vector64.Single"] = RoundToNegativeInfinityScalar_Vector64_Single, ["RoundToPositiveInfinity.Vector64.Single"] = RoundToPositiveInfinity_Vector64_Single, ["RoundToPositiveInfinity.Vector128.Single"] = RoundToPositiveInfinity_Vector128_Single, ["RoundToPositiveInfinityScalar.Vector64.Double"] = RoundToPositiveInfinityScalar_Vector64_Double, ["RoundToPositiveInfinityScalar.Vector64.Single"] = RoundToPositiveInfinityScalar_Vector64_Single, ["RoundToZero.Vector64.Single"] = RoundToZero_Vector64_Single, ["RoundToZero.Vector128.Single"] = RoundToZero_Vector128_Single, ["RoundToZeroScalar.Vector64.Double"] = RoundToZeroScalar_Vector64_Double, ["RoundToZeroScalar.Vector64.Single"] = RoundToZeroScalar_Vector64_Single, ["ShiftArithmetic.Vector64.Int16"] = ShiftArithmetic_Vector64_Int16, ["ShiftArithmetic.Vector64.Int32"] = ShiftArithmetic_Vector64_Int32, ["ShiftArithmetic.Vector64.SByte"] = ShiftArithmetic_Vector64_SByte, ["ShiftArithmetic.Vector128.Int16"] = ShiftArithmetic_Vector128_Int16, ["ShiftArithmetic.Vector128.Int32"] = ShiftArithmetic_Vector128_Int32, ["ShiftArithmetic.Vector128.Int64"] = ShiftArithmetic_Vector128_Int64, ["ShiftArithmetic.Vector128.SByte"] = ShiftArithmetic_Vector128_SByte, ["ShiftArithmeticRounded.Vector64.Int16"] = ShiftArithmeticRounded_Vector64_Int16, ["ShiftArithmeticRounded.Vector64.Int32"] = ShiftArithmeticRounded_Vector64_Int32, ["ShiftArithmeticRounded.Vector64.SByte"] = ShiftArithmeticRounded_Vector64_SByte, ["ShiftArithmeticRounded.Vector128.Int16"] = ShiftArithmeticRounded_Vector128_Int16, ["ShiftArithmeticRounded.Vector128.Int32"] = ShiftArithmeticRounded_Vector128_Int32, ["ShiftArithmeticRounded.Vector128.Int64"] = ShiftArithmeticRounded_Vector128_Int64, ["ShiftArithmeticRounded.Vector128.SByte"] = ShiftArithmeticRounded_Vector128_SByte, ["ShiftArithmeticRoundedSaturate.Vector64.Int16"] = ShiftArithmeticRoundedSaturate_Vector64_Int16, ["ShiftArithmeticRoundedSaturate.Vector64.Int32"] = ShiftArithmeticRoundedSaturate_Vector64_Int32, ["ShiftArithmeticRoundedSaturate.Vector64.SByte"] = ShiftArithmeticRoundedSaturate_Vector64_SByte, ["ShiftArithmeticRoundedSaturate.Vector128.Int16"] = ShiftArithmeticRoundedSaturate_Vector128_Int16, ["ShiftArithmeticRoundedSaturate.Vector128.Int32"] = ShiftArithmeticRoundedSaturate_Vector128_Int32, ["ShiftArithmeticRoundedSaturate.Vector128.Int64"] = ShiftArithmeticRoundedSaturate_Vector128_Int64, ["ShiftArithmeticRoundedSaturate.Vector128.SByte"] = ShiftArithmeticRoundedSaturate_Vector128_SByte, ["ShiftArithmeticRoundedSaturateScalar.Vector64.Int64"] = ShiftArithmeticRoundedSaturateScalar_Vector64_Int64, ["ShiftArithmeticRoundedScalar.Vector64.Int64"] = ShiftArithmeticRoundedScalar_Vector64_Int64, ["ShiftArithmeticSaturate.Vector64.Int16"] = ShiftArithmeticSaturate_Vector64_Int16, ["ShiftArithmeticSaturate.Vector64.Int32"] = ShiftArithmeticSaturate_Vector64_Int32, ["ShiftArithmeticSaturate.Vector64.SByte"] = ShiftArithmeticSaturate_Vector64_SByte, ["ShiftArithmeticSaturate.Vector128.Int16"] = ShiftArithmeticSaturate_Vector128_Int16, ["ShiftArithmeticSaturate.Vector128.Int32"] = ShiftArithmeticSaturate_Vector128_Int32, ["ShiftArithmeticSaturate.Vector128.Int64"] = ShiftArithmeticSaturate_Vector128_Int64, ["ShiftArithmeticSaturate.Vector128.SByte"] = ShiftArithmeticSaturate_Vector128_SByte, ["ShiftArithmeticSaturateScalar.Vector64.Int64"] = ShiftArithmeticSaturateScalar_Vector64_Int64, ["ShiftArithmeticScalar.Vector64.Int64"] = ShiftArithmeticScalar_Vector64_Int64, ["ShiftLeftAndInsert.Vector64.Byte"] = ShiftLeftAndInsert_Vector64_Byte, ["ShiftLeftAndInsert.Vector64.Int16"] = ShiftLeftAndInsert_Vector64_Int16, ["ShiftLeftAndInsert.Vector64.Int32"] = ShiftLeftAndInsert_Vector64_Int32, ["ShiftLeftAndInsert.Vector64.SByte"] = ShiftLeftAndInsert_Vector64_SByte, ["ShiftLeftAndInsert.Vector64.UInt16"] = ShiftLeftAndInsert_Vector64_UInt16, ["ShiftLeftAndInsert.Vector64.UInt32"] = ShiftLeftAndInsert_Vector64_UInt32, ["ShiftLeftAndInsert.Vector128.Byte"] = ShiftLeftAndInsert_Vector128_Byte, ["ShiftLeftAndInsert.Vector128.Int16"] = ShiftLeftAndInsert_Vector128_Int16, ["ShiftLeftAndInsert.Vector128.Int32"] = ShiftLeftAndInsert_Vector128_Int32, ["ShiftLeftAndInsert.Vector128.Int64"] = ShiftLeftAndInsert_Vector128_Int64, ["ShiftLeftAndInsert.Vector128.SByte"] = ShiftLeftAndInsert_Vector128_SByte, ["ShiftLeftAndInsert.Vector128.UInt16"] = ShiftLeftAndInsert_Vector128_UInt16, ["ShiftLeftAndInsert.Vector128.UInt32"] = ShiftLeftAndInsert_Vector128_UInt32, ["ShiftLeftAndInsert.Vector128.UInt64"] = ShiftLeftAndInsert_Vector128_UInt64, ["ShiftLeftAndInsertScalar.Vector64.Int64"] = ShiftLeftAndInsertScalar_Vector64_Int64, ["ShiftLeftAndInsertScalar.Vector64.UInt64"] = ShiftLeftAndInsertScalar_Vector64_UInt64, ["ShiftLeftLogical.Vector64.Byte.1"] = ShiftLeftLogical_Vector64_Byte_1, ["ShiftLeftLogical.Vector64.Int16.1"] = ShiftLeftLogical_Vector64_Int16_1, ["ShiftLeftLogical.Vector64.Int32.1"] = ShiftLeftLogical_Vector64_Int32_1, ["ShiftLeftLogical.Vector64.SByte.1"] = ShiftLeftLogical_Vector64_SByte_1, ["ShiftLeftLogical.Vector64.UInt16.1"] = ShiftLeftLogical_Vector64_UInt16_1, ["ShiftLeftLogical.Vector64.UInt32.1"] = ShiftLeftLogical_Vector64_UInt32_1, ["ShiftLeftLogical.Vector128.Byte.1"] = ShiftLeftLogical_Vector128_Byte_1, ["ShiftLeftLogical.Vector128.Int16.1"] = ShiftLeftLogical_Vector128_Int16_1, ["ShiftLeftLogical.Vector128.Int64.1"] = ShiftLeftLogical_Vector128_Int64_1, ["ShiftLeftLogical.Vector128.SByte.1"] = ShiftLeftLogical_Vector128_SByte_1, ["ShiftLeftLogical.Vector128.UInt16.1"] = ShiftLeftLogical_Vector128_UInt16_1, ["ShiftLeftLogical.Vector128.UInt32.1"] = ShiftLeftLogical_Vector128_UInt32_1, ["ShiftLeftLogical.Vector128.UInt64.1"] = ShiftLeftLogical_Vector128_UInt64_1, ["ShiftLeftLogicalSaturate.Vector64.Byte.1"] = ShiftLeftLogicalSaturate_Vector64_Byte_1, ["ShiftLeftLogicalSaturate.Vector64.Int16.1"] = ShiftLeftLogicalSaturate_Vector64_Int16_1, ["ShiftLeftLogicalSaturate.Vector64.Int32.1"] = ShiftLeftLogicalSaturate_Vector64_Int32_1, ["ShiftLeftLogicalSaturate.Vector64.SByte.1"] = ShiftLeftLogicalSaturate_Vector64_SByte_1, ["ShiftLeftLogicalSaturate.Vector64.UInt16.1"] = ShiftLeftLogicalSaturate_Vector64_UInt16_1, ["ShiftLeftLogicalSaturate.Vector64.UInt32.1"] = ShiftLeftLogicalSaturate_Vector64_UInt32_1, ["ShiftLeftLogicalSaturate.Vector128.Byte.1"] = ShiftLeftLogicalSaturate_Vector128_Byte_1, ["ShiftLeftLogicalSaturate.Vector128.Int16.1"] = ShiftLeftLogicalSaturate_Vector128_Int16_1, ["ShiftLeftLogicalSaturate.Vector128.Int32.1"] = ShiftLeftLogicalSaturate_Vector128_Int32_1, ["ShiftLeftLogicalSaturate.Vector128.Int64.1"] = ShiftLeftLogicalSaturate_Vector128_Int64_1, ["ShiftLeftLogicalSaturate.Vector128.SByte.1"] = ShiftLeftLogicalSaturate_Vector128_SByte_1, ["ShiftLeftLogicalSaturate.Vector128.UInt16.1"] = ShiftLeftLogicalSaturate_Vector128_UInt16_1, ["ShiftLeftLogicalSaturate.Vector128.UInt32.1"] = ShiftLeftLogicalSaturate_Vector128_UInt32_1, ["ShiftLeftLogicalSaturate.Vector128.UInt64.1"] = ShiftLeftLogicalSaturate_Vector128_UInt64_1, ["ShiftLeftLogicalSaturateScalar.Vector64.Int64.1"] = ShiftLeftLogicalSaturateScalar_Vector64_Int64_1, ["ShiftLeftLogicalSaturateScalar.Vector64.UInt64.1"] = ShiftLeftLogicalSaturateScalar_Vector64_UInt64_1, ["ShiftLeftLogicalSaturateUnsigned.Vector64.Int16.1"] = ShiftLeftLogicalSaturateUnsigned_Vector64_Int16_1, ["ShiftLeftLogicalSaturateUnsigned.Vector64.Int32.1"] = ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1, ["ShiftLeftLogicalSaturateUnsigned.Vector64.SByte.1"] = ShiftLeftLogicalSaturateUnsigned_Vector64_SByte_1, ["ShiftLeftLogicalSaturateUnsigned.Vector128.Int16.1"] = ShiftLeftLogicalSaturateUnsigned_Vector128_Int16_1, ["ShiftLeftLogicalSaturateUnsigned.Vector128.Int32.1"] = ShiftLeftLogicalSaturateUnsigned_Vector128_Int32_1, ["ShiftLeftLogicalSaturateUnsigned.Vector128.Int64.1"] = ShiftLeftLogicalSaturateUnsigned_Vector128_Int64_1, ["ShiftLeftLogicalSaturateUnsigned.Vector128.SByte.1"] = ShiftLeftLogicalSaturateUnsigned_Vector128_SByte_1, ["ShiftLeftLogicalSaturateUnsignedScalar.Vector64.Int64.1"] = ShiftLeftLogicalSaturateUnsignedScalar_Vector64_Int64_1, ["ShiftLeftLogicalScalar.Vector64.Int64.1"] = ShiftLeftLogicalScalar_Vector64_Int64_1, }; } } }
90.372881
134
0.729839
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Program.AdvSimd_Part11.cs
10,664
C#
using AzureKit.Data; using AzureKit.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace AzureKit.Tests.Data { public class InMemorySiteMapRepository : ISiteMapRepository { private SiteMap _map; public InMemorySiteMapRepository() { _map = new SiteMap(); _map.Entries = new List<SiteMapEntry>(); } public Task AddItemToSiteMapAsync(SiteMapEntry newEntry) { _map.Entries.Add(newEntry); return Task.CompletedTask; } public Task<SiteMap> GetMapAsync() { return Task.FromResult<SiteMap>(_map); } public Task<bool> IsItemInSiteMapAsync(string contentIdentifier) { bool found = _map.Entries.Find( (e) => e.ContentIdentifier == contentIdentifier) != null; return Task.FromResult<bool>(found); } public Task RemoveItemFromSiteMapAsync(string entryToRemove) { _map.Entries.RemoveAll((sme) => sme.ContentIdentifier == entryToRemove); return Task.CompletedTask; } } }
26.883721
84
0.607266
[ "MIT" ]
Azure-Samples/azure-solutions-digital-marketing-reference-implementation
src/AzureKit/AzureKit.Tests/Data/InMemorySiteMapRepository.cs
1,158
C#
/* * Copyright 2015-2018 Mohawk College of Applied Arts and Technology * * * 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. * * User: fyfej * Date: 2017-9-1 */ using OpenIZ.Core.Model.Acts; using OpenIZ.Persistence.Data.MSSQL.Data; using System.Linq; using System.Security.Principal; namespace OpenIZ.Persistence.Data.MSSQL.Services.Persistence { /// <summary> /// Control act persistence service /// </summary> public class ControlActPersistenceService : ActDerivedPersistenceService<Core.Model.Acts.ControlAct, Data.ControlAct> { /// <summary> /// Convert to model instance /// </summary> public override Core.Model.Acts.ControlAct ToModelInstance(object dataInstance, ModelDataContext context, IPrincipal principal) { var iddat = dataInstance as IDbIdentified; var controlAct = dataInstance as Data.ControlAct ?? context.GetTable<Data.ControlAct>().Where(o => o.ActVersionId == iddat.Id).First(); var dba = dataInstance as Data.ActVersion ?? context.GetTable<Data.ActVersion>().Where(a => a.ActVersionId == controlAct.ActVersionId).First(); // TODO: Any other cact fields return m_actPersister.ToModelInstance<Core.Model.Acts.ControlAct>(dba, context, principal); } } }
41.477273
155
0.70411
[ "Apache-2.0" ]
santedb/openiz
OpenIZ.Persistence.Data.MSSQL/Services/Persistence/ControlActPersistenceService.cs
1,827
C#
using System; using System.ComponentModel; namespace MsSystem.Web.Areas.OA.ViewModel { public class OaLeaveDto { public int Id { get; set; } public string LeaveCode { get; set; } /// <summary> /// 标题 /// </summary> public string Title { get; set; } /// <summary> /// 请假人 /// </summary> public int UserId { get; set; } public string UserName { get; set; } /// <summary> /// 创建时间 /// </summary> public long CreateTime { get; set; } /// <summary> /// 流程状态 /// </summary> public int FlowStatus { get; set; } } public class OaLeaveShowDto { public int Id { get; set; } /// <summary> /// 请假编号 /// </summary> public string LeaveCode { get; set; } /// <summary> /// 标题 /// </summary> public string Title { get; set; } /// <summary> /// 请假人 /// </summary> public int UserId { get; set; } /// <summary> /// 工作代理人 /// </summary> public int AgentId { get; set; } /// <summary> /// 请假类型 /// </summary> public byte LeaveType { get; set; } /// <summary> /// 请假原因 /// </summary> public string Reason { get; set; } /// <summary> /// 请假天数 /// </summary> public int Days { get; set; } /// <summary> /// 开始时间 /// </summary> public DateTime StartTime { get; set; } /// <summary> /// 结束时间 /// </summary> public DateTime EndTime { get; set; } /// <summary> /// 创建人 /// </summary> public int CreateUserId { get; set; } /// <summary> /// 创建时间 /// </summary> public long CreateTime { get; set; } } /// <summary> /// 请假类型 /// </summary> public enum OaLeaveType { [Description("事假")] CompassionateLeave = 0, [Description("病假")] SickLeave = 1, [Description("年假")] AnnualLeave = 2, [Description("婚假")] MarriageLeave = 3, [Description("产假/陪产假")] MaternityLeave = 4, [Description("丧假")] FuneralLeave = 5, [Description("探亲假")] FamilyLeave = 6, } }
21.621622
47
0.442917
[ "MIT" ]
SpoonySeedLSP/BPM-ServiceAndWebApps
src/Web/MVC/Controllers/MsSystem.Web.Areas.OA/ViewModel/OaLeaveDto.cs
2,554
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Ytg.Comm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Ytg.Comm")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("5b268360-1a1a-4636-a581-7b465fbb54c9")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.432432
56
0.710946
[ "Apache-2.0" ]
heqinghua/lottery-code-qq-814788821-
YtgProject/Ytg.Comm/Properties/AssemblyInfo.cs
1,300
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace prooram.Application.CategoryMediatr.Queries { using MediatR; using prooram.Application.CategoryMediatr.DTO; public class GetCategoryQuery : IRequest<EditCategoryDTO> { public Guid Id { get; set; } public string CategoryName { get; set; } } }
22.611111
61
0.724816
[ "Unlicense" ]
ysfbzkrba/prooram
src/Application/CategoryMediatr/Queries/GetCategoryQuery.cs
409
C#
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System.IO; using System.Xml; using System.Text; using Amazon.S3.Util; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Util; #pragma warning disable 1591 namespace Amazon.S3.Model.Internal.MarshallTransformations { /// <summary> /// Put Buckeyt Replication Request Marshaller /// </summary> public class PutBucketReplicationRequestMarshaller : IMarshaller<IRequest, PutBucketReplicationRequest>, IMarshaller<IRequest, Amazon.Runtime.AmazonWebServiceRequest> { public IRequest Marshall(Amazon.Runtime.AmazonWebServiceRequest input) { return this.Marshall((PutBucketReplicationRequest)input); } public IRequest Marshall(PutBucketReplicationRequest putBucketreplicationRequest) { IRequest request = new DefaultRequest(putBucketreplicationRequest, "AmazonS3"); request.HttpMethod = "PUT"; request.ResourcePath = string.Concat("/", S3Transforms.ToStringValue(putBucketreplicationRequest.BucketName)); request.AddSubResource("replication"); var stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Encoding = Encoding.UTF8, OmitXmlDeclaration = true })) { var replicationConfiguration = putBucketreplicationRequest.Configuration; if (replicationConfiguration != null) { xmlWriter.WriteStartElement("ReplicationConfiguration", ""); if (replicationConfiguration.Role != null) { xmlWriter.WriteElementString("Role", "", S3Transforms.ToXmlStringValue(replicationConfiguration.Role)); } if (replicationConfiguration.Rules != null) { foreach (var rule in replicationConfiguration.Rules) { xmlWriter.WriteStartElement("Rule"); if (rule.IsSetId()) { xmlWriter.WriteElementString("ID", "", S3Transforms.ToXmlStringValue(rule.Id)); } if (rule.IsSetPrefix()) { xmlWriter.WriteElementString("Prefix", "", S3Transforms.ToXmlStringValue(rule.Prefix)); } else // Write an empty Prefix tag { xmlWriter.WriteElementString("Prefix", "", S3Transforms.ToXmlStringValue("")); } if (rule.IsSetStatus()) { xmlWriter.WriteElementString("Status", "", S3Transforms.ToXmlStringValue(rule.Status.ToString())); } if (rule.IsSetSourceSelectionCriteria()) { xmlWriter.WriteStartElement("SourceSelectionCriteria"); if (rule.SourceSelectionCriteria.IsSetSseKmsEncryptedObjects()) { xmlWriter.WriteStartElement("SseKmsEncryptedObjects"); if (rule.SourceSelectionCriteria.SseKmsEncryptedObjects.IsSetSseKmsEncryptedObjectsStatus()) { xmlWriter.WriteElementString("Status", "", rule.SourceSelectionCriteria.SseKmsEncryptedObjects.SseKmsEncryptedObjectsStatus); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (rule.IsSetDestination()) { xmlWriter.WriteStartElement("Destination", ""); if (rule.Destination.IsSetBucketArn()) { xmlWriter.WriteElementString("Bucket", "", rule.Destination.BucketArn); } if (rule.Destination.IsSetStorageClass()) { xmlWriter.WriteElementString("StorageClass", "", rule.Destination.StorageClass); } if (rule.Destination.IsSetAccountId()) { xmlWriter.WriteElementString("Account", "", S3Transforms.ToXmlStringValue(rule.Destination.AccountId)); } if (rule.Destination.IsSetEncryptionConfiguration()) { xmlWriter.WriteStartElement("EncryptionConfiguration"); if (rule.Destination.EncryptionConfiguration.isSetReplicaKmsKeyID()) { xmlWriter.WriteElementString("ReplicaKmsKeyID", "", S3Transforms.ToXmlStringValue(rule.Destination.EncryptionConfiguration.ReplicaKmsKeyID)); } xmlWriter.WriteEndElement(); } if (rule.Destination.IsSetAccessControlTranslation()) { xmlWriter.WriteStartElement("AccessControlTranslation"); if (rule.Destination.AccessControlTranslation.IsSetOwner()) { xmlWriter.WriteElementString("Owner", "", S3Transforms.ToXmlStringValue(rule.Destination.AccessControlTranslation.Owner)); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } } try { var content = stringWriter.ToString(); request.Content = Encoding.UTF8.GetBytes(content); request.Headers[HeaderKeys.ContentTypeHeader] = "application/xml"; var checksum = AmazonS3Util.GenerateChecksumForContent(content, true); request.Headers[HeaderKeys.ContentMD5Header] = checksum; } catch (EncoderFallbackException e) { throw new AmazonServiceException("Unable to marshall request to XML", e); } return request; } } }
47.348101
177
0.527603
[ "Apache-2.0" ]
Murcho/aws-sdk-net
sdk/src/Services/S3/Custom/Model/Internal/MarshallTransformations/PutBucketReplicationRequestMarshaller.cs
7,483
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Data.Models { public class Store { public int Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } public ICollection<ProductStoreQuantity> Quantities = new HashSet<ProductStoreQuantity>(); } }
21.352941
98
0.658402
[ "MIT" ]
mkpetrov/Balkanton
Data/Models/Store.cs
365
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DbFirstNorthwind.ConsoleClient.Data { using System; using System.Collections.Generic; public partial class Products_by_Category { public string CategoryName { get; set; } public string ProductName { get; set; } public string QuantityPerUnit { get; set; } public Nullable<short> UnitsInStock { get; set; } public bool Discontinued { get; set; } } }
35.291667
85
0.547816
[ "MIT" ]
pavelhristov/CSharpDatabases
EntityFramework/DbFirstNorthwind.ConsoleClient/Data/Products_by_Category.cs
847
C#
using Microsoft.Management.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using SimCim.Core; namespace SimCim.Root.V2 { public class Win32RoamingProfileSlowLinkParams : GenericInfrastructureObject { public Win32RoamingProfileSlowLinkParams() { } public Win32RoamingProfileSlowLinkParams(IInfrastructureObjectScope scope, CimInstance instance): base(scope, instance) { } public System.UInt32? ConnectionTransferRate { get { System.UInt32? result; this.GetProperty("ConnectionTransferRate", out result); return result; } set { this.SetProperty("ConnectionTransferRate", value); } } public System.UInt16? TimeOut { get { System.UInt16? result; this.GetProperty("TimeOut", out result); return result; } set { this.SetProperty("TimeOut", value); } } } }
24.877551
128
0.515176
[ "Apache-2.0" ]
simonferquel/simcim
SimCim.Root.V2/ClassWin32RoamingProfileSlowLinkParams.cs
1,221
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Nano.Services")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Nano.Services")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3708a0a9-055f-46fb-916b-62695a72e806")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.810811
84
0.744103
[ "MIT" ]
contactsamie/nano
src/Nano/Nano.Services/Properties/AssemblyInfo.cs
1,402
C#
using System; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using ACT.UltraScouter.Models.FFLogs; using FFXIV.Framework.Common; namespace FFLogsRankingDonwloader { public static class Program { static Program() { CosturaUtility.Initialize(); AssemblyResolver.Instance.Initialize(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Main( string[] args) { // ダミーで FFXIV.Framework を読み込む var span = CommonHelper.GetRandomTimeSpan(0.25); if (args == null || args.Length < 2) { return; } var apiKey = args[0]; var fileName = args[1]; var isOnlyHistogram = args.Length >= 3 ? bool.Parse(args[2]) : false; var targetZoneID = args.Length >= 4 ? int.Parse(args[3]) : 0; StatisticsDatabase.Instance.APIKey = apiKey; if (!isOnlyHistogram) { StatisticsDatabase.Instance.CreateAsync(fileName, targetZoneID).Wait(); Console.WriteLine($"[FFLogs] rankings downloaded."); } StatisticsDatabase.Instance.CreateHistogramAsync(fileName).Wait(); Console.WriteLine($"[FFLogs] histgram analyzed."); File.WriteAllLines( $"{fileName}.timestamp.txt", new[] { DateTime.Now.ToString() }, new UTF8Encoding(false)); Console.WriteLine($"[FFLogs] database completed. save to {fileName}."); Thread.Sleep(span); Environment.Exit(0); } } }
29.733333
88
0.54148
[ "BSD-3-Clause" ]
nodchip/ACT.Hojoring
source/FFLogsRankingDonwloader/Program.cs
1,802
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02 Odd Occurrences")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02 Odd Occurrences")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("980bee27-c8d8-4dc3-b81d-b7a16ca3d4b5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.7445
[ "MIT" ]
martinmihov/Programming-Fundamentals
Dictionaries,Lambda and LINQ/02 Odd Occurrences/Properties/AssemblyInfo.cs
1,412
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime: 4.0.30319.17929 // // Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si // el código se vuelve a generar. // </auto-generated> //------------------------------------------------------------------------------ namespace C_Hello_World.Properties { /// <summary> /// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc. /// </summary> // StronglyTypedResourceBuilder generó automáticamente esta clase // a través de una herramienta como ResGen o Visual Studio. // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen // con la opción /str o recompile su proyecto de VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("C_Hello_World.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Invalida la propiedad CurrentUICulture del subproceso actual para todas las /// búsquedas de recursos usando esta clase de recursos fuertemente tipados. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
40.444444
179
0.617102
[ "MIT" ]
m1guelpf/vs-hello-world
C-Hello-World/Properties/Resources.Designer.cs
2,925
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Diagnostics; using Microsoft.Azure.WebJobs.Script.Config; using Microsoft.Azure.WebJobs.Script.Eventing; using Microsoft.Azure.WebJobs.Script.Workers; using Microsoft.Azure.WebJobs.Script.Workers.Http; using Microsoft.Extensions.Logging; using Moq; using Xunit; namespace Microsoft.Azure.WebJobs.Script.Tests.Workers.Http { public class HttpWorkerProcessTests { private const string _testWorkerId = "testId"; private const string _rootScriptPath = "c:\\testDir"; private const int _workerPort = 8090; private readonly ScriptSettingsManager _settingsManager; private readonly Mock<IScriptEventManager> _mockEventManager = new Mock<IScriptEventManager>(); private readonly IWorkerProcessFactory _defaultWorkerProcessFactory = new DefaultWorkerProcessFactory(new TestEnvironment(), new LoggerFactory()); private readonly IProcessRegistry _processRegistry = new EmptyProcessRegistry(); private readonly Mock<IWorkerConsoleLogSource> _languageWorkerConsoleLogSource = new Mock<IWorkerConsoleLogSource>(); private readonly TestLogger _testLogger = new TestLogger("test"); private readonly HttpWorkerOptions _httpWorkerOptions; private readonly Mock<IServiceProvider> _serviceProviderMock; public HttpWorkerProcessTests() { _httpWorkerOptions = new HttpWorkerOptions() { Port = _workerPort, Arguments = new WorkerProcessArguments() { ExecutablePath = "test" }, Description = new HttpWorkerDescription() { WorkingDirectory = @"c:\testDir" } }; _settingsManager = ScriptSettingsManager.Instance; _serviceProviderMock = new Mock<IServiceProvider>(MockBehavior.Strict); } [Theory] [InlineData("9000")] [InlineData("")] [InlineData(null)] public void CreateWorkerProcess_VerifyEnvVars(string processEnvValue) { using (new TestScopedSettings(_settingsManager, HttpWorkerConstants.PortEnvVarName, processEnvValue)) { if (!string.IsNullOrEmpty(processEnvValue)) { Assert.Equal(Environment.GetEnvironmentVariable(HttpWorkerConstants.PortEnvVarName), processEnvValue); } HttpWorkerProcess httpWorkerProcess = new HttpWorkerProcess(_testWorkerId, _rootScriptPath, _httpWorkerOptions, _mockEventManager.Object, _defaultWorkerProcessFactory, _processRegistry, _testLogger, _languageWorkerConsoleLogSource.Object, new TestEnvironment(), new TestMetricsLogger(), _serviceProviderMock.Object); Process childProcess = httpWorkerProcess.CreateWorkerProcess(); Assert.NotNull(childProcess.StartInfo.EnvironmentVariables); Assert.Equal(childProcess.StartInfo.EnvironmentVariables[HttpWorkerConstants.PortEnvVarName], _workerPort.ToString()); Assert.Equal(childProcess.StartInfo.EnvironmentVariables[HttpWorkerConstants.WorkerIdEnvVarName], _testWorkerId); Assert.Equal(childProcess.StartInfo.EnvironmentVariables[HttpWorkerConstants.CustomHandlerPortEnvVarName], _workerPort.ToString()); Assert.Equal(childProcess.StartInfo.EnvironmentVariables[HttpWorkerConstants.CustomHandlerWorkerIdEnvVarName], _testWorkerId); childProcess.Dispose(); } } [Fact] public void CreateWorkerProcess_LinuxConsumption_AssingnsExecutePermissions_invoked() { TestEnvironment testEnvironment = new TestEnvironment(); testEnvironment.SetEnvironmentVariable(EnvironmentSettingNames.ContainerName, "TestContainer"); var mockHttpWorkerProcess = new HttpWorkerProcess(_testWorkerId, _rootScriptPath, _httpWorkerOptions, _mockEventManager.Object, _defaultWorkerProcessFactory, _processRegistry, _testLogger, _languageWorkerConsoleLogSource.Object, testEnvironment, new TestMetricsLogger(), _serviceProviderMock.Object); mockHttpWorkerProcess.CreateWorkerProcess(); // Verify method invocation var testLogs = _testLogger.GetLogMessages(); Assert.Contains("Error while assigning execute permission", testLogs[0].FormattedMessage); } } }
56.875
332
0.718681
[ "Apache-2.0", "MIT" ]
Azure/azure-functions-host
test/WebJobs.Script.Tests/Workers/Http/HttpWorkerProcessTests.cs
4,552
C#
using Chloe; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WaterCloud.Code; using WaterCloud.Domain.Entity.ProductionManage; namespace WaterCloud.Service.ProductionManage { public class MQDesignChangeDetailsService : DataFilterService<MQDesignChangeDetailsEntity>, IDenpendency { public MQDesignChangeDetailsService(IDbContext context) : base(context) { } public async Task<List<MQDesignChangeDetailsEntity>> GetList(Pagination pagination, string keyvalue) { ////获取数据权限 //var list = GetDataPrivilege("u", className.Substring(0, className.Length - 7)); //list = list.Where(t => t.IsEffective == 1); //return GetFieldsFilterData(await repository.OrderList(list, pagination), className.Substring(0, className.Length - 7)); var list = repository.IQueryable(); if (!string.IsNullOrEmpty(keyvalue)) { DateTime startTime = keyvalue.Substring(0, 10).ToDate(); DateTime endTime = keyvalue.Remove(0, 13).ToDate(); list = list.Where(t => t.DCTime >= startTime && t.DCTime <= endTime); } list = list.Where(t => t.IsEffective == 1); return await repository.OrderList(list, pagination); } } }
36.526316
133
0.644813
[ "MIT" ]
jl632541832/WaterCloudCore
WaterCloud.Service/ProductionManage/MQDesignChangeDetailsService.cs
1,402
C#
 namespace Hspi { /// <summary> /// Class for the main program. /// </summary> public static class Program { /// <summary> /// The homeseer server address. Defaults to the local computer but can be changed through the command line argument, server=address. /// </summary> private static string serverAddress = "192.168.10.20"; private const int serverPort = 10400; /// <summary> /// Defines the entry point of the application. /// </summary> /// <param name="args">Command line arguments</param> private static void Main(string[] args) { // parse command line arguments foreach (string sCmd in args) { string[] parts = sCmd.Split('='); switch (parts[0].ToUpperInvariant()) { case "SERVER": serverAddress = parts[1]; break; } } using (var plugin = new HSPI_TwilioMessaging.HSPI()) { plugin.Connect(serverAddress, serverPort); plugin.WaitforShutDownOrDisconnect(); } } } }
30.317073
142
0.502816
[ "MIT" ]
andrewoke/HSPI_TwilioMessaging
src/Program.cs
1,245
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace BellumGens.Api.Models { public class Application { public string Message { get; set; } public NotificationState State { get; set; } [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public DateTimeOffset? Sent { get; set; } } }
21.833333
55
0.768448
[ "MIT" ]
BellumGens/bellum-gens-api
BellumGens.Api/Models/Application.cs
395
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace Microsoft.MixedReality.Toolkit.Editor { /// <summary> /// Base class for all Mixed Reality Toolkit specific <see cref="Microsoft.MixedReality.Toolkit.BaseMixedRealityProfile"/> inspectors to inherit from. /// </summary> public abstract class BaseMixedRealityToolkitConfigurationProfileInspector : BaseMixedRealityProfileInspector { public bool RenderAsSubProfile { get; set; } [SerializeField] private Texture2D logoLightTheme = null; [SerializeField] private Texture2D logoDarkTheme = null; [SerializeField] private static Texture helpIcon = null; private static GUIContent WarningIconContent = null; /// <summary> /// Internal enum used for back navigation along profile hiearchy. /// Indicates what type of parent profile the current profile will return to for going back /// </summary> protected enum BackProfileType { Configuration, Input, RegisteredServices }; protected virtual void Awake() { string assetPath = "StandardAssets/Textures"; if (logoLightTheme == null) { logoLightTheme = (Texture2D)AssetDatabase.LoadAssetAtPath(MixedRealityToolkitFiles.MapRelativeFilePath($"{assetPath}/MRTK_Logo_Black.png"), typeof(Texture2D)); } if (logoDarkTheme == null) { logoDarkTheme = (Texture2D)AssetDatabase.LoadAssetAtPath(MixedRealityToolkitFiles.MapRelativeFilePath($"{assetPath}/MRTK_Logo_White.png"), typeof(Texture2D)); } if (helpIcon == null) { helpIcon = EditorGUIUtility.IconContent("_Help").image; } if (WarningIconContent == null) { WarningIconContent = new GUIContent(EditorGUIUtility.IconContent("console.warnicon").image, "This profile is part of the default set from the Mixed Reality Toolkit SDK. You can make a copy of this profile, and customize it if needed."); } } /// <summary> /// Render the Mixed Reality Toolkit Logo. /// </summary> protected void RenderMixedRealityToolkitLogo() { // If we're being rendered as a sub profile, don't show the logo if (RenderAsSubProfile) { return; } GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label(EditorGUIUtility.isProSkin ? logoDarkTheme : logoLightTheme, GUILayout.MaxHeight(96f)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(3f); } protected bool DrawBacktrackProfileButton(BackProfileType returnProfileTarget = BackProfileType.Configuration) { string backText = string.Empty; BaseMixedRealityProfile backProfile = null; switch (returnProfileTarget) { case BackProfileType.Configuration: backText = "Back to Configuration Profile"; backProfile = MixedRealityToolkit.Instance.ActiveProfile; break; case BackProfileType.Input: backText = "Back to Input Profile"; backProfile = MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile; break; case BackProfileType.RegisteredServices: backText = "Back to Registered Service Providers Profile"; backProfile = MixedRealityToolkit.Instance.ActiveProfile.RegisteredServiceProvidersProfile; break; } return DrawBacktrackProfileButton(backText, backProfile); } /// <summary> /// Renders a button that will take user back to a specified profile object /// </summary> /// <param name="message"></param> /// <param name="activeObject"></param> /// <returns>True if button was clicked</returns> protected bool DrawBacktrackProfileButton(string message, UnityEngine.Object activeObject) { // If we're being rendered as a sub profile, don't show the button if (RenderAsSubProfile) { return false; } if (GUILayout.Button(message)) { Selection.activeObject = activeObject; return true; } return false; } /// <summary> /// Helper function to render buttons correctly indented according to EditorGUI.indentLevel since GUILayout component don't respond naturally /// </summary> /// <param name="buttonText">text to place in button</param> /// <param name="options">layout options</param> /// <returns>true if button clicked, false if otherwise</returns> protected static bool RenderIndentedButton(string buttonText, params GUILayoutOption[] options) { return RenderIndentedButton(() => { return GUILayout.Button(buttonText, options); }); } /// <summary> /// Helper function to render buttons correctly indented according to EditorGUI.indentLevel since GUILayout component don't respond naturally /// </summary> /// <param name="content">What to draw in button</param> /// <param name="style">Style configuration for button</param> /// <param name="options">layout options</param> /// <returns>true if button clicked, false if otherwise</returns> protected static bool RenderIndentedButton(GUIContent content, GUIStyle style, params GUILayoutOption[] options) { return RenderIndentedButton(() => { return GUILayout.Button(content, style, options); }); } /// <summary> /// Helper function to support primary overloaded version of this functionality /// </summary> /// <param name="renderButton">The code to render button correctly based on parameter types passed</param> /// <returns>true if button clicked, false if otherwise</returns> private static bool RenderIndentedButton(Func<bool> renderButton) { bool result = false; GUILayout.BeginHorizontal(); GUILayout.Space(EditorGUI.indentLevel * 15); result = renderButton(); GUILayout.EndHorizontal(); return result; } /// <summary> /// Helper function to render header correctly for all profiles /// </summary> /// <param name="title">Title of profile</param> /// <param name="description">profile tooltip describing purpose</param> /// <param name="backText">Text for back button if not rendering as sub-profile</param> /// <param name="backProfile">Target profile to return to if not rendering as sub-profile</param> /// <returns>true to render rest of profile as-is or false if profile/MRTK is in a state to not render rest of profile contents</returns> protected bool RenderProfileHeader(string title, string description, BackProfileType returnProfileTarget = BackProfileType.Configuration) { RenderMixedRealityToolkitLogo(); if (!MixedRealityInspectorUtility.CheckMixedRealityConfigured()) { return false; } if (DrawBacktrackProfileButton(returnProfileTarget)) { return false; } EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(new GUIContent(title, description), EditorStyles.boldLabel, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider); return true; } } }
41.306931
175
0.619247
[ "MIT" ]
LocalJoost/MRTK2Tap
Assets/MixedRealityToolkit/Inspectors/Profiles/BaseMixedRealityToolkitConfigurationProfileInspector.cs
8,348
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BeatPulse.StatusPageTracker { class StatusPageClient { private readonly HttpClient _httpClient; private readonly StatusPageComponent _statusPageComponent; public StatusPageClient(StatusPageComponent statusPageComponent) { _statusPageComponent = statusPageComponent ?? throw new ArgumentNullException(nameof(statusPageComponent)); _httpClient = new HttpClient( new StatusPageAuthorizationHandler(statusPageComponent.ApiKey)) { BaseAddress = new Uri("https://api.statuspage.io/v1/") }; } public async Task CreateIncident(string failure) { var incidentId = await FindUnresolvedComponentIncident(); if (String.IsNullOrWhiteSpace(incidentId)) { var incident = $"incident[name]={_statusPageComponent.IncidentName}&incident[status]=investigating&incident[body]={failure}&incident[component_ids][]={_statusPageComponent.ComponentId}&incident[components][{_statusPageComponent.ComponentId}]=major_outage"; var content = new StringContent(incident, Encoding.UTF8, "application/x-www-form-urlencoded"); await _httpClient.PostAsync($"pages/{_statusPageComponent.PageId}/incidents.json", content); } } public async Task SolveIncident() { var incidentId = await FindUnresolvedComponentIncident(); if (!String.IsNullOrEmpty(incidentId)) { var content = $"incident[status]=resolved&incident[components][{_statusPageComponent.ComponentId}]=operational"; await _httpClient.PatchAsync($"pages/{_statusPageComponent.PageId}/incidents/{incidentId}.json", new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded")); } } async Task<string> FindUnresolvedComponentIncident() { var response = await _httpClient.GetAsync($"pages/{_statusPageComponent.PageId}/incidents/unresolved.json"); var unresolved = JsonConvert.DeserializeObject<IEnumerable<WebStatusIncident>>( await response.Content.ReadAsStringAsync()); if (unresolved.Any()) { return unresolved.Where(ws => ws.Name.Equals(_statusPageComponent.IncidentName, StringComparison.InvariantCultureIgnoreCase)) .Select(ws => ws.Id) .SingleOrDefault(); } return null; } private class StatusPageAuthorizationHandler : DelegatingHandler { private readonly string _apiKey; public StatusPageAuthorizationHandler(string apiKey) { _apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey)); InnerHandler = new HttpClientHandler(); } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.Headers .TryAddWithoutValidation("Authorization", $"OAuth {_apiKey}"); return await base.SendAsync(request, cancellationToken); } } private class WebStatusIncident { public string Id { get; set; } public string Name { get; set; } public string Status { get; set; } } } }
36.127451
272
0.637449
[ "Apache-2.0" ]
BTDevelop/BeatPulse
src/BeatPulse.StatusPageTracker/StatusPageClient.cs
3,687
C#
using System; using SmartGlass.Common; namespace SmartGlass { internal class TextDelta : ISerializable { public uint Offset { get; set; } public uint DeleteCount { get; set; } public string InsertContent { get; set; } public void Deserialize(EndianReader reader) { Offset = reader.ReadUInt32BE(); DeleteCount = reader.ReadUInt32BE(); InsertContent = reader.ReadUInt16BEPrefixedString(); } public void Serialize(EndianWriter writer) { writer.WriteBE(Offset); writer.WriteBE(DeleteCount); writer.WriteUInt16BEPrefixed(InsertContent); } } }
25.851852
64
0.606017
[ "MIT" ]
OpenXbox/xbox-smartglass-csharp
SmartGlass/TextDelta.cs
700
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XCommerce.Servicio.Core._25_Reserva { using System.Collections.Generic; using DTOs; public interface IReservaServicio { long Insertar(ReservaDto dto); void Modificar(ReservaDto dto); void Eliminar(long reservaId); IEnumerable<ReservaDto> Obtener(string cadenaBuscar); ReservaDto ObtenerPorId(long entidadId); void CambiarEstado(long id, AccesoDatos.EstadoReserva estado); void ReservarMesa(long clienteId, long mesaId, int comensales); IEnumerable<ReservaDto> ObtenerMesasParaReserva(); } }
29.333333
71
0.725852
[ "MIT" ]
RamonChauqui/SubeCodigo
XCommerce.Servicio.Core/25-Reserva/IReservaServicio.cs
706
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UO_UniDataSet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Rocket Software Inc.")] [assembly: AssemblyProduct("UO_UniDataSet")] [assembly: AssemblyCopyright("Copyright © Rocket Software Inc. 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4143985f-731d-4d7d-be5c-4081d1906f25")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.891892
84
0.748436
[ "MIT" ]
KathyGargas/u2-servers-lab
U2-Toolkit/.NET Samples/samples/C#/UniData/UO_UniDataSet/Properties/AssemblyInfo.cs
1,442
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Magnesium.Crawler.Web { /// <summary> /// 最基础的HTTP异常,所有HTTP异常均继承自该类 /// </summary> [Serializable] public class HttpException : Exception { public HttpException() { } public HttpException(string message) : base(message) { } public HttpException(string message, Exception inner) : base(message, inner) { } protected HttpException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } /// <summary> /// HTTP超时引发的异常 /// </summary> [Serializable] public class HttpTimeoutException : HttpException { public HttpTimeoutException() { } public HttpTimeoutException(string message) : base(message) { } public HttpTimeoutException(string message, Exception inner) : base(message, inner) { } protected HttpTimeoutException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } /// <summary> /// HTTP读写中引发的IO错误 /// </summary> [Serializable] public class HttpIOException : HttpException { public HttpIOException() { } public HttpIOException(string message) : base(message) { } public HttpIOException(string message, Exception inner) : base(message, inner) { } protected HttpIOException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
32.796296
95
0.662338
[ "MIT" ]
KureFM/Magnesium
Magnesium.Crawler/Web/HttpException.cs
1,837
C#
using System; using Neo.Core; using Neo.Gui.Base.Data; using Neo.Gui.Globalization.Resources; using Xunit; namespace Neo.Gui.Base.Tests.Data { public class TransactionItemTests { [Fact] public void Ctor_WithValidHash_CreateValidTransactionItem() { // Arrange var hash = UInt256.Parse("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"); // Act var transactionItem = new TransactionItem(hash, TransactionType.ContractTransaction, uint.MinValue, DateTime.Now); // Assert Assert.IsType<TransactionItem>(transactionItem); Assert.Equal(Strings.Unconfirmed, transactionItem.Confirmations); } [Fact] public void Ctor_NullHash_ThrowArgumentNullException() { // Arrange // Act // Assert Assert.Throws<ArgumentNullException>(() => new TransactionItem(null, TransactionType.ContractTransaction, uint.MinValue, DateTime.Now)); } [Fact] public void SetConfirmations_SetOneConfirmation_OneConfirmationIsSetToConfirmationField() { // Arrange var expectedConfirmations = 1; var hash = UInt256.Parse("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF"); // Act var transactionItem = new TransactionItem(hash, TransactionType.ContractTransaction, uint.MinValue, DateTime.Now); transactionItem.SetConfirmations(expectedConfirmations); // Assert Assert.Equal(expectedConfirmations.ToString(), transactionItem.Confirmations); } } }
33.72
148
0.658363
[ "MIT" ]
CityOfZion/neo-gui-wpf
Tests/Neo.Gui.Base.Tests/Data/TransactionItemTests.cs
1,688
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 4.0.1 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace QuantLib { public class RateHelper : Observable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; private bool swigCMemOwnDerived; internal RateHelper(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NQuantLibcPINVOKE.RateHelper_SWIGSmartPtrUpcast(cPtr), true) { swigCMemOwnDerived = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(RateHelper obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } protected override void Dispose(bool disposing) { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwnDerived) { swigCMemOwnDerived = false; NQuantLibcPINVOKE.delete_RateHelper(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } base.Dispose(disposing); } } public QuoteHandle quote() { QuoteHandle ret = new QuoteHandle(NQuantLibcPINVOKE.RateHelper_quote(swigCPtr), false); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Date latestDate() { Date ret = new Date(NQuantLibcPINVOKE.RateHelper_latestDate(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Date earliestDate() { Date ret = new Date(NQuantLibcPINVOKE.RateHelper_earliestDate(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Date maturityDate() { Date ret = new Date(NQuantLibcPINVOKE.RateHelper_maturityDate(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Date latestRelevantDate() { Date ret = new Date(NQuantLibcPINVOKE.RateHelper_latestRelevantDate(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public Date pillarDate() { Date ret = new Date(NQuantLibcPINVOKE.RateHelper_pillarDate(swigCPtr), true); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double impliedQuote() { double ret = NQuantLibcPINVOKE.RateHelper_impliedQuote(swigCPtr); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double quoteError() { double ret = NQuantLibcPINVOKE.RateHelper_quoteError(swigCPtr); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } } }
39.366667
137
0.700819
[ "Apache-2.0" ]
andrew-stakiwicz-r3/financial_derivatives_demo
quantlib_swig_bindings/CSharp/csharp/RateHelper.cs
3,543
C#
// // IMethodSignature.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Text; using Mono.Collections.Generic; namespace Mono.Cecil { public interface IMethodSignature : IMetadataTokenProvider { bool HasThis { get; set; } bool ExplicitThis { get; set; } MethodCallingConvention CallingConvention { get; set; } bool HasParameters { get; } Collection<ParameterDefinition> Parameters { get; } TypeReference ReturnType { get; set; } MethodReturnType MethodReturnType { get; } } static partial class Mixin { public static void MethodSignatureFullName (this IMethodSignature self, StringBuilder builder) { builder.Append ("("); if (self.HasParameters) { var parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { var parameter = parameters [i]; if (i > 0) builder.Append (","); if (parameter.ParameterType.IsSentinel) builder.Append ("...,"); builder.Append (parameter.ParameterType.FullName); } } builder.Append (")"); } } }
30.535211
96
0.71679
[ "MIT" ]
AlexAlbala/Alter-Native
Mono.Cecil/Mono.Cecil/IMethodSignature.cs
2,168
C#
// <copyright file="Armors.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> namespace MUnique.OpenMU.Persistence.Initialization.Version075.Items; using MUnique.OpenMU.AttributeSystem; using MUnique.OpenMU.DataModel.Attributes; using MUnique.OpenMU.DataModel.Configuration; using MUnique.OpenMU.DataModel.Configuration.Items; using MUnique.OpenMU.GameLogic.Attributes; using MUnique.OpenMU.Persistence.Initialization.CharacterClasses; using MUnique.OpenMU.Persistence.Initialization.Items; /// <summary> /// Initializer for armor data. /// </summary> public class Armors : InitializerBase { private static readonly int[] DefenseIncreaseByLevel = { 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 31, 36 }; private List<LevelBonus>? _defenseBonusPerLevel; private List<LevelBonus>? _shieldDefenseBonusPerLevel; /// <summary> /// Initializes a new instance of the <see cref="Armors"/> class. /// </summary> /// <param name="context">The persistence context.</param> /// <param name="gameConfiguration">The game configuration.</param> public Armors(IContext context, GameConfiguration gameConfiguration) : base(context, gameConfiguration) { } /// <summary> /// Initializes armor data. /// </summary> public override void Initialize() { this.CreateBonusDefensePerLevel(); // Shields: this.CreateShield(0, 1, 0, 2, 2, "Small Shield", 3, 1, 3, 22, 70, 0, 1, 1, 1); this.CreateShield(1, 1, 0, 2, 2, "Horn Shield", 9, 3, 9, 28, 100, 0, 0, 1, 0); this.CreateShield(2, 1, 0, 2, 2, "Kite Shield", 12, 4, 12, 32, 110, 0, 0, 1, 0); this.CreateShield(3, 1, 0, 2, 2, "Elven Shield", 21, 8, 21, 36, 30, 100, 0, 0, 1); this.CreateShield(4, 1, 18, 2, 2, "Buckler", 6, 2, 6, 24, 80, 0, 1, 1, 1); this.CreateShield(5, 1, 18, 2, 2, "Dragon Slayer Shield", 35, 10, 36, 44, 100, 40, 0, 1, 0); this.CreateShield(6, 1, 18, 2, 2, "Skull Shield", 15, 5, 15, 34, 110, 0, 1, 1, 1); this.CreateShield(7, 1, 18, 2, 2, "Spiked Shield", 30, 9, 30, 40, 130, 0, 0, 1, 0); this.CreateShield(8, 1, 18, 2, 2, "Tower Shield", 40, 11, 40, 46, 130, 0, 0, 1, 1); this.CreateShield(9, 1, 18, 2, 2, "Plate Shield", 25, 8, 25, 38, 120, 0, 0, 1, 0); this.CreateShield(10, 1, 18, 2, 2, "Big Round Shield", 18, 6, 18, 35, 120, 0, 0, 1, 0); this.CreateShield(11, 1, 18, 2, 2, "Serpent Shield", 45, 12, 45, 48, 130, 0, 0, 1, 1); this.CreateShield(12, 1, 18, 2, 2, "Bronze Shield", 54, 13, 54, 52, 140, 0, 0, 1, 0); this.CreateShield(13, 1, 18, 2, 2, "Dragon Shield", 60, 14, 60, 60, 120, 40, 0, 1, 0); this.CreateShield(14, 1, 0, 2, 3, "Legendary Shield", 48, 7, 48, 50, 90, 25, 1, 0, 1); // Helmets: this.CreateArmor(0, 2, 2, 2, "Bronze Helm", 16, 9, 34, 80, 20, 0, 1, 0); this.CreateArmor(1, 2, 2, 2, "Dragon Helm", 57, 24, 68, 120, 30, 0, 1, 0); this.CreateArmor(2, 2, 2, 2, "Pad Helm", 5, 4, 28, 20, 0, 1, 0, 0); this.CreateArmor(3, 2, 2, 2, "Legendary Helm", 50, 18, 42, 30, 0, 1, 0, 0); this.CreateArmor(4, 2, 2, 2, "Bone Helm", 18, 9, 30, 30, 0, 1, 0, 0); this.CreateArmor(5, 2, 2, 2, "Leather Helm", 6, 5, 30, 80, 0, 0, 1, 0); this.CreateArmor(6, 2, 2, 2, "Scale Helm", 26, 12, 40, 110, 0, 0, 1, 0); this.CreateArmor(7, 2, 2, 2, "Sphinx Mask", 32, 13, 36, 30, 0, 1, 0, 0); this.CreateArmor(8, 2, 2, 2, "Brass Helm", 36, 17, 44, 100, 30, 0, 1, 0); this.CreateArmor(9, 2, 2, 2, "Plate Helm", 46, 20, 50, 130, 0, 0, 1, 0); this.CreateArmor(10, 2, 2, 2, "Vine Helm", 6, 4, 22, 30, 60, 0, 0, 1); this.CreateArmor(11, 2, 2, 2, "Silk Helm", 16, 8, 26, 30, 70, 0, 0, 1); this.CreateArmor(12, 2, 2, 2, "Wind Helm", 28, 12, 32, 30, 80, 0, 0, 1); this.CreateArmor(13, 2, 2, 2, "Spirit Helm", 40, 16, 38, 40, 80, 0, 0, 1); this.CreateArmor(14, 2, 2, 2, "Guardian Helm", 53, 23, 45, 40, 80, 0, 0, 1); // Armors: this.CreateArmor(0, 3, 2, 2, "Bronze Armor", 18, 14, 34, 80, 20, 0, 1, 0); this.CreateArmor(1, 3, 2, 3, "Dragon Armor", 59, 37, 68, 120, 30, 0, 1, 0); this.CreateArmor(2, 3, 2, 2, "Pad Armor", 10, 7, 28, 30, 0, 1, 0, 0); this.CreateArmor(3, 3, 2, 2, "Legendary Armor", 56, 22, 42, 40, 0, 1, 0, 0); this.CreateArmor(4, 3, 2, 2, "Bone Armor", 22, 13, 30, 40, 0, 1, 0, 0); this.CreateArmor(5, 3, 2, 3, "Leather Armor", 10, 10, 30, 80, 0, 0, 1, 0); this.CreateArmor(6, 3, 2, 2, "Scale Armor", 28, 18, 40, 110, 0, 0, 1, 0); this.CreateArmor(7, 3, 2, 3, "Sphinx Armor", 38, 17, 36, 40, 0, 1, 0, 0); this.CreateArmor(8, 3, 2, 2, "Brass Armor", 38, 22, 44, 100, 30, 0, 1, 0); this.CreateArmor(9, 3, 2, 2, "Plate Armor", 48, 30, 50, 130, 0, 0, 1, 0); this.CreateArmor(10, 3, 2, 2, "Vine Armor", 10, 8, 22, 30, 60, 0, 0, 1); this.CreateArmor(11, 3, 2, 2, "Silk Armor", 20, 12, 26, 30, 70, 0, 0, 1); this.CreateArmor(12, 3, 2, 2, "Wind Armor", 32, 16, 32, 30, 80, 0, 0, 1); this.CreateArmor(13, 3, 2, 2, "Spirit Armor", 44, 21, 38, 40, 80, 0, 0, 1); this.CreateArmor(14, 3, 2, 2, "Guardian Armor", 57, 29, 45, 40, 80, 0, 0, 1); // Pants: this.CreateArmor(0, 4, 2, 2, "Bronze Pants", 15, 10, 34, 80, 20, 0, 1, 0); this.CreateArmor(1, 4, 2, 2, "Dragon Pants", 55, 26, 68, 120, 30, 0, 1, 0); this.CreateArmor(2, 4, 2, 2, "Pad Pants", 8, 5, 28, 30, 0, 1, 0, 0); this.CreateArmor(3, 4, 2, 2, "Legendary Pants", 53, 20, 42, 40, 0, 1, 0, 0); this.CreateArmor(4, 4, 2, 2, "Bone Pants", 20, 10, 30, 40, 0, 1, 0, 0); this.CreateArmor(5, 4, 2, 2, "Leather Pants", 8, 7, 30, 80, 0, 0, 1, 0); this.CreateArmor(6, 4, 2, 2, "Scale Pants", 25, 14, 40, 110, 0, 0, 1, 0); this.CreateArmor(7, 4, 2, 2, "Sphinx Pants", 34, 15, 36, 40, 0, 1, 0, 0); this.CreateArmor(8, 4, 2, 2, "Brass Pants", 35, 18, 44, 100, 30, 0, 1, 0); this.CreateArmor(9, 4, 2, 2, "Plate Pants", 45, 22, 50, 130, 0, 0, 1, 0); this.CreateArmor(10, 4, 2, 2, "Vine Pants", 8, 6, 22, 30, 60, 0, 0, 1); this.CreateArmor(11, 4, 2, 2, "Silk Pants", 18, 10, 26, 30, 70, 0, 0, 1); this.CreateArmor(12, 4, 2, 2, "Wind Pants", 30, 14, 32, 30, 80, 0, 0, 1); this.CreateArmor(13, 4, 2, 2, "Spirit Pants", 42, 18, 38, 40, 80, 0, 0, 1); this.CreateArmor(14, 4, 2, 2, "Guardian Pants", 54, 25, 45, 40, 80, 0, 0, 1); // Gloves: this.CreateArmor(0, 5, 2, 2, "Bronze Gloves", 13, 4, 34, 80, 20, 0, 1, 0); this.CreateArmor(1, 5, 2, 2, "Dragon Gloves", 52, 14, 68, 120, 30, 0, 1, 0); this.CreateArmor(2, 5, 2, 2, "Pad Gloves", 3, 2, 28, 20, 0, 1, 0, 0); this.CreateArmor(3, 5, 2, 2, "Legendary Gloves", 44, 11, 42, 20, 0, 1, 0, 0); this.CreateArmor(4, 5, 2, 2, "Bone Gloves", 14, 5, 30, 20, 0, 1, 0, 0); this.CreateArmor(5, 5, 2, 2, "Leather Gloves", 4, 2, 30, 80, 0, 0, 1, 0); this.CreateArmor(6, 5, 2, 2, "Scale Gloves", 22, 7, 40, 110, 0, 0, 1, 0); this.CreateArmor(7, 5, 2, 2, "Sphinx Gloves", 28, 8, 36, 20, 0, 1, 0, 0); this.CreateArmor(8, 5, 2, 2, "Brass Gloves", 32, 9, 44, 100, 30, 0, 1, 0); this.CreateArmor(9, 5, 2, 2, "Plate Gloves", 42, 12, 50, 130, 0, 0, 1, 0); this.CreateArmor(10, 5, 2, 2, "Vine Gloves", 4, 2, 22, 30, 60, 0, 0, 1); this.CreateArmor(11, 5, 2, 2, "Silk Gloves", 14, 4, 26, 30, 70, 0, 0, 1); this.CreateArmor(12, 5, 2, 2, "Wind Gloves", 26, 6, 32, 30, 80, 0, 0, 1); this.CreateArmor(13, 5, 2, 2, "Spirit Gloves", 38, 9, 38, 40, 80, 0, 0, 1); this.CreateArmor(14, 5, 2, 2, "Guardian Gloves", 50, 15, 45, 40, 80, 0, 0, 1); // Boots: this.CreateArmor(0, 6, 2, 2, "Bronze Boots", 12, 4, 34, 80, 20, 0, 1, 0); this.CreateArmor(1, 6, 2, 2, "Dragon Boots", 54, 15, 68, 120, 30, 0, 1, 0); this.CreateArmor(2, 6, 2, 2, "Pad Boots", 4, 3, 28, 20, 0, 1, 0, 0); this.CreateArmor(3, 6, 2, 2, "Legendary Boots", 46, 12, 42, 30, 0, 1, 0, 0); this.CreateArmor(4, 6, 2, 2, "Bone Boots", 16, 6, 30, 30, 0, 1, 0, 0); this.CreateArmor(5, 6, 2, 2, "Leather Boots", 5, 2, 30, 80, 0, 0, 1, 0); this.CreateArmor(6, 6, 2, 2, "Scale Boots", 22, 8, 40, 110, 0, 0, 1, 0); this.CreateArmor(7, 6, 2, 2, "Sphinx Boots", 30, 9, 36, 30, 0, 1, 0, 0); this.CreateArmor(8, 6, 2, 2, "Brass Boots", 32, 10, 44, 100, 30, 0, 1, 0); this.CreateArmor(9, 6, 2, 2, "Plate Boots", 42, 12, 50, 130, 0, 0, 1, 0); this.CreateArmor(10, 6, 2, 2, "Vine Boots", 5, 2, 22, 30, 60, 0, 0, 1); this.CreateArmor(11, 6, 2, 2, "Silk Boots", 15, 4, 26, 30, 70, 0, 0, 1); this.CreateArmor(12, 6, 2, 2, "Wind Boots", 27, 7, 32, 30, 80, 0, 0, 1); this.CreateArmor(13, 6, 2, 2, "Spirit Boots", 40, 10, 38, 40, 80, 0, 0, 1); this.CreateArmor(14, 6, 2, 2, "Guardian Boots", 52, 16, 45, 40, 80, 0, 0, 1); this.BuildSets(); } private IncreasableItemOption BuildDefenseBonusOption(float bonus) { var defenseBonus = this.Context.CreateNew<IncreasableItemOption>(); defenseBonus.PowerUpDefinition = this.Context.CreateNew<PowerUpDefinition>(); defenseBonus.PowerUpDefinition.Boost = this.Context.CreateNew<PowerUpDefinitionValue>(); defenseBonus.PowerUpDefinition.Boost.ConstantValue.AggregateType = AggregateType.Multiplicate; defenseBonus.PowerUpDefinition.Boost.ConstantValue.Value = bonus; defenseBonus.PowerUpDefinition.TargetAttribute = Stats.DefenseBase.GetPersistent(this.GameConfiguration); return defenseBonus; } private void CreateSetGroup(int setLevel, IncreasableItemOption option, ICollection<ItemDefinition> group) { var setForDefense = this.Context.CreateNew<ItemSetGroup>(); setForDefense.Name = $"{group.First().Name.Split(' ')[0]} Defense Bonus (Level {setLevel})"; setForDefense.MinimumItemCount = group.Count; setForDefense.Options.Add(option); setForDefense.SetLevel = (byte)setLevel; foreach (var item in group) { var itemOfSet = this.Context.CreateNew<ItemOfItemSet>(); itemOfSet.ItemDefinition = item; setForDefense.Items.Add(itemOfSet); } } private void BuildSets() { var sets = this.GameConfiguration.Items.Where(item => item.Group is >= 7 and <= 11).GroupBy(item => item.Number); var defenseRateBonus = this.Context.CreateNew<IncreasableItemOption>(); defenseRateBonus.PowerUpDefinition = this.Context.CreateNew<PowerUpDefinition>(); defenseRateBonus.PowerUpDefinition.Boost = this.Context.CreateNew<PowerUpDefinitionValue>(); defenseRateBonus.PowerUpDefinition.Boost.ConstantValue.AggregateType = AggregateType.Multiplicate; defenseRateBonus.PowerUpDefinition.Boost.ConstantValue.Value = 1.1f; defenseRateBonus.PowerUpDefinition.TargetAttribute = Stats.DefenseRatePvm.GetPersistent(this.GameConfiguration); var defenseBonus = new Dictionary<int, IncreasableItemOption> { { 10, this.BuildDefenseBonusOption(1.05f) }, { 11, this.BuildDefenseBonusOption(1.10f) }, }; foreach (var group in sets) { var setForDefenseRate = this.Context.CreateNew<ItemSetGroup>(); setForDefenseRate.Name = group.First().Name.Split(' ')[0] + " Defense Rate Bonus"; setForDefenseRate.MinimumItemCount = group.Count(); setForDefenseRate.Options.Add(defenseRateBonus); foreach (var item in group) { var itemOfSet = this.Context.CreateNew<ItemOfItemSet>(); itemOfSet.ItemDefinition = item; setForDefenseRate.Items.Add(itemOfSet); } for (int setLevel = 10; setLevel <= Constants.MaximumItemLevel; setLevel++) { this.CreateSetGroup(setLevel, defenseBonus[setLevel], group.ToList()); } } } private void CreateShield(byte number, byte slot, byte skill, byte width, byte height, string name, byte dropLevel, int defense, int defenseRate, byte durability, int strengthRequirement, int agilityRequirement, int darkWizardClassLevel, int darkKnightClassLevel, int elfClassLevel) { var shield = this.CreateArmor(number, slot, width, height, name, dropLevel, 0, durability, strengthRequirement, agilityRequirement, darkWizardClassLevel, darkKnightClassLevel, elfClassLevel); if (skill != 0) { shield.Skill = this.GameConfiguration.Skills.First(s => s.Number == skill); } if (defense > 0) { var powerUp = this.Context.CreateNew<ItemBasePowerUpDefinition>(); powerUp.TargetAttribute = Stats.DefenseBase.GetPersistent(this.GameConfiguration); powerUp.BaseValue = defense; this._shieldDefenseBonusPerLevel?.ForEach(powerUp.BonusPerLevel.Add); shield.BasePowerUpAttributes.Add(powerUp); } if (defenseRate > 0) { var powerUp = this.Context.CreateNew<ItemBasePowerUpDefinition>(); powerUp.TargetAttribute = Stats.DefenseRatePvm.GetPersistent(this.GameConfiguration); powerUp.BaseValue = defenseRate; this._defenseBonusPerLevel?.ForEach(powerUp.BonusPerLevel.Add); shield.BasePowerUpAttributes.Add(powerUp); } var isShieldEquipped = this.Context.CreateNew<ItemBasePowerUpDefinition>(); isShieldEquipped.TargetAttribute = Stats.IsShieldEquipped.GetPersistent(this.GameConfiguration); isShieldEquipped.BaseValue = 1; shield.BasePowerUpAttributes.Add(isShieldEquipped); } private ItemDefinition CreateArmor(byte number, byte slot, byte width, byte height, string name, byte dropLevel, int defense, byte durability, int strengthRequirement, int agilityRequirement, int darkWizardClassLevel, int darkKnightClassLevel, int elfClassLevel) { var armor = this.Context.CreateNew<ItemDefinition>(); this.GameConfiguration.Items.Add(armor); armor.Group = (byte)(slot + 5); armor.Number = number; armor.Width = width; armor.Height = height; armor.Name = name; armor.DropLevel = dropLevel; armor.MaximumItemLevel = Constants.MaximumItemLevel; armor.DropsFromMonsters = true; armor.Durability = durability; armor.ItemSlot = this.GameConfiguration.ItemSlotTypes.First(st => st.ItemSlots.Contains(slot)); this.CreateItemRequirementIfNeeded(armor, Stats.TotalStrengthRequirementValue, strengthRequirement); this.CreateItemRequirementIfNeeded(armor, Stats.TotalAgilityRequirementValue, agilityRequirement); if (defense > 0) { var powerUp = this.Context.CreateNew<ItemBasePowerUpDefinition>(); powerUp.TargetAttribute = Stats.DefenseBase.GetPersistent(this.GameConfiguration); powerUp.BaseValue = defense; this._defenseBonusPerLevel?.ForEach(powerUp.BonusPerLevel.Add); armor.BasePowerUpAttributes.Add(powerUp); } var classes = this.GameConfiguration.DetermineCharacterClasses(darkWizardClassLevel == 1, darkKnightClassLevel == 1, elfClassLevel == 1); foreach (var characterClass in classes) { armor.QualifiedCharacters.Add(characterClass); } armor.PossibleItemOptions.Add(this.GameConfiguration.GetLuck()); armor.PossibleItemOptions.Add(this.GameConfiguration.GetDefenseOption()); return armor; } private void CreateBonusDefensePerLevel() { this._defenseBonusPerLevel = new List<LevelBonus>(); this._shieldDefenseBonusPerLevel = new List<LevelBonus>(); for (int level = 1; level <= Constants.MaximumItemLevel; level++) { var levelBonus = this.Context.CreateNew<LevelBonus>(); levelBonus.Level = level; levelBonus.AdditionalValue = DefenseIncreaseByLevel[level]; this._defenseBonusPerLevel.Add(levelBonus); var shieldLevelBonus = this.Context.CreateNew<LevelBonus>(); levelBonus.Level = level; levelBonus.AdditionalValue = level; this._shieldDefenseBonusPerLevel.Add(shieldLevelBonus); } } }
55.520134
286
0.606649
[ "MIT" ]
ADMTec/OpenMU
src/Persistence/Initialization/Version075/Items/Armors.cs
16,547
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("MvvmCross.Plugins.PlatformTask")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("Denys Fiediaiev")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
37.777778
82
0.741176
[ "MIT" ]
Prin53/MvvmCross.Plugins.PlatformTask
MvvmCross.Plugins.PlatformTask/Properties/AssemblyInfo.cs
1,022
C#
using System; using UnityEngine; using DG.Tweening; using Json; namespace JTween { [Serializable] [SerializeField] public abstract class JTweenBase { protected int m_tweenType = 0; protected JTweenElement m_tweenElement = JTweenElement.None; protected string m_name = string.Empty; protected float m_duration = 0; protected float m_delay = 0; protected bool m_isSnapping = false; protected Ease m_animEase = Ease.Linear; protected AnimationCurve m_animCurve = null; protected int m_loopCount = 0; protected LoopType m_loopType = LoopType.Restart; protected UnityEngine.Transform m_target = null; private Tween m_lastPlayTween = null; /// <summary> /// 事件名 /// </summary> public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// 持续时间 /// </summary> public float Duration { get { return m_duration; } set { m_duration = value; } } /// <summary> /// 延迟时间 /// </summary> public float Delay { get { return m_delay; } set { m_delay = value; } } /// <summary> /// 结果取整 /// </summary> public bool IsSnapping { get { return m_isSnapping; } set { m_isSnapping = value; } } /// <summary> /// 动效方式 /// </summary> public Ease AnimEase { get { return m_animEase; } set { m_animEase = value; } } /// <summary> /// 动效曲线 /// </summary> public AnimationCurve AnimCure { get { return m_animCurve; } set { m_animCurve = value; } } /// <summary> /// 循环次数 /// </summary> public int LoopCount { get { return m_loopCount; } set { m_loopCount = value; } } /// <summary> /// 循环类型 /// </summary> public LoopType LoopType { get { return m_loopType; } set { m_loopType = value; } } /// <summary> /// 上一个动效 /// </summary> public Tween LastTween { get { return m_lastPlayTween; } } /// <summary> /// 动效实体 /// </summary> public UnityEngine.Transform Target { get { return m_target; } } /// <summary> /// 动效元素 /// </summary> public JTweenElement TweenElement { get { return m_tweenElement; } } /// <summary> /// 动效类型 /// </summary> public int TweenType { get { return m_tweenType; } set { m_tweenType = value; } } /// <summary> /// 绑定实体 /// </summary> /// <param name="tran"></param> public void Bind(UnityEngine.Transform tran) { m_target = tran; Init(); } /// <summary> /// 播放动效 /// </summary> /// <param name="_onComplete"> 动效完成回调 </param> /// <returns></returns> public Tween Play(TweenCallback _onComplete = null) { if (m_target == null) { Debug.LogError("must Binding tran first!!!"); return null; } // end if m_lastPlayTween = DOPlay(); if (m_lastPlayTween != null) { if (m_delay > 0) m_lastPlayTween.SetDelay(m_delay); // end if if (m_animCurve == null) { m_lastPlayTween.SetEase(m_animEase); } else { m_lastPlayTween.SetEase(m_animCurve); } // end if if (m_loopCount != 0) { m_lastPlayTween.SetLoops(m_loopCount, m_loopType); } // end if if (_onComplete != null) m_lastPlayTween.OnComplete(_onComplete); // end if } return m_lastPlayTween; } /// <summary> /// 动效参数是否有效 /// </summary> /// <param name="errorInfo"> 错误信息 </param> /// <returns></returns> public bool IsValid(out string errorInfo) { if (m_target == null) { errorInfo = "target is Null!!"; return false; } // end if if (JTweenUtils.IsEqual(m_duration, 0)) { errorInfo = "duration is zero!!"; return false; } // end if return CheckValid(out errorInfo); } /// <summary> /// 删除动效 /// </summary> /// <param name="complete"> 是否设置为完成状态 </param> public void Kill(bool complete = false) { if (m_lastPlayTween != null) m_lastPlayTween.Kill(complete); // end if OnKill(); } /// <summary> /// 转成Json /// </summary> public IJsonNode DoJson() { IJsonNode json = JsonHelper.CreateNode(); if (m_tweenType != 0) json.SetInt("tweenType", m_tweenType); // end if json.SetInt("tweenElement", (int)m_tweenElement); if (!string.IsNullOrEmpty(m_name)) json.SetString("name", m_name); // end if json.SetDouble("duration", Math.Round(m_duration, 4)); if (m_delay > 0.00009f) json.SetDouble("delay", Math.Round(m_delay, 4)); // end if json.SetBool("snapping", m_isSnapping); if (m_animCurve != null && m_animCurve.keys != null && m_animCurve.keys.Length > 0) { json.SetNode("animCurve", JTweenUtils.AnimationCurveJson(m_animCurve)); } else { json.SetInt("animEase", (int)m_animEase); } // end if if (m_loopCount > 0) { json.SetInt("loopCount", m_loopCount); json.SetInt("loopType", (int)m_loopType); } // end if ToJson(ref json); return json; } /// <summary> /// 加载Json /// </summary> /// <param name="json"></param> public void JsonDo(IJsonNode json) { if (json.Contains("tweenType")) m_tweenType = json.GetInt("tweenType"); // end if if (json.Contains("tweenElement")) m_tweenElement = (JTweenElement)json.GetInt("tweenElement"); // end if if (json.Contains("name")) m_name = json.GetString("name"); // end if if (json.Contains("delay")) m_delay = json.GetFloat("delay"); // end if if (json.Contains("duration")) m_duration = json.GetFloat("duration"); // end if if (json.Contains("snapping")) m_isSnapping = json.GetBool("snapping"); // end if if (json.Contains("animCurve")) m_animCurve = JTweenUtils.JsonAnimationCurve(json.GetNode("animCurve")); // end if if (json.Contains("animEase")) m_animEase = (Ease)json.GetInt("animEase"); // end if if (json.Contains("loopCount")) m_loopCount = json.GetInt("loopCount"); // end if if (json.Contains("loopType")) m_loopType = (LoopType)json.GetInt("loopType"); // end if JsonTo(json); } /// <summary> /// 转成Json /// </summary> /// <param name="json"></param> protected abstract void ToJson(ref IJsonNode json); /// <summary> /// 加载Json /// </summary> /// <param name="json"></param> protected abstract void JsonTo(IJsonNode json); /// <summary> /// 初始化 /// </summary> protected abstract void Init(); /// <summary> /// 还原 /// </summary> public abstract void Restore(); /// <summary> /// 播放 /// </summary> /// <returns></returns> protected abstract Tween DOPlay(); /// <summary> /// 检测参数是否有效 /// </summary> /// <param name="errorInfo"></param> /// <returns></returns> protected virtual bool CheckValid(out string errorInfo) { errorInfo = null; return true; } /// <summary> /// /// </summary> protected virtual void OnKill() { } } // end class JTweenBase } // end namespace JTween
30.783051
116
0.457108
[ "Unlicense" ]
HelloWindows/AccountBook
client/framework/GameFramework-master/JTween/JTween/JTweenBase.cs
9,303
C#
using HarmonyLib; using Planetbase; using PlanetbaseModUtilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using UnityEngine; namespace StorageGuru {/// <summary> /// Because of the way this is done, by picking the first module that has free slots and not passing the resource type to /// getEmptyStorageSlotCount, the easiest way I can see to inject our code here is essentially replacing the method /// </summary> [HarmonyPatch(typeof(Module), nameof(Module.findStorage))] public class ModuleFindStoragePatch { public static bool Prefix(ref Module __result, Character character) { float smallestDistance = float.MaxValue; __result = null; Vector3 position = character.getPosition(); List<Module> storageModules = Module.getCategoryModules(Module.Category.Storage); if (character.getLoadedResource() is Resource resource) { // Shortlist only modules that allow this resource storageModules = StorageGuruMod.StorageController.ListValidModules(resource.getResourceType()); } if (storageModules != null) { int count = storageModules.Count; for (int i = 0; i < count; i++) { Module module = storageModules[i]; if (module.isOperational() && module.isSurvivable(character) && module.getEmptyStorageSlotCount() > module.getPotentialUserCount(character)) { float sqrMagnitude = (module.getPosition() - position).sqrMagnitude; if (sqrMagnitude < smallestDistance) { __result = module; smallestDistance = sqrMagnitude; } } } } return false; // We don't want to run the original code } } [HarmonyPatch(typeof(Module), nameof(Module.serialize))] public class ModuleSerializePatch { /// <summary> /// Add check for storage manifest an serialize if exists /// </summary> public static void Postfix(ref Module __instance, XmlNode parent) { if(StorageGuruMod.StorageController.GetManifestEntry(__instance) is ManifestEntry entry) { XmlNode storageGuruNode = Serialization.createNode(parent.LastChild, "storageguru-manifest"); Serialization.serializeList(storageGuruNode, "resource-types", entry.AllowedResources.Select(x => x.GetType().Name).ToList()); } } } [HarmonyPatch(typeof(Module), nameof(Module.deserialize))] public class ModuleDeserializePatch { /// <summary> /// Deserialize manifest xml node if exists /// </summary> public static void Postfix(ref Module __instance, XmlNode node) { if (node["storageguru-manifest"] is XmlNode manifestNode) { var resourceTypes = new List<ResourceType>(); if (Serialization.deserializeList<string>(manifestNode["resource-types"]) is List<string> resources) { foreach (var resourceName in resources) { if (TypeList<ResourceType, ResourceTypeList>.find(resourceName) is ResourceType resourceType) { resourceTypes.Add(resourceType); } } } StorageGuruMod.StorageController.AddManifestEntry(__instance, resourceTypes); } } } }
33.32
145
0.663265
[ "MIT" ]
JCoil/PlanetbaseMods
StorageGuru/Patches/ModulePatches.cs
3,334
C#
using UnityEngine; using UnityEditor; using MxM; namespace MxMEditor { [CustomEditor(typeof(MxMEventDefinition))] public class MxMEventDefinitionInspector : Editor { private SerializedProperty m_spId; private SerializedProperty m_spEventName; private SerializedProperty m_spEventType; private SerializedProperty m_spPriority; private SerializedProperty m_spContactCountToMatch; private SerializedProperty m_spContactCountToWarp; private SerializedProperty m_spExitWithMotion; private SerializedProperty m_spMatchPose; private SerializedProperty m_spMatchTrajectory; private SerializedProperty m_spMatchRequireTags; private SerializedProperty m_spPostEventTrajectoryMode; private SerializedProperty m_spMatchTiming; private SerializedProperty m_spTimingWeight; private SerializedProperty m_spTimingWarpType; private SerializedProperty m_spMatchPosition; private SerializedProperty m_spPositionWeight; private SerializedProperty m_spMotionWarpType; private SerializedProperty m_spWarpTimeScaling; private SerializedProperty m_spContactCountToTimeScale; private SerializedProperty m_spMinWarpTimeScale; private SerializedProperty m_spMaxWarpTimeScale; private SerializedProperty m_spMatchRotation; private SerializedProperty m_spRotationWeight; private SerializedProperty m_spRotationWarpType; private bool m_generalFoldout = true; private bool m_timingFoldout = true; private bool m_positionFoldout = true; private bool m_rotationFoldout = true; private SerializedProperty m_spTargetAnimData; private void OnEnable() { m_spId = serializedObject.FindProperty("Id"); m_spEventName = serializedObject.FindProperty("EventName"); m_spEventType = serializedObject.FindProperty("EventType"); m_spPriority = serializedObject.FindProperty("Priority"); m_spContactCountToMatch = serializedObject.FindProperty("ContactCountToMatch"); m_spContactCountToWarp = serializedObject.FindProperty("ContactCountToWarp"); m_spExitWithMotion = serializedObject.FindProperty("ExitWithMotion"); m_spMatchPose = serializedObject.FindProperty("MatchPose"); m_spMatchTrajectory = serializedObject.FindProperty("MatchTrajectory"); m_spMatchRequireTags = serializedObject.FindProperty("MatchRequireTags"); m_spPostEventTrajectoryMode = serializedObject.FindProperty("PostEventTrajectoryMode"); m_spMatchTiming = serializedObject.FindProperty("MatchTiming"); m_spTimingWeight = serializedObject.FindProperty("TimingWeight"); m_spTimingWarpType = serializedObject.FindProperty("TimingWarpType"); m_spMatchPosition = serializedObject.FindProperty("MatchPosition"); m_spPositionWeight = serializedObject.FindProperty("PositionWeight"); m_spMotionWarpType = serializedObject.FindProperty("MotionWarpType"); m_spMatchRotation = serializedObject.FindProperty("MatchRotation"); m_spRotationWeight = serializedObject.FindProperty("RotationWeight"); m_spRotationWarpType = serializedObject.FindProperty("RotationWarpType"); m_spWarpTimeScaling = serializedObject.FindProperty("WarpTimeScaling"); m_spContactCountToTimeScale = serializedObject.FindProperty("ContactCountToTimeScale"); m_spMinWarpTimeScale = serializedObject.FindProperty("MinWarpTimeScale"); m_spMaxWarpTimeScale = serializedObject.FindProperty("MaxWarpTimeScale"); m_spTargetAnimData = serializedObject.FindProperty("m_targetAnimData"); } public override void OnInspectorGUI() { EditorGUILayout.LabelField(""); Rect lastRect = GUILayoutUtility.GetLastRect(); float curHeight = lastRect.y + 9f; curHeight = EditorUtil.EditorFunctions.DrawTitle("MxM Event Definition", curHeight); m_generalFoldout = EditorUtil.EditorFunctions.DrawFoldout("General", curHeight, EditorGUIUtility.currentViewWidth, m_generalFoldout); if (m_generalFoldout) { MxMAnimData animData = m_spTargetAnimData.objectReferenceValue as MxMAnimData; if (animData != null) { EditorGUI.BeginChangeCheck(); m_spId.intValue = EditorGUILayout.Popup("Event Name", m_spId.intValue, animData.EventNames); if(EditorGUI.EndChangeCheck()) { if (m_spId.intValue > -1 && m_spId.intValue < animData.EventNames.Length) { m_spEventName.stringValue = animData.EventNames[m_spId.intValue]; } } } else { EditorGUI.BeginChangeCheck(); m_spId.intValue = EditorGUILayout.IntField("Event Id", m_spId.intValue); if (EditorGUI.EndChangeCheck()) { if (m_spId.intValue < 0) m_spId.intValue = 0; } } m_spEventType.intValue = (int)(EMxMEventType)EditorGUILayout.EnumPopup("Event Type", (EMxMEventType)m_spEventType.intValue); EditorGUI.BeginChangeCheck(); m_spPriority.intValue = EditorGUILayout.IntField("Priority", m_spPriority.intValue); if (EditorGUI.EndChangeCheck()) { if (m_spPriority.intValue < -1) m_spPriority.intValue = -1; } EditorGUI.BeginChangeCheck(); m_spContactCountToMatch.intValue = EditorGUILayout.IntField("Num Contacts to Match", m_spContactCountToMatch.intValue); if(EditorGUI.EndChangeCheck()) { if (m_spContactCountToMatch.intValue < 0) m_spContactCountToMatch.intValue = 0; } EditorGUI.BeginChangeCheck(); m_spContactCountToWarp.intValue = EditorGUILayout.IntField("Num Contacts to Warp", m_spContactCountToWarp.intValue); if (EditorGUI.EndChangeCheck()) { if (m_spContactCountToWarp.intValue < 0) m_spContactCountToWarp.intValue = 0; } m_spExitWithMotion.boolValue = EditorGUILayout.Toggle("Exit With Motion", m_spExitWithMotion.boolValue); m_spMatchPose.boolValue = EditorGUILayout.Toggle("Match Pose", m_spMatchPose.boolValue); m_spMatchTrajectory.boolValue = EditorGUILayout.Toggle("Match Trajectory", m_spMatchTrajectory.boolValue); m_spMatchRequireTags.boolValue = EditorGUILayout.Toggle("Match Require Tags", m_spMatchRequireTags.boolValue); m_spPostEventTrajectoryMode.intValue = (int)(EPostEventTrajectoryMode)EditorGUILayout.EnumPopup( "Post Event Trajectory Mode", (EPostEventTrajectoryMode)m_spPostEventTrajectoryMode.intValue); EditorGUI.BeginChangeCheck(); EditorGUILayout.ObjectField(m_spTargetAnimData, typeof(MxMAnimData), new GUIContent("Ref AnimData")); if (EditorGUI.EndChangeCheck()) { animData = m_spTargetAnimData.objectReferenceValue as MxMAnimData; if (animData != null) { (target as MxMEventDefinition).ValidateEventId(); } } curHeight += 18f * 10f; } curHeight += 30f; GUILayout.Space(3f); m_timingFoldout = EditorUtil.EditorFunctions.DrawFoldout("Time Warping", curHeight, EditorGUIUtility.currentViewWidth, m_timingFoldout); if (m_timingFoldout) { EditorGUI.BeginChangeCheck(); m_spMatchTiming.boolValue = EditorGUILayout.Toggle("Match Timing", m_spMatchTiming.boolValue); if(EditorGUI.EndChangeCheck()) { if (m_spMatchTiming.boolValue) { m_spWarpTimeScaling.boolValue = false; } } m_spTimingWeight.floatValue = EditorGUILayout.FloatField("Timing Weight", m_spTimingWeight.floatValue); m_spTimingWarpType.intValue = (int)(EEventWarpType)EditorGUILayout.EnumPopup("Timing Warp Type", (EEventWarpType)m_spTimingWarpType.intValue); curHeight += 18f * 3f; } curHeight += 30f; GUILayout.Space(3f); m_positionFoldout = EditorUtil.EditorFunctions.DrawFoldout("Position Warping", curHeight, EditorGUIUtility.currentViewWidth, m_positionFoldout); if (m_positionFoldout) { m_spMatchPosition.boolValue = EditorGUILayout.Toggle("Match Position", m_spMatchPosition.boolValue); m_spPositionWeight.floatValue = EditorGUILayout.FloatField("Position Weight", m_spPositionWeight.floatValue); m_spMotionWarpType.intValue = (int)(EEventWarpType)EditorGUILayout.EnumPopup("Position Warp Type", (EEventWarpType)m_spMotionWarpType.intValue); EditorGUI.BeginChangeCheck(); m_spWarpTimeScaling.boolValue = EditorGUILayout.Toggle("Time Scaling", m_spWarpTimeScaling.boolValue); if(EditorGUI.EndChangeCheck()) { if(m_spWarpTimeScaling.boolValue) { m_spMatchTiming.boolValue = false; } } if (m_spWarpTimeScaling.boolValue) { EditorGUILayout.BeginHorizontal(); GUILayout.Space(20f); EditorGUILayout.BeginVertical(); m_spContactCountToTimeScale.intValue = EditorGUILayout.IntField("Contact Count", m_spContactCountToTimeScale.intValue); m_spMinWarpTimeScale.floatValue = EditorGUILayout.FloatField("Min", m_spMinWarpTimeScale.floatValue); m_spMaxWarpTimeScale.floatValue = EditorGUILayout.FloatField("Max", m_spMaxWarpTimeScale.floatValue); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); curHeight += 18f * 3f; } curHeight += 18f * 4f; } curHeight += 30f; GUILayout.Space(3f); m_rotationFoldout = EditorUtil.EditorFunctions.DrawFoldout("Rotation Warping", curHeight, EditorGUIUtility.currentViewWidth, m_rotationFoldout); if (m_rotationFoldout) { m_spMatchRotation.boolValue = EditorGUILayout.Toggle("Match Rotation", m_spMatchRotation.boolValue); m_spRotationWeight.floatValue = EditorGUILayout.FloatField("Rotation Weight", m_spRotationWeight.floatValue); m_spRotationWarpType.intValue = (int)(EEventWarpType)EditorGUILayout.EnumPopup("Rotation Warp Type", (EEventWarpType)m_spRotationWarpType.intValue); curHeight += 18f * 3f; } curHeight += 30f; GUILayout.Space(3f); serializedObject.ApplyModifiedProperties(); } }//End of class: MxMEventDefinitionInspector }//End of namespace: MxMEditor
46.825397
164
0.632458
[ "MIT" ]
suweitao8/MotionMatchingTutorial
Assets/Plugins/MotionMatching/Code/MxM/Editor/Inspectors/MxMEventDefinitionInspector.cs
11,802
C#
using System.Globalization; using System.Threading.Tasks; using JustSaying.Tools.Commands; using Magnum.CommandLineParser; using Magnum.Monads.Parser; namespace JustSaying.Tools { public static class CommandParser { public static async Task<bool> ParseAndExecuteAsync(string commandText) { var anyCommandFailure = false; await CommandLine .Parse<ICommand>(commandText, InitializeCommandLineParser) .ForEachAsync(async option => { var optionSuccess = await option.ExecuteAsync().ConfigureAwait(false); anyCommandFailure |= !optionSuccess; }).ConfigureAwait(false); return anyCommandFailure; } private static void InitializeCommandLineParser(ICommandLineElementParser<ICommand> x) { x.Add((from arg in x.Argument("exit") select (ICommand) new ExitCommand()) .Or(from arg in x.Argument("quit") select (ICommand) new ExitCommand()) .Or(from arg in x.Argument("help") select (ICommand) new HelpCommand()) .Or(from arg in x.Argument("move") from sourceQueueName in x.Definition("from") from destinationQueueName in x.Definition("to") from region in x.Definition("in") from count in (from d in x.Definition("count") select d).Optional("count", "1") select (ICommand) new MoveCommand(sourceQueueName.Value, destinationQueueName.Value, region.Value, int.Parse(count.Value, CultureInfo.InvariantCulture))) ); } } }
38.456522
118
0.583946
[ "Apache-2.0" ]
JarrodJ83/JustSaying
JustSaying.Tools/CommandParser.cs
1,769
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.PSharp; using Microsoft.PSharp.Timers; using System.Threading.Tasks; namespace TimerSample { class Client : TimedMachine { #region fields /// <summary> /// Count of #timeout events processed per state. /// </summary> int count; /// <summary> /// A dummy payload object received with timeout events. /// </summary> object payload = new object(); /// <summary> /// Timer used in the Ping State. /// </summary> TimerId pingTimer; /// <summary> /// Timer used in the Pong state. /// </summary> TimerId pongTimer; #endregion #region states /// <summary> /// Start the pingTimer and start handling the timeout events from it. /// After handling 10 events, stop pingTimer and move to the Pong state. /// </summary> [Start] [OnEntry(nameof(DoPing))] [OnEventDoAction(typeof(TimerElapsedEvent), nameof(HandleTimeoutForPing))] class Ping : MachineState { } /// <summary> /// Start the pongTimer and start handling the timeout events from it. /// After handling 10 events, stop pongTimer and move to the Ping state. /// </summary> [OnEntry(nameof(DoPong))] [OnEventDoAction(typeof(TimerElapsedEvent), nameof(HandleTimeoutForPong))] class Pong : MachineState { } #endregion #region event handlers private void DoPing() { // reset the count count = 1; // Start a periodic timer with timeout interval of 1sec. // The timer generates TimerElapsedEvent with 'm' as payload. pingTimer = StartTimer(payload, 50, true); } /// <summary> /// Handle timeout events from the pingTimer. /// </summary> private async Task HandleTimeoutForPing() { TimerElapsedEvent e = (this.ReceivedEvent as TimerElapsedEvent); // Ensure that we are handling a valid timeout event. this.Assert(e.Tid == this.pingTimer, "Handling timeout event from an invalid timer."); this.Logger.WriteLine("ping count: {0}", count); // Extract the payload Object payload = e.Tid.Payload; // Increment the count count++; // Halt pingTimer after handling 10 timeout events if (count == 10) { // Stop the pingTimer, and flush the inbox of all timeout events generated by it await StopTimer(pingTimer, flush: true); this.Goto<Pong>(); } } /// <summary> /// Handle timeout events from the pongTimer. /// </summary> private void DoPong() { // reset the count count = 1; // Start a periodic timer with timeout interval of 0.5sec. // The timer generates TimerElapsedEvent with 'm' as payload. pongTimer = StartTimer(payload, 50, true); } private async Task HandleTimeoutForPong() { TimerElapsedEvent e = (this.ReceivedEvent as TimerElapsedEvent); // Ensure that we are handling a valid timeout event. this.Assert(e.Tid == this.pongTimer, "Handling timeout event from an invalid timer."); this.Logger.WriteLine("pong count: {0}", count); // Extract the payload Object payload = e.Tid.Payload; // Increment the count count++; // Halt pingTimer after handling 10 timeout events if (count == 10) { // Stop the pingTimer, and flush the inbox of all timeout events generated by it await StopTimer(pongTimer, flush: true); this.Goto<Ping>(); } } #endregion } }
25.097744
89
0.67825
[ "MIT" ]
chandramouleswaran/PSharp
Samples/Timers/TimerSample/Client.cs
3,340
C#
using System; using Utilities; namespace EddiEvents { [PublicAPI] public class MissionFailedEvent : Event { public const string NAME = "Mission failed"; public const string DESCRIPTION = "Triggered when you fail a mission"; public const string SAMPLE = "{ \"timestamp\":\"2016-09-25T12:53:01Z\", \"event\":\"MissionFailed\", \"Name\":\"Mission_PassengerVIP_name\", \"MissionID\":26493517 }"; [PublicAPI("The ID of the mission")] public long? missionid { get; private set; } [PublicAPI("The name of the mission")] public string name { get; private set; } [PublicAPI("The fine levied")] public long fine { get; private set; } public MissionFailedEvent(DateTime timestamp, long? missionid, string name, long fine) : base(timestamp, NAME) { this.missionid = missionid; this.name = name; this.fine = fine; } } }
32.033333
175
0.611863
[ "Apache-2.0" ]
EDCD/EliteDangerousDataProvider
Events/MissionFailedEvent.cs
963
C#