public async Task <IActionResult> Edit(int id, [Bind("Id,Details")] SomeData someData) { if (id != someData.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(someData); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SomeDataExists(someData.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(someData)); }
static void Main(string[] args) { SomeData[] data = new SomeData[] { new SomeData { Name = "ZZZZ", X = -1 }, new SomeData { Name = "AAAA", X = 5 }, new SomeData { Name = "BBBB", X = 5 }, new SomeData { Name = "CCCC", X = 5 } }; var prop1 = new DynamicProperty <SomeData>("X"); var prop2 = new DynamicProperty <SomeData>("Name"); var sorted = data.OrderBy(x => prop1.GetPropertyValue(x)) .ThenByDescending(x => prop2.GetPropertyValue(x)); foreach (var res in sorted) { Console.WriteLine("{0} X: {1}", res.Name, res.X); } }
public SomeData DataContractOperation(SomeData input) { return(new SomeData() { Value = Square(input.Value) }); }
public void SerializeAndDeserializeTest() { var sd1 = new SomeData("test", 123, new List <string> { "one", "two" }); var optionJson = Transformer.Serialize(sd1); if (optionJson.HasValue) { var json = optionJson.ValueOr(""); Console.WriteLine(json); Assert.AreEqual <string>(@"{""Name"":""test"",""Age"":123,""Stages"":[""one"",""two""]}", json); var optionSd2 = Transformer.Deserialize(json); if (optionSd2.HasValue) { var sd2 = optionSd2.ValueOr(() => null); Assert.AreEqual(sd1, sd2); } else { Assert.Fail("Deserialize failed"); } } else { Assert.Fail("Serialize failed"); } }
private void btnPut_Click(object sender, EventArgs e) { var cnt = tbCount.Text.AsInt(); var keyStart = tbKeyStart.Text.AsInt(); var tbl = m_Cache.GetOrCreateTable <GDID>(tbTable.Text); var par = tbParallel.Text.AsInt(1); var absExp = tbAbsoluteExpiration.Text.AsNullableDateTime(); if (absExp.HasValue) { absExp = absExp.Value.ToUniversalTime(); } var maxAgeSec = tbMaxAgeSec.Text.AsNullableInt(null); var binF = tbBinFrom.Text.AsInt(); var binT = tbBinTo.Text.AsInt(); if (tbMaxCapacity.Text.IsNotNullOrWhiteSpace()) { tbl.Options.MaximumCapacity = tbMaxCapacity.Text.AsInt(); } var sw = Stopwatch.StartNew(); var utcNow = DateTime.UtcNow; Parallel.For(0, cnt, new ParallelOptions { MaxDegreeOfParallelism = par }, (i) => { var key = new GDID(0, (ulong)(keyStart + i)); var data = //new SomeDataParcel(key, new SomeData { ID = key, Text1 = "Some text one" + i.ToString(), Text2 = "Another line of text which is longer", Long1 = i, Long2 = i * 178, SD = DateTime.UtcNow, Bin = (binF >= 0 && binT >= 0) ? new byte[Ambient.Random.NextScaledRandomInteger(binF, binT)] : null };//, // new SomeReplicationVersionInfo(utcNow) // );//"My data object #"+key.ToString() tbl.Put(key, data, maxAgeSec: maxAgeSec, absoluteExpirationUTC: absExp); } ); tbKeyStart.Text = (keyStart + cnt + 1).ToString(); var ems = sw.ElapsedMilliseconds; Text = "Put {0:n0} in {1:n0} ms at {2:n2}/sec".Args(cnt, ems, cnt / (ems / 1000d)); }
public void Retry_executes_action_when_all_attempts_fail() { var repo = Mock.Of <ISomeDataRepository>(); var data = new SomeData() { Id = 10, Name = "Fernando" }; var cnt = 0; Mock.Get(repo).Setup(r => r.SaveSomeData(It.IsAny <SomeData>())).Callback(() => { cnt++; throw new ApplicationException("Error saving data due to timeout!"); }); string log = ""; try { Retry.It(() => repo.SaveSomeData(data)) .WhenExceptionMessageContains("timeout") .Times(3) .OnFailure((r, e) => { log = "Can't save this s***!"; }) .Go(); Assert.Fail("Did not throw exception!"); } catch (ApplicationException ex) { Assert.AreEqual("Error saving data due to timeout!", ex.Message); Assert.AreEqual(4, cnt); // 1 + 3 retries Assert.AreEqual("Can't save this s***!", log); } }
public static void Call <X>(X[] dataCollection, ref SomeData someOtherValue, JobHandle inputDeps) where X : struct { foreach (var data in dataCollection) { data.Call(); } }
public TestMe(SomeData data) { ITreasure treasure = _factory.Get(data); if (treasure is BlueTreasure) ... else if (treasure is RedTreasure) ... else if (treasure is GreenTreasure) ... }
public void Retry_throws_exception() { var repo = Mock.Of <ISomeDataRepository>(); var data = new SomeData() { Id = 10, Name = "Fernando" }; Mock.Get(repo).Setup(r => r.SaveSomeData(It.IsAny <SomeData>())).Callback(() => { throw new ApplicationException("Shit!"); }); try { Retry.It(() => repo.SaveSomeData(data)) .WhenExceptionMessageContains("timeout") // exception is "Shit!", will not retry .Times(3) .Go(); Assert.Fail("Did not throw exception!"); } catch (ApplicationException ex) { Assert.AreEqual("Shit!", ex.Message); } }
// Use this for initialization void Start() { var someData = new SomeData(); var pt = new ParallelTaskCollection <SomeData>(someData); var st = new SerialTaskCollection <SomeData>(someData); st.Add(Print("s1")); st.Add(Print("s2")); st.Add(pt); st.Add(Print("s3")); st.Add(Print("s4")); pt.Add(Print("1")); pt.Add(Print("2")); pt.Add(DoSomethingAsynchonously()); pt.Add(new LoadSomething(new WWW("www.google.com"))); //obviously the token could be passed by constructor, but in some complicated situations, this is not possible (usually while exploiting continuation) pt.Add(new LoadSomething(new WWW("http://download.thinkbroadband.com/5MB.zip"))); pt.Add(new LoadSomething(new WWW("www.ebay.com"))); pt.Add(Print("3")); pt.Add(Print("4")); pt.Add(Print("5")); pt.Add(Print("6")); pt.Add(Print("7")); pt.Add(Print(someData.justForTest.ToString())); TaskRunner.Instance.Run(st); }
public void Retry_retry_when_exception_type_is() { var repo = Mock.Of <ISomeDataRepository>(); var data = new SomeData() { Id = 10, Name = "Fernando" }; var cnt = 0; Mock.Get(repo).Setup(r => r.SaveSomeData(It.IsAny <SomeData>())).Callback(() => { cnt++; if (cnt < 3) { throw new ArgumentNullException("teste"); } }); Retry.It(() => repo.SaveSomeData(data)) .WhenExceptionTypeIs(typeof(ArgumentNullException)) .Times(3) .Go(); Mock.Get(repo).Verify(r => r.SaveSomeData(It.Is <SomeData>(d => d.Id.Equals(10) && d.Name.Equals("Fernando")))); Assert.AreEqual(3, cnt); }
public void Do(Db db) { bool dispose = false; if (db == null) { db = new Db("DATA"); dispose = true; } #if (SERVER) db._db_internal.CallServer = (byte[] f) => { return(SocketTesting.CallServer(f)); }; #endif #if (SOCKETS) db._db_internal.CallServer = (byte[] f) => { return(SocketTesting.CallServer(f, db)); }; #endif #if (SOCKETS || SAMEDB || INDEXES || SERVER) db.Table <SomeData>().Delete(new HashSet <int>(db.Table <SomeData>().Select(f => new { f.Id }).Select(f => f.Id).ToList())); #endif var d = new SomeData() { Id = 1, Normalized = 1.2, PeriodId = 5 }; db.Table <SomeData>().Save(d); try { var res = db.Table <SomeData>() .Select(f => new { PeriodId = f.PeriodId + 1 }); throw new Exception("Assert failure"); } catch (Exception e) { if (!e.Message.Contains("Linqdb: Select must not have any expressions")) { throw new Exception("Assert failure"); } } #if (SERVER || SOCKETS) if (dispose) { Logic.Dispose(); } #else if (dispose) { db.Dispose(); } #endif #if (!SOCKETS && !SAMEDB && !INDEXES && !SERVER) if (dispose) { ServerSharedData.SharedUtils.DeleteFilesAndFoldersRecursively("DATA"); } #endif }
/// It is not easy to compact object-by-object even for TLS data because TLS data is most typically interleaved with /// the data required for TLS bookkeeping: /// 0000022a61982318 00007ffd9c5faba0 24 Chapter2.Examples.ThreadLocalFalseSharingDemo+SomeTLSData // 0000022a61982330 00007ffd9c6510a0 32 System.Threading.ThreadLocal`1+LinkedSlotVolatile[[Chapter2.Examples.ThreadLocalFalseSharingDemo + SomeTLSData, Chapter2.Examples]][] // 0000022a61982350 00007ffd9c6514c0 32 System.Threading.ThreadLocal`1+FinalizationHelper[[Chapter2.Examples.ThreadLocalFalseSharingDemo + SomeTLSData, Chapter2.Examples]] // 0000022a61982370 00007ffd9c636098 48 System.Threading.ThreadLocal`1+LinkedSlot[[Chapter2.Examples.ThreadLocalFalseSharingDemo + SomeTLSData, Chapter2.Examples]] // ... // 0000022a61982520 00007ffd9c5faba0 24 Chapter2.Examples.ThreadLocalFalseSharingDemo+SomeTLSData // // Thus, although False Sharing may happen between TLS-based data, it is really (really) hard to recreate such scenario public void Run() { var threadId = Thread.CurrentThread.ManagedThreadId; var prevAddress = 0L; var sum = 0L; while (true) { var obj = _threadLocal.Value; var address = obj.GetAddress1(); var gen = GC.GetGeneration(obj); if (address != prevAddress) { Console.WriteLine($"[TID {threadId}] {prevAddress:x16}->{address:x16} ({address-prevAddress}), gen {gen}"); prevAddress = address; } if (gen < 2) { sum += new SomeData().GetData(); // Allocate and consume! } var allocated = GC.GetAllocatedBytesForCurrentThread(); if (allocated % 0x1_0000 == 0 && gen < 2) { GC.Collect(2, GCCollectionMode.Forced, true, true); } } }
bool InsertInTransaction(Db db, int i) { using (var transaction = new LinqdbTransaction()) { var d = new SomeData() { Id = i, Normalized = 1.2, PeriodId = 5, Value = i }; db.Table <SomeData>(transaction).Save(d); var d2 = new BinaryData() { Id = i, Data = new List <byte>() { 1, 2, 3 }.ToArray() }; db.Table <BinaryData>(transaction).Save(d2); if (i % 2 == 0) { transaction.Commit(); return(true); } else { return(false); } } }
public void WriteAndReadBadSubData() { var cut = new XmlFormatter <SomeData>(); var data = new SomeData { Name = null, Number = 0.42M + GetHashCode(), DataAfterObject = $"Some text after object at {GetHashCode()}", SubData = new BadSubData($"Info at {GetHashCode()}"), Names = new[] { "Name1", "Name2" }, }; cut.Serialize(data, Filename); var read = cut.Deserialize(Filename); Assert.AreEqual(data.Name, read.Name); Assert.AreEqual(data.Number, read.Number); Assert.AreEqual(data.YesNo, read.YesNo); Assert.AreEqual(data.Value, read.Value); Assert.AreNotEqual(data.SubData.Info, read.SubData.Info); Assert.AreEqual(data.DataAfterObject, read.DataAfterObject); Assert.AreNotEqual(data.NotGood, read.NotGood); Assert.AreEqual(data.Names.Length, read.Names.Length); for (var i = 0; i < data.Names.Length; i++) { Assert.AreEqual(data.Names[i], read.Names[i], $"Names[{i}] differ"); } }
IEnumerator DoPost() { //Add form data for Post (such as (hashed!) login information) WWWForm form = new WWWForm(); form.AddField("origin", "127.0.0.1"); //Use post, append form UnityWebRequest request = UnityWebRequest.Post("http://httpbin.org/post", form); yield return(request.SendWebRequest()); if (request.isHttpError || request.isNetworkError) { Debug.LogError("Oops"); } else { Debug.Log(request.downloadHandler.text); //Parse as searchable JSON, instead of Unity object (sometimes you don't want Unity objects!) var n = JSON.Parse(request.downloadHandler.text); Debug.Log(n["form"]); //Parse form into Unity object anyway! SomeData d = JsonUtility.FromJson <SomeData>(n["form"].ToString()); Debug.Log(d.origin); } }
static void Main() { var hsc1 = new SomeData { EffectiveDate = new DateTime(2011, 4, 5), Kind = "KindOne" }; var hsc2 = new SomeData { EffectiveDate = new DateTime(2011, 4, 10), Kind = "KindTwo" }; var hsc3 = new SomeData { EffectiveDate = new DateTime(2011, 4, 20), Kind = "KindOne" }; var hsc4 = new SomeData { EffectiveDate = new DateTime(2011, 4, 25), Kind = "KindOne" }; var all = new[] { hsc1, hsc2, hsc3, hsc4 }; var lastSomeData = all.OrderByDescending((x) => x.EffectiveDate).First(); var q = (from h in all orderby h.EffectiveDate descending select h).TakeWhile(x => x.Kind == lastSomeData.Kind); var result = q.ToArray(); foreach (var item in result) { Console.WriteLine(item); } Console.WriteLine(""); Console.WriteLine("Press any key"); Console.ReadKey(); }
public void Retry_throw_original_exception_when_reaches_max_retries() { var repo = Mock.Of <ISomeDataRepository>(); var data = new SomeData() { Id = 10, Name = "Fernando" }; var cnt = 0; Mock.Get(repo).Setup(r => r.SaveSomeData(It.IsAny <SomeData>())).Callback(() => { cnt++; throw new ApplicationException("Error saving data due to timeout!"); }); try { Retry.It(() => repo.SaveSomeData(data)) .WhenExceptionMessageContains("timeout") .Times(3) .Go(); Assert.Fail("Did not throw exception!"); } catch (ApplicationException ex) { Assert.AreEqual("Error saving data due to timeout!", ex.Message); Assert.AreEqual(4, cnt); // 1 + 3 retries } }
public void Retry_executes_action_after_each_retry() { var repo = Mock.Of <ISomeDataRepository>(); var data = new SomeData() { Id = 10, Name = "Fernando" }; var cnt = 0; Mock.Get(repo).Setup(r => r.SaveSomeData(It.IsAny <SomeData>())).Callback(() => { cnt++; if (cnt < 3) { throw new ApplicationException("Error saving data due to timeout!"); } }); int afterCount = 0; Retry.It(() => repo.SaveSomeData(data)) .WhenExceptionMessageContains("timeout") .Times(3) .AfterRetry((r, e) => { afterCount++; }) .Go(); Mock.Get(repo).Verify(r => r.SaveSomeData(It.Is <SomeData>(d => d.Id.Equals(10) && d.Name.Equals("Fernando")))); Assert.AreEqual(3, cnt); Assert.AreEqual(2, afterCount); }
public static void Insert(Db db) { try { var norm = 1.2; int a = 5; int period = a == 5 ? 5 : 6; var date = DateTime.Now.AddDays(-1); var name = "test"; var d = new SomeData() { Id = 1, Normalized = norm, PeriodId = period, Date = date, NameSearch = name }; //db.Table<SomeData>().Save(d); db.Table <SomeData>() .Where(f => f.PeriodId == period && f.Normalized == norm && f.Date == date && f.NameSearch == name) .AtomicIncrement2Props(f => f.PeriodId, f => f.PersonId, 1, 1, d); //if (res.Count() != 1 || res[0].PeriodId != period) //{ // throw new Exception("Assert failure"); //} } catch (Exception) { throw new Exception("Assert failure"); } }
public static SomeData GetObject() { if (d == null) { d = new SomeData(); } return(d); }
public void SomeDataConstructorTest() { var sd = new SomeData("test", 123, new List <string> { "one", "two" }); Assert.AreNotEqual(null, sd); }
static void Main() { SomeDataClass data1 = new SomeDataClass(); SomeDataClass data2 = new SomeDataClass(); data1.Data = SomeData.Load("somefile.dat"); data2.Data = data1.Data; }
public void Bug951c(SomeData data) { DoAction(delegate { DoAction(delegate { DoSomething(data.Value); }); }); }
public void Do(Db db_unused) { if (db_unused != null) { #if (SERVER) Logic.Dispose(); #else db_unused.Dispose(); #endif if (Directory.Exists("DATA")) { ServerSharedData.SharedUtils.DeleteFilesAndFoldersRecursively("DATA"); } } var db = new Db("DATA"); #if (SERVER) db._db_internal.CallServer = (byte[] f) => { return(SocketTesting.CallServer(f)); }; #endif var d = new SomeData() { Id = 1, Normalized = -1.2, PeriodId = 5 }; db.Table <SomeData>().Save(d); d = new SomeData() { Id = 2, Normalized = -0.9, PeriodId = 7 }; db.Table <SomeData>().Save(d); #if (SERVER) db.Table <Testing.tables.SomeType>()._internal._db._InternalClearCache(); #endif var count = db.Table <Testing.tables4.SomeData>().Count(); var dic = new Dictionary <int, double>() { { 1, 0 }, { 2, 0 } }; db.Table <Testing.tables4.SomeData>().Update(f => f.SomeDouble, dic); var res = db.Table <Testing.tables4.SomeData>().SelectEntity(); if (res.Count() != 2 || res[0].Value != 0 || res[1].Value != 0) { throw new Exception("Assert failure"); } #if (SERVER) Logic.Dispose(); #else db.Dispose(); #endif ServerSharedData.SharedUtils.DeleteFilesAndFoldersRecursively("DATA"); }
public void WriteAndRead() { var cut = new XmlFormatter <SomeData>(); var data = new SomeData { Name = null, Number = 0.42M + GetHashCode(), Time = DateTime.Now, Span = TimeSpan.FromMilliseconds(457575578), DataAfterObject = $"Some text after object at {GetHashCode()}", SubData = new SubData { Info = $"Info at {GetHashCode()}" }, Names = new[] { "Name1", "Name2" }, Products = { "product1", "product2", "product3" }, SubDatas = { { "Test1", new SubData { Info = $"Test1 dictionary at {GetHashCode()}" } }, { "Test2", new SubData { Info = $"Test2 dictionary at {GetHashCode()}" } } }, Location = new Point(5, 6) }; cut.Serialize(data, Filename); var read = cut.Deserialize(Filename); Assert.AreEqual(data.Name, read.Name); Assert.AreEqual(data.Number, read.Number); Assert.AreEqual(data.Time, read.Time); Assert.AreEqual(data.Span, read.Span); Assert.AreEqual(data.YesNo, read.YesNo); Assert.AreEqual(data.Value, read.Value); Assert.AreEqual(data.Location, read.Location); Assert.AreEqual(data.SubData.Info, read.SubData.Info); Assert.AreEqual(data.DataAfterObject, read.DataAfterObject); Assert.AreNotEqual(data.NotGood, read.NotGood); Assert.AreEqual(data.Names.Length, read.Names.Length); for (var i = 0; i < data.Names.Length; i++) { Assert.AreEqual(data.Names[i], read.Names[i], $"Names[{i}] differ"); } Assert.AreEqual(data.Products.Count, read.Products.Count); for (var i = 0; i < data.Products.Count; i++) { Assert.AreEqual(data.Products[i], read.Products[i], $"Products[{i}] differ"); } Assert.AreEqual(data.SubDatas.Count, read.SubDatas.Count); foreach (var key in data.SubDatas.Keys) { Assert.AreEqual(data.SubDatas[key].Info, read.SubDatas[key].Info); } }
public void SubsequentViewPersistence( IRepository <string, SomeData> repository, View view, ISequenceResolver sequenceResolver, IRepository <string, Snapshot> snapshotRepository, IViewManager viewManager, SomeEvent firstEvent, SomeEvent secondEvent, SomeData initialData, SomeData actualInitialData, SomeData subsequentData) { "Given a view repository"._(() => repository = new MemoryRepository <string, SomeData>()); "and some intial data"._( () => initialData = new SomeData { LastEventId = "test2", EventCount = 2, }); "and the repository contains the initial data"._(() => repository.AddOrUpdate("root", initialData)); "and a view"._(() => view = new SomeView(repository)); "and a sequence resolver"._(() => sequenceResolver = new CustomSequenceResolver()); "and a snapshot repository"._(() => snapshotRepository = new MemoryRepository <string, Snapshot>()); "and the snapshot repository contains the initial snapshot data"._( () => snapshotRepository.AddOrUpdate( view.GetType().FullName, new Snapshot { ViewName = view.GetType().FullName, PersistedSequenceNumber = 2, })); "and a view manager"._(ctx => viewManager = ViewManager.ForViews(view) .OrderEventsUsing(sequenceResolver) .SnapshotViewsUsing(snapshotRepository).WithAQuietTimeTimeoutOf(2) .Create().Using(ctx)); "and a third event"._(() => firstEvent = new SomeEvent { Sequence = 3, Id = "test3" }); "and a fourth event"._(() => secondEvent = new SomeEvent { Sequence = 4, Id = "test4" }); "when those events are dispatched"._( () => { viewManager.QueueForDispatch(firstEvent); viewManager.QueueForDispatch(secondEvent); }); "and the operation is given time to process"._(() => Thread.Sleep(1000)); "and the repository is queried initially"._(() => actualInitialData = repository.Get("root")); "and the snapshot is given time to process"._(() => Thread.Sleep(2000)); "and the repository is queried subsequently"._(() => subsequentData = repository.Get("root")); "then the initial query should be empty"._(() => actualInitialData.Should().Be(initialData)); "and the view received the second event last"._(() => subsequentData.LastEventId.Should().Be(secondEvent.Id)); "and the view received two events"._(() => subsequentData.EventCount.Should().Be(4)); }
public IActionResult SomeDataQuery([FromQuery] SomeData data) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Poco parameter was define like this : [FromQuery] SomeData data"); sb.AppendLine("If a property was not set then default value will be inserted."); sb.AppendLine("Result as Json:"); sb.AppendLine(JsonConvert.SerializeObject(data, Formatting.Indented)); return(Ok(sb.ToString())); }
public void ToStringTest() { var sd = new SomeData("test", 123, new List <string> { "one", "two" }); var str = sd.ToString(); //Console.WriteLine(str); Assert.AreEqual <string>("SomeData: Name: test, Age: 123, Stages: [one, two]", str); }
public async Task <IActionResult> Create([Bind("Id,Details")] SomeData someData) { if (ModelState.IsValid) { _context.Add(someData); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(someData)); }
public void it_should_be_serializable_deserialiazble() { var someData = new SomeData { stringValue = "qwerty", intValue = 12345, boolValue = false, stringArray = new[] { "q", "w", "e" } }; var stream = ProtoBufSerializer.Serialize(someData); stream.Should().NotBeNull(); ProtoBufSerializer.Deserialize<SomeData>(stream).ShouldBeEquivalentTo(someData); }
public void cache_entry_should_support_this_type() { var someData = new SomeData { stringValue = "qwerty", intValue = 12345, boolValue = false, stringArray = new[] { "q", "w", "e" } }; var cacheEntry = new CacheEntry<SomeData> {Value = someData}; var stream = ProtoBufSerializer.Serialize(cacheEntry); stream.Should().NotBeNull(); ProtoBufSerializer.Deserialize<CacheEntry<SomeData>>(stream).ShouldBeEquivalentTo(cacheEntry, options => options.Excluding(x=>x.Value)); }