public EntitySet <T> ApplyChangesFromPortableText(string json) { EntitySet <T> retVal = new EntitySet <T>(); if (string.IsNullOrWhiteSpace(json) || json.Length > 100000000) { throw new CEFInvalidStateException(InvalidStateType.BadParameterValue, "Incoming data is too short or too long."); } var kdef = KeyService.ResolveKeyDefinitionForType(typeof(T)); if (kdef == null || kdef.Count == 0) { throw new CEFInvalidStateException(InvalidStateType.MissingKey, typeof(T).Name); } using (var jr = new Newtonsoft.Json.JsonTextReader(new StringReader(json))) { var jq = Newtonsoft.Json.Linq.JObject.Load(jr); var sourceCols = new List <string>(); var sourceTypes = new List <string>(); var keyIndexes = new List <int>(); var idx = 0; foreach (Newtonsoft.Json.Linq.JObject scol in jq.Value <Newtonsoft.Json.Linq.JArray>("schema")) { var pcn = scol.Property("cn"); var pdt = scol.Property("dt"); if (pcn != null && pdt != null) { var cn = pcn.Value.ToString(); sourceCols.Add(cn); var dt = pdt.Value.ToString(); sourceTypes.Add(dt); if (kdef.Contains(cn)) { keyIndexes.Add(idx); } idx++; } } // An indexed view in this case can be a dictionary for fast lookup var index = ToDictionary(kdef); HashSet <T> sourceVisits = new HashSet <T>(); foreach (Newtonsoft.Json.Linq.JArray row in jq.Value <Newtonsoft.Json.Linq.JArray>("rows")) { var keyval = new StringBuilder(128); foreach (var c in kdef) { if (keyval.Length > 0) { keyval.Append("~"); } var kloc = sourceCols.IndexOf(c); keyval.Append(row[kloc].ToString()); } bool isnew = false; if (!index.TryGetValue(keyval.ToString(), out T target)) { target = new T(); Add(target); isnew = true; } else { sourceVisits.Add(target); retVal.Add(target); } var tiw = target.AsInfraWrapped() ?? throw new CEFInvalidStateException(InvalidStateType.ObjectTrackingIssue); var prefTypes = tiw.GetAllPreferredTypes(); for (int i = 0; i < sourceCols.Count; ++i) { if (!keyIndexes.Contains(i) || isnew) { var v = row[i].ToString(); if (!string.IsNullOrEmpty(v)) { var scn = sourceCols[i]; var oldval = tiw.GetValue(scn)?.ToString(); if (string.Compare(sourceTypes[i], "datetime") == 0) { if (long.TryParse(v, out long ld)) { v = (new DateTime((ld * 10000L) + 621355968000000000L, DateTimeKind.Utc)).ToString("O"); } if (!string.IsNullOrEmpty(oldval)) { oldval = Convert.ToDateTime(oldval).ToString("O"); } } if (string.Compare(oldval, v, false) != 0) { if (prefTypes.TryGetValue(scn, out Type pt)) { tiw.SetValue(scn, v.CoerceType(pt)); } else { tiw.SetValue(scn, v); } } } } } } foreach (T i in index.Values) { if (!sourceVisits.Contains(i)) { CEF.DeleteObject(i); this.Remove(i); } } } return(retVal); }
public string GetPortableText(PortableSerializationOptions?options = null) { if (options == null) { options = new PortableSerializationOptions(); } StringBuilder sb = new StringBuilder(4096); var actmode = options.Mode.GetValueOrDefault(Globals.PortableJSONMode.GetValueOrDefault(CEF.CurrentServiceScope.Settings.SerializationMode)); CEF.CurrentServiceScope.ReconcileModifiedState(null); using (var jw = new JsonTextWriter(new StringWriter(sb))) { jw.FloatFormatHandling = FloatFormatHandling.DefaultValue; // All contained within an object jw.WriteStartObject(); jw.WritePropertyName("schema"); jw.WriteStartArray(); var c = typeof(T).FastGetAllProperties(true, (actmode & SerializationMode.IncludeReadOnlyProps) == 0 ? true : new bool?()).ToList(); // Use a top x sample of entries in collection to determine if there are any extended properties to serialize if (options.IncludeExtended.GetValueOrDefault(Globals.PortableJSONIncludeExtended) && options.ExtendedPropertySampleSize.GetValueOrDefault(Globals.PortableJSONExtendedPropertySampleSize) > 0) { foreach (T i in this.Take(options.ExtendedPropertySampleSize.GetValueOrDefault(Globals.PortableJSONExtendedPropertySampleSize))) { var iw = i.AsInfraWrapped(); if (iw != null) { c = c.Union(from a in iw.GetAllPreferredTypes() select(a.Key, a.Value, true, true)).ToList(); } } } // Explicitly remove audit if needed if (options.ExcludeAudit.GetValueOrDefault(Globals.PortableJSONExcludeAudit)) { if (!string.IsNullOrEmpty(CEF.CurrentAuditService()?.LastUpdatedByField)) { var trem = (from a in c where string.Compare(a.name, CEF.CurrentAuditService()?.LastUpdatedByField, true) == 0 select a); if (trem.Any()) { c.Remove(trem.First()); } } if (!string.IsNullOrEmpty(CEF.CurrentAuditService()?.LastUpdatedDateField)) { var trem = (from a in c where string.Compare(a.name, CEF.CurrentAuditService()?.LastUpdatedDateField, true) == 0 select a); if (trem.Any()) { c.Remove(trem.First()); } } if (!string.IsNullOrEmpty(CEF.CurrentAuditService()?.IsDeletedField)) { var trem = (from a in c where string.Compare(a.name, CEF.CurrentAuditService()?.IsDeletedField, true) == 0 select a); if (trem.Any()) { c.Remove(trem.First()); } } } // Apply column name filters if needed if (options.IncludeColumns != null) { c = (from a in c where (from b in options.IncludeColumns where string.Compare(a.name, b, true) == 0 select b).Any() select a).ToList(); } if (options.ExcludeColumns != null) { c = (from a in c where !(from b in options.ExcludeColumns where string.Compare(a.name, b, true) == 0 select b).Any() select a).ToList(); } // Get any available key for this type var keydef = KeyService.ResolveKeyDefinitionForType(typeof(T)); List <string> finalName = new List <string>(); List <Type> finalType = new List <Type>(); // Actual schema write based on distinct list of columns and types foreach (var prop in (from n in (from a in c select a.name).Distinct() select new { Name = n, Type = (from t in c where string.Compare(t.name, n, true) == 0 orderby(t.type == null ? 1 : 0) select t.type).First() })) { var restype = prop.Type; var req = !(prop.Type.IsGenericType && prop.Type.GetGenericTypeDefinition() == typeof(Nullable <>)); if (!req) { restype = Nullable.GetUnderlyingType(prop.Type); } var rp = ValidationService.GetRequiredFor(typeof(T), prop.Name); if (rp.HasValue) { req = rp.Value; } // Ignore non-primative ref types - things like property classes in generated code should interop with the base instance if (restype.IsPrimitive || restype.IsValueType || restype.IsSerializable) { jw.WriteStartObject(); jw.WritePropertyName("cn"); jw.WriteValue(prop.Name); if ((actmode & SerializationMode.IncludeType) != 0) { jw.WritePropertyName("dt"); jw.WriteValue(restype.Name.ToLower().Replace("system.", "")); jw.WritePropertyName("key"); jw.WriteValue((from a in keydef where string.Compare(a, prop.Name, true) == 0 select a).Any()); jw.WritePropertyName("req"); jw.WriteValue(req); // If there's a maxlength setting available, write it var ml = ValidationService.GetMaxLengthFor(typeof(T), prop.Name); if (ml.HasValue) { jw.WritePropertyName("maxlen"); jw.WriteValue(ml); } } jw.WriteEndObject(); finalName.Add(prop.Name); finalType.Add(restype); } } // end schema jw.WriteEndArray(); // Start data jw.WritePropertyName("rows"); jw.WriteStartArray(); var cdates = options.ConvertDates.GetValueOrDefault(Globals.PortableJSONConvertDates); IEnumerable <ICEFInfraWrapper> list = this.AllAsInfraWrapped(); if (options.SortSpec != null) { list = list.OrderBy(options.SortSpec); } if (options.FilterSpec != null) { list = list.Where(options.FilterSpec); } foreach (var iw in list) { if ((actmode & SerializationMode.OnlyChanged) == 0 || iw.GetRowState() != ObjectState.Unchanged) { jw.WriteStartArray(); for (int i = 0; i < finalName.Count; ++i) { var cv = iw.GetValue(finalName[i]); if (cv == null) { string?s = null; jw.WriteValue(s); } else { if (finalType[i] == typeof(DateTime)) { var asdate = Convert.ToDateTime(cv); if (cdates == DateConversionMode.ToGMTAlways || (cdates == DateConversionMode.ToGMTWhenHasTime && asdate.TimeOfDay.Seconds > 0)) { asdate = asdate.ToUniversalTime(); } var d = Convert.ToInt64(asdate.Ticks - 621355968000000000L) / 10000L; jw.WriteValue(d); } else { var cvt = cv.GetType(); // For non-primative ref types, need to "flatten" properties if (cvt.IsValueType || cvt.IsPrimitive || cvt.IsSerializable) { jw.WriteValue(cv); } } } } jw.WriteEndArray(); } } // end data jw.WriteEndArray(); jw.WriteEndObject(); } return(sb.ToString()); }
void f_brow_Close() { browser.Dispose(); CEF.Shutdown(); }
public static void Shutdown() { CEF.Shutdown(); }
public static void Benchmark1WithBulk(int total_parents, List <long> testTimes, List <long> testTimes2, ref int rowcount, ref int rowcount2) { var watch = new System.Diagnostics.Stopwatch(); watch.Start(); using (CEF.NewServiceScope()) { var people = new EntitySet <Person>(); for (int parentcnt = 1; parentcnt <= total_parents; ++parentcnt) { var parent = new PersonWrapped() { Name = $"NP{parentcnt}", Age = (parentcnt % 60) + 20, Gender = (parentcnt % 2) == 0 ? "F" : "M" }; parent.Phones.Add(new Phone() { Number = "888-7777", PhoneTypeID = PhoneType.Mobile }); parent.Phones.Add(new Phone() { Number = "777-6666", PhoneTypeID = PhoneType.Work }); if ((parentcnt % 12) == 0) { CEF.NewObject(new Phone() { Number = "666-5555", PhoneTypeID = PhoneType.Home }); } else { parent.Phones.Add(new Phone() { Number = "777-6666", PhoneTypeID = PhoneType.Home }); } rowcount += 4; for (int childcnt = 1; childcnt <= (parentcnt % 4); ++childcnt) { var child = CEF.NewObject(new PersonWrapped() { Name = $"NC{parentcnt}{childcnt}", Age = parent.Age - 20, Gender = (parentcnt % 2) == 0 ? "F" : "M" , Phones = new Phone[] { new Phone() { Number = "999-8888", PhoneTypeID = PhoneType.Mobile } } }); parent.Kids.Add(child); rowcount += 2; } people.Add(parent); } CEF.DBSave(new DBSaveSettings().UseBulkInsertTypes(typeof(Phone))); } testTimes.Add(watch.ElapsedMilliseconds); watch.Restart(); // For purposes of benchmarking, treat this as a completely separate operation using (var ss = CEF.NewServiceScope()) { // For everyone who's a parent of at least 30 yo, if at least 2 children of same sex, remove work phone, increment age EntitySet <Person> people = new EntitySet <Person>().DBRetrieveSummaryForParents(30); Parallel.ForEach((from a in people let d = a.AsDynamic() where d.MaleChildren > 1 || d.FemaleChildren > 1 select a).ToList(), (p) => { using (CEF.UseServiceScope(ss)) { p.Age += 1; var ph = new EntitySet <Phone>().DBRetrieveByOwner(p.PersonID, PhoneType.Work).FirstOrDefault(); if (ph != null) { CEF.DeleteObject(ph); } } }); rowcount2 += CEF.DBSave().Count(); } watch.Stop(); testTimes2.Add(watch.ElapsedMilliseconds); }
public GoogleV3TileSchema(string gmeClientID, string googleChannel, string referer, GoogleV3TileSource.MapTypeId mapType) { MapType = mapType; Height = 256; Width = 256; Extent = new Extent(-20037508.342789, -20037508.342789, 20037508.342789, 20037508.342789); OriginX = -20037508.342789; OriginY = 20037508.342789; Name = "GoogleSchema"; Format = "png"; Axis = AxisDirection.InvertedY; Srs = "EPSG:3857"; m_gmeClientID = gmeClientID; m_googleChannel = googleChannel; m_referer = referer; if (m_cachedUrLs.ContainsKey(mapType + "_base")) { MapUrlTemplates = m_cachedUrLs[mapType + "_base"]; } if (m_cachedUrLs.ContainsKey(mapType + "_overlay")) { OverlayUrlTemplates = m_cachedUrLs[mapType + "_overlay"]; } m_appContext = new ApplicationContext(); /* var frm = new Form(); * frm.Show(); * frm.Size = new System.Drawing.Size(600, 400); * Label l = new Label(); * l.Text = "Test"; * * WebBrowser bw = new WebBrowser(); * bw.Size = new System.Drawing.Size(600, 400); * frm.Size = new System.Drawing.Size(600, 400); * * frm.Controls.Add(l); * frm.Controls.Add(bw); */ wbThread = new Thread(() => { try { #if USE_CefSharp var settings = new CefSharp.Settings { PackLoadingDisabled = true, }; if (CEF.Initialize(settings)) { m_webView = new WebView(); m_webView.PropertyChanged += WebViewOnPropertyChanged; m_webView.Address = referer; } #else m_webBrowser = new WebBrowser(); m_webBrowser.Navigating += m_WebBrowser_Navigating; m_webBrowser.Visible = true; m_webBrowser.ScrollBarsEnabled = false; m_webBrowser.Size = new System.Drawing.Size(600, 400); m_webBrowser.ScriptErrorsSuppressed = true; m_webBrowser.DocumentCompleted += m_WebBrowser_DocumentCompleted; //bw.Invoke(new MethodInvoker(delegate //{ // bw.Navigating += new WebBrowserNavigatingEventHandler(m_WebBrowser_Navigating); // bw.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(m_WebBrowser_DocumentCompleted); // bw.DocumentText = // "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><style>BODY { background-color: red;}</style></head><body></body></html>"; //})); //m_webBrowser = bw; if (!string.IsNullOrEmpty(referer)) { m_webBrowser.Navigate(referer); } else { m_webBrowser.DocumentText = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><body></body></html>"; } #endif if (m_appContext != null) { Application.Run(m_appContext); } } catch (Exception ee) { m_logger.Error("Exception in WebBrowserThread, quitting", ee); } }); wbThread.Name = "WebBrowser Thread"; wbThread.SetApartmentState(ApartmentState.STA); wbThread.Start(); if (m_logger.IsDebugEnabled) { m_logger.Debug("WebBrowserThread Started"); } }
private void WriteSerializationText(JsonTextWriter tw, object o, SerializationMode mode, SerializationVisitTracker visits) { var iw = o.AsInfraWrapped(false); if (iw != null) { tw.WriteStartObject(); var wot = iw.GetWrappedObject()?.GetType() ?? iw.GetBaseType(); // We only really want/need to include type info on outermost objects (session scope level only), so reset this for all nested objects var nextmode = (SerializationMode)((int)mode & (-1 ^ (int)SerializationMode.IncludeType)); if ((mode & SerializationMode.IncludeType) != 0) { tw.WritePropertyName(Globals.SerializationTypePropertyName); tw.WriteValue(o.GetType().AssemblyQualifiedName); } // Attempt to push enumerable types to the "end" foreach (var kvp in (from a in iw.GetAllValues() orderby a.Value is IEnumerable ? 1 : 0 select a)) { // If it's enumerable, recurse each item // TODO - better way to detect primitive type like string w/o hardcoding?? if (kvp.Value is IEnumerable && kvp.Value.GetType() != typeof(string)) { tw.WritePropertyName(kvp.Key); tw.WriteStartArray(); var asEnum = (kvp.Value as IEnumerable).GetEnumerator(); while (asEnum.MoveNext()) { var i = asEnum.Current; // We only need to do this for tracked objects, for now we only do for value types or non-system (TODO) if (i == null || i.GetType().IsValueType || i.GetType().FullName.StartsWith("System.")) { tw.WriteValue(i); } else { if ((mode & SerializationMode.SingleLevel) == 0) { var iw2 = i.AsInfraWrapped(); if (iw2 != null) { SaveContents(tw, iw2, nextmode, visits); } else { if (i.GetType().IsSerializable) { tw.WriteValue(i); } } } } } tw.WriteEndArray(); } else { // If it's a tracked object, recurse if (kvp.Value != null && !kvp.Value.GetType().IsValueType&& CEF.CurrentServiceScope.GetTrackedByWrapperOrTarget(kvp.Value) != null) { if ((mode & SerializationMode.SingleLevel) == 0) { var iw2 = kvp.Value.AsInfraWrapped(); if (iw2 != null) { tw.WritePropertyName(kvp.Key); SaveContents(tw, iw2, nextmode, visits); } } } else { if ((mode & SerializationMode.ExtendedInfoAsShadowProps) != 0) { var rs = iw.GetRowState(); if (rs == ObjectState.Modified || rs == ObjectState.ModifiedPriority) { var ov = iw.GetOriginalValue(kvp.Key, false); if (ov != null) { tw.WritePropertyName("\\\\" + kvp.Key); tw.WriteValue(ov); } } // We write out schema metadata only when see a type for the first time if (!visits.Types.Contains(wot)) { var pb = wot.GetProperty(kvp.Key); // Preferred data type var pt = (from a in iw.GetAllPreferredTypes() where a.Key == kvp.Key select a.Value).FirstOrDefault() ?? pb?.PropertyType; if (pt != null) { tw.WritePropertyName("\\+" + kvp.Key); tw.WriteValue(pt.AssemblyQualifiedName); // Is writeable tw.WritePropertyName("\\-" + kvp.Key); tw.WriteValue(pb?.CanWrite); } } } if (kvp.Value != null || (mode & SerializationMode.IncludeNull) != 0) { if (((mode & SerializationMode.IncludeReadOnlyProps) != 0) || (wot.GetProperty(kvp.Key)?.CanWrite).GetValueOrDefault(true)) { if (((mode & SerializationMode.OnlyCLRProperties) == 0) || (wot.GetProperty(kvp.Key)?.CanRead).GetValueOrDefault(false)) { var aud = CEF.CurrentAuditService(); if (aud != null) { if (((mode & SerializationMode.OriginalForConcurrency) == 0) || (string.Compare(aud.LastUpdatedDateField, kvp.Key, true) != 0 && string.Compare(aud.IsDeletedField, kvp.Key, true) != 0)) { if (kvp.Value == null || kvp.Value.GetType().IsSerializable) { tw.WritePropertyName(kvp.Key); tw.WriteValue(kvp.Value); } } else { // Only need to send original date - do not send isdeleted at all if (string.Compare(aud.IsDeletedField, kvp.Key, true) != 0) { var rs = iw.GetRowState(); if (rs != ObjectState.Added && rs != ObjectState.Unlinked) { var val = iw.GetOriginalValue(kvp.Key, false); if (val != null) { tw.WritePropertyName(kvp.Key); tw.WriteValue(val); } } } } } } } } } } } if ((mode & SerializationMode.ExtendedInfoAsShadowProps) != 0) { tw.WritePropertyName("_ot_"); tw.WriteValue(wot.Name); } // Allows for inclusion of object state, etc. iw.FinalizeObjectContents(tw, mode); tw.WriteEndObject(); } else { tw.WriteValue(o); } }
private void view_TestCookieVisitorActivated(object sender, EventArgs e) { CEF.VisitAllCookies(this); }
public void TearDown() { createdEvent.WaitOne(); CEF.Shutdown(); Application.Exit(); }
public void AddByQuery <T>(IEnumerable <T> list, string text, object[] parms = null, int?expirySeconds = null, CacheBehavior?mode = null) where T : class, new() { var ss = CEF.CurrentServiceScope; if (mode == null) { mode = ss.ResolvedCacheBehaviorForType(typeof(T)); } if ((mode & CacheBehavior.QueryBased) == 0 && (mode & CacheBehavior.ConvertQueryToIdentity) != 0 && ((mode & CacheBehavior.ForAllDoesntConvertToIdentity) == 0 || string.Compare(text, "All", true) != 0)) { // All we can do is for all list items, add to identity cache void act2() { try { Interlocked.Increment(ref _working); Parallel.ForEach(list, (i) => { using (CEF.UseServiceScope(ss)) { AddByIdentity <T>(i, expirySeconds: expirySeconds); } }); } catch (Exception ex) { CEFDebug.WriteInfo($"Exception in cache serializer: {ex.Message}"); } finally { Interlocked.Decrement(ref _working); } } if (Globals.AsyncCacheUpdates) { Task.Factory.StartNew(act2); } else { act2(); } return; } if ((mode & CacheBehavior.OnlyForAllQuery) != 0 && string.Compare(text, "All", true) != 0) { return; } StringBuilder sb = new StringBuilder(128); sb.Append(typeof(T).Name); sb.Append(text.ToUpperInvariant()); if (parms != null) { foreach (var k in parms) { sb.Append(k); } } string hash; using (SHA256Managed hasher = new SHA256Managed()) { hash = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(sb.ToString()))); } var c = _index.GetFirstByName(nameof(MFSEntry.ByQuerySHA), hash); if (!expirySeconds.HasValue) { expirySeconds = CEF.CurrentServiceScope.ResolvedCacheDurationForType(typeof(T)); } var newExpDate = DateTime.Now.AddSeconds(expirySeconds.GetValueOrDefault(DefaultCacheIntervalSeconds)); if (c == null) { c = new MFSEntry(); if (list.Any()) { c.ObjectTypeName = list.First().GetBaseType().Name; } else { c.ObjectTypeName = typeof(T).Name; } c.ByQuerySHA = hash; c.FileName = BuildNewFileName(typeof(T)); c.QueryForAll = string.Compare(text, "All", true) == 0; _index.Add(c); } long current; lock (c.ObjSync) { current = ++c.Sequence; c.ExpiryDate = newExpDate; c.SourceList = list; c.Active = true; } void act() { try { Interlocked.Increment(ref _working); using (CEF.UseServiceScope(ss)) { // Process all items in parallel, building a list we'll turn into json but also potentially caching "by identity" per row ConcurrentBag <IDictionary <string, object> > rows = new ConcurrentBag <IDictionary <string, object> >(); var aiw = list.AllAsInfraWrapped().ToArray(); Parallel.ForEach(aiw, (iw) => { using (CEF.UseServiceScope(ss)) { rows.Add(iw.GetAllValues(true, true)); if ((mode & CacheBehavior.ConvertQueryToIdentity) != 0 && ((mode & CacheBehavior.ForAllDoesntConvertToIdentity) == 0 || string.Compare(text, "All", true) != 0)) { var uw = iw.AsUnwrapped() as T; if (uw != null) { AddByIdentity <T>(uw, expirySeconds: expirySeconds); } } } }); lock (c.ObjSync) { if (c.Sequence == current) { c.Rows = rows; c.SourceList = null; } } } } catch (Exception ex) { CEFDebug.WriteInfo($"Exception in cache serializer: {ex.Message}"); // Invalidate the entry is probably the safest c.Active = false; c.Properties = null; c.Rows = null; } finally { Interlocked.Decrement(ref _working); } } if (Globals.AsyncCacheUpdates) { Task.Factory.StartNew(act); } else { act(); } }
public void Shutdown() { WebView.Dispose(); System.Threading.Thread.Sleep(1000); CEF.Shutdown(); }
private void StartTests_Click(object sender, RoutedEventArgs e) { try { ConsoleList.Items.Clear(); StartTests.IsEnabled = false; RunBenchmark.IsEnabled = false; // If did a prior run, clear out ambient scope which is bound to the UI thread CEF.CurrentServiceScope.Dispose(); // Execute tear-down/set-up of test SQL objects from script CEF.CurrentDBService().ExecuteRaw("DELETE CEFTest.Phone; UPDATE CEFTest.Person SET IsDeleted=1, LastUpdatedDate=GETUTCDATE(), LastUpdatedBy='Test';"); var random = new Random(); var watch = new System.Diagnostics.Stopwatch(); watch.Start(); // Creates and saves a person in 2 lines of code! // Of note: no need for a context, we're using the implicit one created in TLS (great for a simple console app, recommended is to use explicit scopes) var tristan = CEF.NewObject(new Person() { Name = "Tristan", Age = 4, Gender = "M" }); ConsoleWriteLine($"Rows saved: {CEF.DBSave().Count()}"); ConsoleWriteLine($"A PersonID key as assigned by the database has been round-tripped back to us: {tristan.PersonID}"); ConsoleWriteLine($"And LastUpdatedDate as assigned by the database too, despite not being in our base POCO: {((PersonWrapped)tristan).LastUpdatedDate}"); // Creates and saves a person similar to above, but using wrapper object directly is fine too - and we've got an extension method that lets us save in 1 line of code! var zella = CEF.NewObject(new PersonWrapped() { Name = "Zella", Age = 7, Gender = "F" }).DBSave(); ConsoleWriteLine($"Similar to above, but already working with genned wrapper so no need to cast it: {zella.LastUpdatedDate}"); // We have the option to indicate whether the object should be considered new or not with respect to db, when adding to scope (CreateObject on the other hand is always "new") - in reality we could have used NewObject here too var sally = new Person() { Name = "Sally", Age = 34, Gender = "F" }; sally = CEF.IncludeObject(sally, ObjectState.Added); ConsoleWriteLine($"Should be 1: {CEF.DBSave().Count()}"); // Now make a change: we're changing the source model in a simple way - associating already saved kids to a person - should turn into 3 updates and 2 inserts (we can't stop people from adding non-wrapped items, so we watch for this and Billy gets replaced by a PersonWrapped on addition here, plus his phone gets accounted for as well) // Also of note, sally.Kids was previously null, and still is, so we initialize it with a trackable list (EntitySet is prefect) - Global.ReplaceNullCollections could have been set to true to do this automatically for us at the expense of performance sally.Kids = CEF.CreateList <Person>(sally, nameof(Person.Kids)); sally.Kids.Add(tristan); sally.Kids.Add(zella); var billy = new Person() { Name = "Billy", Age = 1, Gender = "M" }; ConsoleWriteLine($"Row state for Tristan: {tristan.AsInfraWrapped().GetRowState()}"); billy.Phones = new Phone[] { new Phone() { Number = "707-555-1236", PhoneTypeID = PhoneType.Mobile, Owner = billy } }; sally.Kids.Add(CEF.IncludeObject(billy, ObjectState.Added)); sally.Age += 1; billy.Age += 1; // On saving here, of note we're inserting a new person, getting their id back, carrying this down to the child (phone as the owner), saving the child - all this despite the Phone class not even *having* a PersonID on it (it's just the Owner property which assumes this relationship exists, and we established that in the setup) dynamic billyPhone = billy.Phones.First().AsDynamic(); ConsoleWriteLine($"Row state for Billy's phone: {billyPhone.GetRowState()}"); CEF.DBSave(); ConsoleWriteLine($"Billy's phone has a PhoneID tracked despite the POCO object model not containing this field: {billyPhone.PhoneID}"); // Remove Zella from Sally's kids - should just nullify the ParentPersonID sally.Kids.Remove(zella); CEF.DBSave(); // Put it back now sally.Kids.Add(zella); CEF.DBSave(); // Swap ownership of Billy's phone to Zella - saving should reflect Zella's new ownership (and Billy's non-ownership) // Note: our POCO here does not implement INotifyPropertyChanged, so this change in row state is not reflected until we do something meaningful (e.g. save) var phone = billy.Phones.First(); phone.Owner = zella; ConsoleWriteLine($"Row state for phone in question (unchanged): {phone.AsInfraWrapped().GetRowState()}"); CEF.DBSave(); // Ok, we're done..? If not, the local scope will be rebuilt next time it's used. In this case, all our prior work is wiped out, we're "starting fresh" CEF.CurrentServiceScope.Dispose(); // One way to repopulate our service scope is to load people with 2 retrievals: start with the parent (by key), then a second call (by parent id) for children - merge into the same set (extension method names help make that clearer) // The "by parent" retrieval is done as an extension method that we propose can and should be code generated based on the db object - forms a stronger contract with the db so if say a parameter changes, we could get a compile-time error to track down and fix // (We could also have created a procedure to "load family" in one call - a union for parent and children. In many cases, reducing DB round-trips helps performance at cost of a slightly more complex data layer.) // Next, delete parent (with cascade option), save (notice it properly deletes children first, then parent) // Framework has automtically wired up the relationships between parent and child such that marking the parent for deletion has automatically marked children for deletion as well // Note that removal from collection is not considered deletion - there could be other reasons you're removing from a collection, but might offer a way to interpret this as deletion on a one-off basis in future // Also note that we use Tristan's PersonID not "tristan" itself - scope was disposed above, no longer has wrappers, etc. // And what about Billy's phone? If it had audit history, we'd prefer to have the framework manage/delete it too (versus say leaving it to cascaded deletes in the database) - and we do achieve that because of an extra call to load Phones for a parent and all their kids // Important question: does a phone *require* an owner? This will be left to key service in vnext as it has an important implication on deletion here: cascade deletes or set to null where able to (for this example, cascades the deletion to the Phone) var sallysFamily = new EntitySet <Person>().DBRetrieveByKey(sally.PersonID).DBAppendByParentID(sally.PersonID); var sallysFamilyPhones = new EntitySet <Phone>().DBRetrieveAllForFamily(sally.PersonID); var newSally = (from a in sallysFamily where a.Kids != null && a.Kids.Any() select a).First(); var newTristan = (from a in sallysFamily where a.PersonID == tristan.PersonID select a).First(); ConsoleWriteLine($"Row state for Tristan (unchanged): {newTristan.AsInfraWrapped().GetRowState()}"); CEF.DeleteObject(newSally); ConsoleWriteLine($"Row state for Tristan (deleted): {newTristan.AsInfraWrapped().GetRowState()}"); ConsoleWriteLine($"Saved rows: {CEF.DBSave().Count()}"); ConsoleWriteLine("Please wait, starting background process."); Exception toReport = null; var backgroundTask = new Task(() => { try { using (CEF.NewServiceScope(new ServiceScopeSettings() { InitializeNullCollections = true })) { // Create an entire object graph using POCO's // Note that our arrays will end up getting coverted to EntitySet's automatically when we add the root (greatgrandpa) to the scope later // We can also intermix POCO and wrapper types at will var greatgrandpa = new Person() { Name = "Zeke", Age = 92, Gender = "M" }; var grandpa = new Person() { Name = "Zeke Jr.", Age = 70, Gender = "M" }; var mom = new PersonWrapped() { Name = "Wilma", Age = 48, Gender = "F" }; var me = new Person() { Name = "Joe", Age = 29, Gender = "M" }; // Notice, using linkages here that could/should be recognized either way as related data - this is testing the relationship existing *both* ways, should not fail var myphone = new Phone() { Owner = me, Number = "707-555-1919", PhoneTypeID = PhoneType.Home }; me.Phones = new Phone[] { myphone }; var auntie = new Person() { Name = "Betty", Age = 50, Gender = "F", Phones = new Phone[] { new Phone() { Number = "707-555-1240", PhoneTypeID = PhoneType.Home } } }; var cuz1 = new Person { Name = "Knarf", Age = 40, Gender = "M", Phones = new Phone[] { new Phone() { Number = "510-555-5555", PhoneTypeID = PhoneType.Mobile } } }; var cuz2 = new Person { Name = "Hazel", Age = 40, Gender = "F", Phones = new Phone[] { new Phone() { Number = "510-555-8888", PhoneTypeID = PhoneType.Mobile } } }; greatgrandpa.Kids = new Person[] { grandpa }; grandpa.Kids = new Person[] { auntie, mom }; auntie.Kids = new Person[] { cuz1, cuz2 }; CEF.IncludeObject(greatgrandpa, ObjectState.Added); myphone.PhoneTypeID = PhoneType.Mobile; // But wait, we didn't initialize mom.Kids with a collection instance! - some of the details of the current scope can be adjusted, such as above where we use InitializeNullCollections=true mom.Kids.Add(me); mom.Phones.Add(CEF.NewObject(new Phone() { Number = "510-555-2222", PhoneTypeID = PhoneType.Work })); // Creates 3 records in DB with parent-child relationship - we'll use an explict new scope (no visibility to any pending changes above) // Also demonstrates using 2 different connection scopes - default is transactional = true which is why we call CanCommit a la System.Transactions using (var ss = CEF.NewServiceScope()) { var joel = CEF.NewObject(new Person() { Name = "Joel", Age = 44, Gender = "M" }); var cellnum = CEF.NewObject(new Phone() { Owner = joel, PhoneTypeID = PhoneType.Mobile, Number = "707-555-1234" }); var worknum = CEF.NewObject(new Phone() { Owner = joel, PhoneTypeID = PhoneType.Work, Number = "707-555-1235" }); using (var cs = CEF.NewConnectionScope()) { // We could also use CEF.DBSave() since current scope will be "ss" now ConsoleWriteLine($"Should be 3: {ss.DBSave().Count()}"); // This should do nothing - nothing is actually dirty! ConsoleWriteLine($"Should be 0: {CEF.DBSave().Count()}"); // Updates 2 records (parent, child), delete other record, saves // Of note: Phone class is NOT wrapped by a code genned object - but it still gets saved properly (we miss out on notifications, etc. unless we explicitly ask for its infra wrapper which has these) // Also, we've updated the POCO for Joel - which has no notifications - this might be "lost" during save, but we do check for updates done in this manner and catch it joel.Age += 1; cellnum.Number = "707-555-7777"; CEF.DeleteObject(worknum); CEF.DBSave(); // This *does* reflect a change in the row state prior to saving since the wrapper class implements INotifyPropertyChanged... HOWEVER, we are in a transaction, and the initial row state of "added" remains joel.AsDynamic().Age += 1; ConsoleWriteLine($"Row state for Joel: {joel.AsInfraWrapped().GetRowState()}"); CEF.DBSave(); // A catch handler not calling this allows the transaction to naturally roll back cs.CanCommit(); } using (var cs = CEF.NewConnectionScope()) { // Finally, we can use this as a dynamic object as well and expect the same results... notice here, using our INotifyPropertyChanged wrapper does automatically change the row state... ((PersonWrapped)joel).Age += 1; ConsoleWriteLine($"Row state for Joel: {joel.AsInfraWrapped().GetRowState()}"); ConsoleWriteLine($"Initial saves, time: {watch.ElapsedMilliseconds} ms"); watch.Restart(); // This approach creates 10000 people with 2 phone numbers each. Saving is done using BULK INSERT, and is expectedly very fast. One constraint: we lose round-tripping of key assignment that was illustrated before. // Couple of options here, but in this case, I will save people, do a direct query to *just* retrieve people ID's (also illustrates partial loading), populate phone numbers based on that list and save again. EntitySet <Person> city = new EntitySet <Person>(); for (int i = 0; i < 10000; ++i) { city.Add(new Person() { Name = $"N{i}", Age = random.Next(1, 90), Gender = random.Next(2) == 0 ? "F" : "M" }); } // Default insert threshold to revert to BULK INSERT is 100,000 rows, so we use an explicit option to do this with 10,000 CEF.DBSave(new DBSaveSettings() { BulkInsertMinimumRows = 10000 }); ConsoleWriteLine($"Saved 10,000 new people, time: {watch.ElapsedMilliseconds} ms"); watch.Restart(); // Here's an example of using raw SQL: yes, we can do this even in the 0.2 release! Points to the fact we should expect more LINQ to SQL type of enhancements in the future // The fact we're loading a very lean Person entity set isn't a problem: we're not updating people here, we're just adding phones and it's nice to have people available to identify ownership (just assuming the ID's are sequential isn't a great idea, the database may have had other ideas!) using (CEF.NewServiceScope()) { EntitySet <Phone> phones = new EntitySet <Phone>(); foreach (var p in new EntitySet <Person>().DBRetrieveByQuery(CommandType.Text, "SELECT PersonID FROM CEFTest.Person")) { phones.Add(new Phone() { Owner = p, PhoneTypeID = PhoneType.Home, Number = $"{random.Next(10)}{random.Next(10)}{random.Next(10)}-{random.Next(10)}{random.Next(10)}{random.Next(10)}{random.Next(10)}" }); phones.Add(new Phone() { Owner = p, PhoneTypeID = PhoneType.Mobile, Number = $"{random.Next(10)}{random.Next(10)}{random.Next(10)}-{random.Next(10)}{random.Next(10)}{random.Next(10)}{random.Next(10)}" }); } // This method of saving limits to this specific set phones.DBSave(new DBSaveSettings() { BulkInsertMinimumRows = 10000, RowSavePreview = (row) => { return(true, ObjectState.Added); } }); } ConsoleWriteLine($"Saved 20,000 new phones, time: {watch.ElapsedMilliseconds} ms"); watch.Restart(); cs.CanCommit(); } }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); //Mutex runOnce = null; //if (Properties.Settings.Default.IsRestarting == true) //{ // Properties.Settings.Default.IsRestarting = false; // Properties.Settings.Default.Save(); //} try { bool flag = false; runOnce = new Mutex(true, "SINGLE_INSTANCE", out flag); if (flag) { //Application.EnableVisualStyles(); runOnce.ReleaseMutex(); RequestHandler.Init(); Application.Run(new ChatForm()); CEF.Shutdown(); } else { MessageBox.Show("程序已经运行!", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information); Application.Exit(); } } finally { if (runOnce != null) { runOnce.Close(); } } //Process[] processes = Process.GetProcessesByName("daishu_message"); //if (processes.Length >= 2) //{ // MessageBox.Show("程序已经运行!", "提醒", MessageBoxButtons.OK, MessageBoxIcon.Information); // return; //} //else //{ //LoginForm loginForm = new LoginForm(); //loginForm.ShowDialog(); //if (loginForm.DialogResult != DialogResult.Cancel) //{ // //} //} }
protected virtual void ProcessAdd(IList newItems, int newStartingIndex) { var niCopy = (from a in newItems.Cast <Object>() select a).ToList(); foreach (T ni in niCopy) { _contains[ni] = true; } if (!EnableIntegration) { return; } if (BoundScope != null) { // First, we inspect to see if we have a wrapped object or not - if not, we try to do so and REPLACE the current item if (!BoundScope.Settings.EntitySetUsesUnwrapped) { var idx2 = 0; foreach (var ni in niCopy.ToArray()) { if (ni != null) { if (BoundScope.InternalCreateAddBase(ni, AddedIsNew, null, null, null, new Dictionary <object, object>(Globals.DefaultDictionaryCapacity), true, false) is ICEFWrapper w) { var cast = w as T; if (ni != cast) { if (ni is T nit && cast != null) { try { this.SuspendNotifications(true); using (new WriterLock(LockInfo)) { this.Replace(nit, cast); _contains.Add(cast, true); if (newItems[idx2] is T nit2) { _contains.Remove(nit2); } } } finally { this.SuspendNotifications(false); } } niCopy[idx2] = cast; idx2++; } } } } } } if (ParentContainer != null && EnableLinking) { foreach (var ni in niCopy) { if (ni != null && BoundScope != null && ParentTypeName != null && ParentFieldName != null) { // Attempt to establish a FK relationship, carry parent key down CEF.CurrentKeyService()?.LinkChildInParentContainer(BoundScope, ParentTypeName, ParentFieldName, ParentContainer, ni); } } } }
public IEnumerable <T> GetItemsFromSerializationText <T>(string json, JsonSerializationSettings settings) where T : class, new() { if (settings == null) { settings = new JsonSerializationSettings(); } switch (settings.SerializationType) { case SerializationType.Array: { var setArray = JArray.Parse(json); foreach (var i in setArray.Children()) { if (i.Type == JTokenType.Object) { yield return(CEF.Deserialize <T>(i.ToString())); } } break; } case SerializationType.ObjectWithSchemaType1AndRows: { // Read schema Dictionary <string, Type> schema = new Dictionary <string, Type>(); var root = JObject.Parse(json); // Read schema foreach (var propInfo in root.GetValue(settings.SchemaName).ToArray()) { if (propInfo is JObject jo) { if (jo.Count < 2 || jo.Count > 3) { throw new CEFInvalidOperationException("Invalid JSON format."); } JProperty pn = (from a in jo.Children() let b = a as JProperty where b != null && b.Name.Equals(settings.SchemaFieldNameName) select b).FirstOrDefault(); JProperty pt = (from a in jo.Children() let b = a as JProperty where b != null && b.Name.Equals(settings.SchemaFieldTypeName) select b).FirstOrDefault(); JProperty pr = (from a in jo.Children() let b = a as JProperty where b != null && b.Name.Equals(settings.SchemaFieldRequiredName) select b).FirstOrDefault(); if (pn == null || pt == null) { throw new CEFInvalidOperationException("Invalid JSON format."); } var t = settings.GetDataType(pt.Value.ToString()); var torig = t; // Assume that any property might be omitted/missing which means everything should be considered nullable if (t.IsValueType && !(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable <>))) { t = typeof(Nullable <>).MakeGenericType(t); } var name = pn.Value.ToString(); schema[name] = t; // If is required, we add a validation for this if (pr != null && bool.TryParse(pr.Value.ToString(), out bool prv) && prv) { ValidationService.RegisterRequired <T>(torig, name); } } } // Read objects, using the schema as the "basis" where missing/omitted properties are still carried through foreach (var itemInfo in root.GetValue(settings.DataRootName).ToArray()) { var obj = CEF.Deserialize <T>(itemInfo.ToString()); var iw = obj.AsInfraWrapped(); // We need to apply property type settings after-the-fact var allProp = iw.GetAllValues(); foreach (var propInfo in schema) { var existingInfo = (from a in allProp where a.Key == propInfo.Key select(propInfo.Value, a.Value)); if (existingInfo.Any()) { iw.SetValue(propInfo.Key, existingInfo.First().Item2, existingInfo.First().Item1); } else { iw.SetValue(propInfo.Key, null, propInfo.Value); } } yield return(obj); } break; } } }
private void view_ExitActivated(object sender, EventArgs e) { model.Dispose(); CEF.Shutdown(); System.Environment.Exit(0); }
internal static void CopyParsePropertyValues(IDictionary <string, object?>?sourceProps, object target, bool isNew, ServiceScope?ss, IDictionary <object, object> visits, bool justTraverse) { // Can disable this to improve performance - default is enabled if (!Globals.DoCopyParseProperties) { return; } _propCache.TryGetValue(target.GetType(), out var dic); if (dic == null) { dic = (from a in target.FastGetAllProperties(true, true) select new { Name = a.name, PropertyType = a.type }).ToDictionary((p) => p.Name, (p) => p.PropertyType); _propCache[target.GetType()] = dic; } var iter = sourceProps == null ? (from t in dic select(t.Key, target.FastGetValue(t.Key), t.Value)) : (from s in sourceProps from t in dic where s.Key == t.Key select(s.Key, s.Value, t.Value)); var maxdop = Globals.EnableParallelPropertyParsing && Environment.ProcessorCount > 4 && iter.Count() >= Environment.ProcessorCount ? Environment.ProcessorCount >> 2 : 1; Interlocked.Add(ref _copyNesting, maxdop); try { void a((string PropName, object SourceVal, Type TargPropType) info) { object?wrapped = null; if (ss != null && IsWrappableListType(info.TargPropType, info.SourceVal)) { ICEFList?wrappedCol = null; if (ss.Settings.InitializeNullCollections || info.SourceVal != null) { // This by definition represents CHILDREN // Use an observable collection we control - namely EntitySet wrappedCol = CreateWrappingList(ss, info.TargPropType, target, info.PropName); target.FastSetValue(info.PropName, wrappedCol); } else { wrappedCol = info.SourceVal as ICEFList; } // Merge any existing data into the collection - as we do this, recursively construct wrappers! if (info.SourceVal != null && wrappedCol != null) { // Based on the above type checks, we know this thing supports IEnumerable var sValEnum = ((System.Collections.IEnumerable)info.SourceVal).GetEnumerator(); while (sValEnum.MoveNext()) { if (visits.ContainsKey(sValEnum.Current)) { wrapped = visits[sValEnum.Current] ?? sValEnum.Current; } else { wrapped = ss.InternalCreateAddBase(sValEnum.Current, isNew, null, null, null, visits, true, true); } if (wrapped != null) { wrappedCol.AddWrappedItem(wrapped); } } } if (wrappedCol != null && (ss.Settings.InitializeNullCollections || info.SourceVal != null)) { ((ISupportInitializeNotification)wrappedCol).EndInit(); } } else { // If the type is a ref type that we manage, then this property represents a PARENT and we should replace/track it (only if we have a PK for it: without one, can't be tracked) if (ss != null && info.SourceVal != null) { var svt = info.SourceVal.GetType(); if (!_sourceValTypeOk.TryGetValue(svt, out bool svtok)) { svtok = !svt.IsValueType && svt != typeof(string) && KeyService.ResolveKeyDefinitionForType(svt).Any(); _sourceValTypeOk[svt] = svtok; } if (svtok) { if (visits.ContainsKey(info.SourceVal)) { wrapped = visits[info.SourceVal] ?? info.SourceVal; } else { var to = ss.GetTrackedByWrapperOrTarget(info.SourceVal); if (to == null) { wrapped = ss.InternalCreateAddBase(info.SourceVal, isNew, null, null, null, visits, true, true); } else { wrapped = to.GetWrapperTarget(); } } if (wrapped != null) { target.FastSetValue(info.PropName, wrapped); } } else { if (!justTraverse) { target.FastSetValue(info.PropName, info.SourceVal); } } } else { if (!justTraverse) { target.FastSetValue(info.PropName, info.SourceVal); } } } } int resdop = Interlocked.Read(ref _copyNesting) > 12 ? 1 : maxdop; if (resdop == 1) { foreach (var info in iter) { a(info); } } else { ss ??= CEF.CurrentServiceScope; Parallel.ForEach(iter, new ParallelOptions() { MaxDegreeOfParallelism = resdop }, (info) => { using (CEF.UseServiceScope(ss)) { a(info); } }); } } finally { Interlocked.Add(ref _copyNesting, -maxdop); } }
/// <summary> /// Handles the ApplicationExit of System.Windows.Forms.Application. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The event arguments.</param> private static void Application_ApplicationExit(object sender, EventArgs e) { CEF.Shutdown(); }
public InteropDemo() { InitializeComponent(); string url = "http://127.0.0.1/rispweb/rispservice/ajaxSvrLogin.aspx"; m_cookie = RealsunClientNet.m_CookieContainer.GetCookies(new System.Uri(url))[0].ToString(); CEF.Initialize(new Settings { LogSeverity = LogSeverity.Disable, PackLoadingDisabled = true }); BrowserSettings browserSetting = new BrowserSettings { ApplicationCacheDisabled = true, PageCacheDisabled = true }; setCefCookie(m_cookie); _view = new WebView(string.Empty, browserSetting) { Address = m_url, RequestHandler = this, Background = Brushes.White }; _view.RegisterJsObject("callbackObj", new CallbackObjectForJs()); _view.LoadCompleted += _view_LoadCompleted; MainGrid.Children.Insert(0, _view); /*new code */ //var setting = new CefSharp.CefSettings(); //BrowserSettings a = new BrowserSettings(); //////CEF.Initialize(new Settings { LogSeverity = LogSeverity.Disable, PackLoadingDisabled = true }); //////BrowserSettings browserSetting = new BrowserSettings { ApplicationCacheDisabled = true, PageCacheDisabled = true }; //////_view = new WebView(string.Empty, browserSetting) //////{ ////// Address = url, ////// RequestHandler = this, ////// Background = Brushes.White //////}; //////_view.RegisterJsObject("callbackObj", new CallbackObjectForJs()); //////_view.LoadCompleted += _view_LoadCompleted; //////MainGrid.Children.Insert(0, _view); //_view = new CefSharp.Wpf.ChromiumWebBrowser(); //if (!Cef.IsInitialized) //{ // Cef.Initialize(setting, true, false); //} //_view.Loaded += _view_Loaded; //_view.Address = m_url; //MainGrid.Children.Insert(0, _view); ////_view.Load(m_url); ////CEF.Initialize(new Settings { LogSeverity = LogSeverity.Disable, PackLoadingDisabled = true }); ///*old code */ ////var setting = new CefSharp.CefSettings(); ////if (!Cef.IsInitialized) ////{ CefSharp.Cef.Initialize(setting, true, false); } ////var webView = new CefSharp.Wpf.ChromiumWebBrowser(); ////this.Content = webView; ////setCefCookie(m_cookie); ////webView.Address = m_url; ////setcookie(m_cookie); ////WebBrowser.Url = new System.Uri(m_url); }
public static void Benchmark1SavePer(int total_parents, List <long> testTimes, List <long> testTimes2, ref int rowcount, ref int rowcount2) { var watch = new System.Diagnostics.Stopwatch(); watch.Start(); long cnt1 = 0; var people = new EntitySet <PersonWrapped>(); Parallel.For(1, total_parents + 1, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, (parentcnt) => { using (CEF.NewServiceScope()) { var parent = CEF.NewObject(new PersonWrapped() { Name = $"NP{parentcnt}", Age = (parentcnt % 60) + 20, Gender = (parentcnt % 2) == 0 ? "F" : "M" }); parent.Phones.Add(new Phone() { Number = "888-7777", PhoneTypeID = PhoneType.Mobile }); parent.Phones.Add(new Phone() { Number = "777-6666", PhoneTypeID = PhoneType.Work }); if ((parentcnt % 12) == 0) { CEF.NewObject(new Phone() { Number = "666-5555", PhoneTypeID = PhoneType.Home }); } else { parent.Phones.Add(new Phone() { Number = "777-6666", PhoneTypeID = PhoneType.Home }); } Interlocked.Add(ref cnt1, 4); for (int childcnt = 1; childcnt <= (parentcnt % 4); ++childcnt) { var child = CEF.NewObject(new PersonWrapped() { Name = $"NC{parentcnt}{childcnt}", Age = parent.Age - 20, Gender = (parentcnt % 2) == 0 ? "F" : "M" , Phones = new Phone[] { new Phone() { Number = "999-8888", PhoneTypeID = PhoneType.Mobile } } }); parent.Kids.Add(child); Interlocked.Add(ref cnt1, 2); } CEF.DBSave(); people.Add(parent); } }); rowcount += (int)cnt1; testTimes.Add(watch.ElapsedMilliseconds); watch.Restart(); long cnt2 = 0; // For purposes of benchmarking, treat this as a completely separate operation // For everyone who's a parent of at least 30 yo, if at least 2 children of same sex, remove work phone, increment age using (var ss = CEF.NewServiceScope()) { var people2 = new EntitySet <Person>().DBRetrieveSummaryForParents(30); Parallel.ForEach((from a in people2 let d = a.AsDynamic() where d.MaleChildren > 1 || d.FemaleChildren > 1 select a).ToList(), (p) => { using (CEF.UseServiceScope(ss)) { p.AsInfraWrapped().SetValue(nameof(Person.Age), p.Age + 1); var ph2 = new EntitySet <Phone>().DBRetrieveByOwner(p.PersonID, PhoneType.Work).FirstOrDefault(); if (ph2 != null) { CEF.DeleteObject(ph2); } p.DBSave(); Interlocked.Add(ref cnt2, 2); } }); } rowcount2 += (int)cnt2; watch.Stop(); testTimes2.Add(watch.ElapsedMilliseconds); }
private void ExitMenuItemClick(object sender, EventArgs e) { browser.Dispose(); CEF.Shutdown(); Close(); }