public void NativeInstancePropertySetMessage() { var ctx = new LocalContext(); var inst = new PropertyTestClass(); ctx.SetVariable("x", new STInstance(inst)); compiler.Evaluate("x instanceProperty: 3", ctx); Assert.AreEqual((long)3, inst.InstanceProperty); }
public void NativeInstancePropertyGetMessage() { var ctx = new LocalContext(); var inst = new PropertyTestClass(); inst.InstanceProperty = 3; ctx.SetVariable("x", new STInstance(inst)); var three = compiler.Evaluate("x instanceProperty", ctx); Assert.IsNotNull(three); Assert.IsInstanceOfType(typeof(STInstance), three); Assert.AreEqual((three as STInstance).Target, (long)3); }
public async void HookedDbContext_MustCallHooks_WhenRunningSaveChangesAsync() { var hooks = new IHook[] { new TimestampPreInsertHook() }; var context = new LocalContext(hooks); var entity = new TimestampedSoftDeletedEntity(); context.Entities.Add(entity); await context.SaveChangesAsync(); Assert.AreEqual(entity.CreatedAt.Date, DateTime.Today); }
/// <summary> /// This function will bake the objects in the given receiver. Behaviour: /// 1) Fresh bake: objects are created /// 2) Diff bake: old objects are deleted, any overlapping objects (by applicationId) are either edited or left alone if not marked as having been user modified, new objects are created. /// </summary> /// <param name="args">Serialised client coming from the ui.</param> public override void BakeReceiver(string args) { var client = JsonConvert.DeserializeObject <dynamic>(args); var apiClient = new SpeckleApiClient((string)client.account.RestApi) { AuthToken = (string)client.account.Token }; apiClient.ClientType = "Revit"; //dispatch on the cef window to let progress bar update SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, loadingBlurb = "Getting stream from server..." })); }, System.Windows.Threading.DispatcherPriority.Background); var previousStream = LocalState.FirstOrDefault(s => s.StreamId == (string)client.streamId); var stream = apiClient.StreamGetAsync((string)client.streamId, "").Result.Resource; InjectScaleInKits(GetScale((string)stream.BaseProperties.units)); var test = stream.BaseProperties.unitsDictionary; if (test != null) { var secondTest = JsonConvert.DeserializeObject <Dictionary <string, string> >(JsonConvert.SerializeObject(test)); InjectUnitDictionaryInKits(secondTest); } else { InjectUnitDictionaryInKits(null); // make sure it's not there to potentially muddy the waters on other conversions } // If it's the first time we bake this stream, create a local shadow copy if (previousStream == null) { previousStream = new SpeckleStream() { StreamId = stream.StreamId, Objects = new List <SpeckleObject>() }; LocalState.Add(previousStream); } LocalContext.GetCachedObjects(stream.Objects, (string)client.account.RestApi); var payload = stream.Objects.Where(o => o.Type == "Placeholder").Select(obj => obj._id).ToArray(); // TODO: Orchestrate & save in cache afterwards! var objects = apiClient.ObjectGetBulkAsync(payload, "").Result.Resources; foreach (var obj in objects) { stream.Objects[stream.Objects.FindIndex(o => o._id == obj._id)] = obj; } var(toDelete, ToAddOrMod) = DiffStreamStates(previousStream, stream); SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, loadingBlurb = "Deleting " + toDelete.Count() + " objects.", objects = stream.Objects })); }, System.Windows.Threading.DispatcherPriority.Background); // DELETION OF OLD OBJECTS if (toDelete.Count() > 0) { Queue.Add(new Action(() => { using (Transaction t = new Transaction(CurrentDoc.Document, "Speckle Delete (" + (string)client.streamId + ")")) { t.Start(); foreach (var obj in toDelete) { var myObj = previousStream.Objects.FirstOrDefault(o => o._id == obj._id); if (myObj != null) { var elem = CurrentDoc.Document.GetElement(myObj.Properties["revitUniqueId"] as string); CurrentDoc.Document.Delete(elem.Id); } } t.Commit(); } })); Executor.Raise(); } // ADD/MOD/LEAVE ALONE EXISTING OBJECTS //if the conversion completely fails, it outputs a speckleerror and it's put in here var errors = new List <SpeckleError>(); //this instead will store errors swallowed by the erroreater class Globals.ConversionErrors = new List <SpeckleError>(); var tempList = new List <SpeckleObject>(); Queue.Add(new Action(() => { using (var t = new Transaction(CurrentDoc.Document, "Speckle Bake")) { t.Start(); int i = 0; foreach (var mySpkObj in ToAddOrMod) { SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, isLoadingIndeterminate = false, loadingProgress = 1f * i / ToAddOrMod.Count * 100, loadingBlurb = string.Format("Creating/updating objects: {0} / {1}", i, ToAddOrMod.Count) })); }, System.Windows.Threading.DispatcherPriority.Background); object res; var failOpts = t.GetFailureHandlingOptions(); failOpts.SetFailuresPreprocessor(new ErrorEater()); t.SetFailureHandlingOptions(failOpts); try { res = SpeckleCore.Converter.Deserialise(obj: mySpkObj, excludeAssebmlies: new string[] { "SpeckleCoreGeometryDynamo", "SpeckleCoreGeometryRevit" }); // The converter returns either the converted object, or the original speckle object if it failed to deserialise it. // Hence, we need to create a shadow copy of the baked element only if deserialisation was succesful. if (res is Element) { // creates a shadow copy of the baked object to store in our local state. var myObject = new SpeckleObject() { Properties = new Dictionary <string, object>() }; myObject._id = mySpkObj._id; myObject.ApplicationId = mySpkObj.ApplicationId; myObject.Properties["__type"] = mySpkObj.Type; myObject.Properties["revitUniqueId"] = ((Element)res).UniqueId; myObject.Properties["revitId"] = ((Element)res).Id.ToString(); myObject.Properties["userModified"] = false; tempList.Add(myObject); } // TODO: Handle scenario when one object creates more objects. // ie: SpeckleElements wall with a base curve that is a polyline/polycurve if (res is System.Collections.IEnumerable) { int k = 0; var xx = ((IEnumerable <object>)res).Cast <Element>(); foreach (var elm in xx) { var myObject = new SpeckleObject(); myObject._id = mySpkObj._id; myObject.ApplicationId = mySpkObj.ApplicationId; myObject.Properties["__type"] = mySpkObj.Type; myObject.Properties["revitUniqueId"] = ((Element)elm).UniqueId; myObject.Properties["revitId"] = ((Element)elm).Id.ToString(); myObject.Properties["userModified"] = false; myObject.Properties["orderIndex"] = k++; // keeps track of which elm it actually is tempList.Add(myObject); } } //if( res is SpeckleObject || res == null ) failedToBake++; if (res is SpeckleError) { errors.Add(res as SpeckleError); } } catch (Exception e) { //if(e.Message.Contains("missing")) //failedToBake++; errors.Add(new SpeckleError { Message = e.Message }); } i++; } t.Commit(); } })); Executor.Raise(); Queue.Add(new Action(() => { SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, isLoadingIndeterminate = true, loadingBlurb = string.Format("Updating shadow state.") })); }, System.Windows.Threading.DispatcherPriority.Background); // set the local state stream's object list, and inject it in the kits, persist it in the doc previousStream.Objects = tempList; InjectStateInKits(); using (var t = new Transaction(CurrentDoc.Document, "Speckle State Save")) { t.Start(); Storage.SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState); t.Commit(); } string errorMsg = ""; int failedToConvert = errors.Count(); //other conversion errors that we are catching var additionalErrors = GetAndClearConversionErrors(); if (additionalErrors != null && additionalErrors.Count > 0) { errors.AddRange(additionalErrors); } errors.AddRange(Globals.ConversionErrors); //remove duplicates errors = errors.GroupBy(x => x.Message).Select(x => x.First()).ToList(); if (errors.Any()) { errorMsg += string.Format("There {0} {1} error{2} ", errors.Count() == 1 ? "is" : "are", errors.Count(), errors.Count() == 1 ? "" : "s"); if (failedToConvert > 0) { errorMsg += string.Format("and {0} objects that failed to convert ", failedToConvert, failedToConvert == 1 ? "" : "s"); } errorMsg += "<nobr>" + Globals.GetRandomSadFace() + "</nobr>"; } //if(errors.Any()) //{ // errorMsg += "" + // //errors += "<v-divider></v-divider>" + // "<v-layout row wrap><v-flex xs12>"; // //"<strong>Missing families:</strong> "; // foreach( var err in errors) // { // errorMsg += $"<code>{err.Message}</code> "; // } // errorMsg += "</v-flex></v-layout>"; //} SpeckleWindow.Dispatcher.Invoke(() => { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = false, isLoadingIndeterminate = true, loadingBlurb = string.Format("Done."), errorMsg, errors })); }, System.Windows.Threading.DispatcherPriority.Background); })); Executor.Raise(); }
public UsingStatementState(LocalContext context, CombinedSyntaxNode contextNode) : base(context, contextNode) { }
public ListUsersViewModel(LocalContext localContext) { LocalContext = localContext; }
public async void SendStaggeredUpdate(bool force = false) { if (Paused && !force) { Context.NotifySpeckleFrame("client-expired", StreamId, ""); return; } else { // create a clone var cloneResult = Client.StreamCloneAsync(StreamId).Result; Client.Stream.Children.Add(cloneResult.Clone.StreamId); Client.BroadcastMessage("stream", StreamId, new { eventType = "update-children" }); } if (IsSendingUpdate) { Expired = true; return; } IsSendingUpdate = true; Context.NotifySpeckleFrame("client-is-loading", StreamId, ""); var objs = RhinoDoc.ActiveDoc.Objects.FindByUserString("spk_" + this.StreamId, "*", false).OrderBy(obj => obj.Attributes.LayerIndex); Context.NotifySpeckleFrame("client-progress-message", StreamId, "Converting " + objs.Count() + " objects..."); // layer list creation var pLayers = new List <SpeckleCore.Layer>(); int lindex = -1, count = 0, orderIndex = 0; foreach (RhinoObject obj in objs) { Rhino.DocObjects.Layer layer = RhinoDoc.ActiveDoc.Layers[obj.Attributes.LayerIndex]; if (lindex != obj.Attributes.LayerIndex) { var spkLayer = new SpeckleCore.Layer() { Name = layer.FullPath, Guid = layer.Id.ToString(), ObjectCount = 1, StartIndex = count, OrderIndex = orderIndex++, Properties = new LayerProperties() { Color = new SpeckleCore.SpeckleBaseColor() { A = 1, Hex = System.Drawing.ColorTranslator.ToHtml(layer.Color) }, } }; pLayers.Add(spkLayer); lindex = obj.Attributes.LayerIndex; } else { var spkl = pLayers.FirstOrDefault(pl => pl.Name == layer.FullPath); spkl.ObjectCount++; } count++; } // convert objects var convertedObjects = new List <SpeckleObject>(); foreach (RhinoObject obj in objs) { var myObj = Converter.Serialise(obj.Geometry); myObj.ApplicationId = obj.Id.ToString(); convertedObjects.Add(myObj); } LocalContext.PruneExistingObjects(convertedObjects, Client.BaseUrl); List <SpeckleObject> persistedObjects = new List <SpeckleObject>(); if (convertedObjects.Count(obj => obj.Type == "Placeholder") != convertedObjects.Count) { // create the update payloads count = 0; var objectUpdatePayloads = new List <List <SpeckleObject> >(); long totalBucketSize = 0; long currentBucketSize = 0; var currentBucketObjects = new List <SpeckleObject>(); var allObjects = new List <SpeckleObject>(); foreach (SpeckleObject convertedObject in convertedObjects) { if (count++ % 100 == 0) { Context.NotifySpeckleFrame("client-progress-message", StreamId, "Converted " + count + " objects out of " + objs.Count() + "."); } // size checking & bulk object creation payloads creation long size = Converter.getBytes(convertedObject).Length; currentBucketSize += size; totalBucketSize += size; currentBucketObjects.Add(convertedObject); // Object is too big? if (size > 2e6) { Context.NotifySpeckleFrame("client-error", StreamId, JsonConvert.SerializeObject("This stream contains a super big object. These will fail. Sorry for the bad error message - we're working on improving this.")); currentBucketObjects.Remove(convertedObject); } if (currentBucketSize > 5e5) // restrict max to ~500kb; should it be user config? anyway these functions should go into core. at one point. { Debug.WriteLine("Reached payload limit. Making a new one, current #: " + objectUpdatePayloads.Count); objectUpdatePayloads.Add(currentBucketObjects); currentBucketObjects = new List <SpeckleObject>(); currentBucketSize = 0; } } // add in the last bucket if (currentBucketObjects.Count > 0) { objectUpdatePayloads.Add(currentBucketObjects); } Debug.WriteLine("Finished, payload object update count is: " + objectUpdatePayloads.Count + " total bucket size is (kb) " + totalBucketSize / 1000); // create bulk object creation tasks int k = 0; List <ResponseObject> responses = new List <ResponseObject>(); foreach (var payload in objectUpdatePayloads) { Context.NotifySpeckleFrame("client-progress-message", StreamId, String.Format("Sending payload {0} out of {1}", k++, objectUpdatePayloads.Count)); try { var objResponse = await Client.ObjectCreateAsync(payload); responses.Add(objResponse); persistedObjects.AddRange(objResponse.Resources); int m = 0; foreach (var oL in payload) { oL._id = objResponse.Resources[m++]._id; } // push sent objects in the cache non-blocking Task.Run(() => { foreach (var oL in payload) { if (oL.Type != "Placeholder") { LocalContext.AddSentObject(oL, Client.BaseUrl); } } }); } catch (Exception err) { Context.NotifySpeckleFrame("client-error", Client.Stream.StreamId, JsonConvert.SerializeObject(err.Message)); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); IsSendingUpdate = false; return; } } } else { persistedObjects = convertedObjects; } Context.NotifySpeckleFrame("client-progress-message", StreamId, "Updating stream..."); // finalise layer creation foreach (var layer in pLayers) { layer.Topology = "0-" + layer.ObjectCount + " "; } // create placeholders for stream update payload List <SpeckleObject> placeholders = new List <SpeckleObject>(); //foreach ( var myResponse in responses ) foreach (var obj in persistedObjects) { placeholders.Add(new SpecklePlaceholder() { _id = obj._id }); } // create stream update payload SpeckleStream streamUpdatePayload = new SpeckleStream(); streamUpdatePayload.Layers = pLayers; streamUpdatePayload.Objects = placeholders; streamUpdatePayload.Name = Client.Stream.Name; // set some base properties (will be overwritten) var baseProps = new Dictionary <string, object>(); baseProps["units"] = RhinoDoc.ActiveDoc.ModelUnitSystem.ToString(); baseProps["tolerance"] = RhinoDoc.ActiveDoc.ModelAbsoluteTolerance; baseProps["angleTolerance"] = RhinoDoc.ActiveDoc.ModelAngleToleranceRadians; streamUpdatePayload.BaseProperties = baseProps; // update the stream ResponseBase response = null; try { response = await Client.StreamUpdateAsync(Client.Stream.StreamId, streamUpdatePayload); } catch (Exception err) { Context.NotifySpeckleFrame("client-error", Client.Stream.StreamId, JsonConvert.SerializeObject(err.Message)); IsSendingUpdate = false; return; } // emit events, etc. Client.Stream.Layers = streamUpdatePayload.Layers.ToList(); Client.Stream.Objects = placeholders; Context.NotifySpeckleFrame("client-metadata-update", StreamId, Client.Stream.ToJson()); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); Client.BroadcastMessage("stream", StreamId, new { eventType = "update-global" }); IsSendingUpdate = false; if (Expired) { DataSender.Start(); } Expired = false; }
private List<ICompletionListItem> HandleValueCompletion(LocalContext context) { var items = new List<ICompletionListItem>(); AddProperties(items, context.Property); if (items.Count > 0) items.Add(new CompletionItem("inherit", ItemKind.Value)); return items; }
private void HandleCompletion(CompleteMode mode, LocalContext context, bool autoInsert, bool autoHide) { List<ICompletionListItem> items = null; switch (mode) { case CompleteMode.Selector: items = HandleSelectorCompletion(context); break; case CompleteMode.Pseudo: items = HandlePseudoCompletion(context); break; case CompleteMode.Prefix: items = HandlePrefixCompletion(context); break; case CompleteMode.Attribute: items = HandlePropertyCompletion(context); break; case CompleteMode.Variable: items = HandleVariableCompletion(context); break; case CompleteMode.Value: items = HandleValueCompletion(context); break; } if (items == null) return; if (autoInsert && !string.IsNullOrEmpty(context.Word)) { var matches = new List<ICompletionListItem>(); foreach(var item in items) if (item.Label.StartsWith(context.Word)) matches.Add(item); if (matches.Count == 1) { ScintillaControl sci = PluginBase.MainForm.CurrentDocument.SciControl; sci.SetSel(context.Position, sci.CurrentPos); sci.ReplaceSel(matches[0].Label); } //else } else CompletionList.Show(items, autoHide, context.Word); }
public EmployeewsOfLocalPOS() { context = new LocalContext(); }
private void ParseSpecialProperty(LocalContext context, string propertyName) { var propertyConfiguration = this.vw.Settings.PropertyConfiguration; // special fields if (propertyName.Equals(propertyConfiguration.LabelProperty, StringComparison.Ordinal)) { // passed in label has precedence if (label == null) this.ParseLabel(); else reader.Skip(); } else if (propertyName.Equals(propertyConfiguration.TextProperty, StringComparison.Ordinal)) { // parse text segment feature this.defaultMarshaller.MarshalFeatureStringSplit( context.Context, context.Namespace, new Feature(propertyName), reader.ReadAsString()); } else if (propertyName.Equals(propertyConfiguration.LabelIndexProperty, StringComparison.Ordinal)) { if (!this.reader.Read()) throw new VowpalWabbitJsonException(this.reader, "Unexpected end"); this.LabelIndex = (int)(long)this.reader.Value; } else if (propertyName.StartsWith(propertyConfiguration.LabelPropertyPrefix, StringComparison.Ordinal)) { if (!this.reader.Read()) throw new VowpalWabbitJsonException(this.reader, "Unexpected end"); if (this.labelObject == null) this.labelObject = new JObject(); var targetPropertyName = propertyName.Substring(propertyConfiguration.LabelPropertyPrefix.Length); this.labelObject.Add(targetPropertyName, new JValue(this.reader.Value)); } else { if (propertyName.Equals(propertyConfiguration.MultiProperty, StringComparison.Ordinal)) this.foundMulti = true; // forward to handler if (specialPropertyAction == null || !specialPropertyAction(propertyName)) reader.Skip(); // if not handled, skip it } }
/// <summary> /// Parses { "feature1":1, "feature2":true, .... } /// </summary> private void ParseNamespaceAndFeatures(List<LocalContext> path, string namespaceValue) { LocalContext localContext = null; try { var ns = new Namespace(this.vw, namespaceValue); localContext = new LocalContext { Namespace = ns, Context = new VowpalWabbitMarshalContext(this.vw, this.DefaultNamespaceContext.ExampleBuilder), JsonProperty = namespaceValue }; path.Add(localContext); var propertyConfiguration = this.vw.Settings.PropertyConfiguration; this.defaultMarshaller.MarshalNamespace(localContext.Context, ns, () => this.ParseProperties(path)); path.RemoveAt(path.Count - 1); // append default namespaces features if we found some if (this.vw.Settings.EnableStringExampleGeneration) { var str = localContext.Context.ToString(); if (str.Length > 0) this.namespaceStrings.Add(str); } } finally { if (localContext != null && localContext.Context != null) localContext.Context.Dispose(); } }
public OneMaterialViewModel(LocalContext localContext) { LocalContext = localContext; }
// Drives the topology components public void RunTestCase() { // An empty dictionary for use when creating components Dictionary <string, Object> emptyDictionary = new Dictionary <string, object>(); #region Test the spout { Console.WriteLine("Starting spout"); // LocalContext is a local-mode context that can be used to initialize // components in the development environment. LocalContext spoutCtx = LocalContext.Get(); // Get a new instance of the spout, using the local context Spout sentences = Spout.Get(spoutCtx, emptyDictionary); // Emit 10 tuples for (int i = 0; i < 10; i++) { sentences.NextTuple(emptyDictionary); } // Use LocalContext to persist the data stream to file spoutCtx.WriteMsgQueueToFile("sentences.txt"); Console.WriteLine("Spout finished"); } #endregion #region Test the splitter bolt { Console.WriteLine("Starting splitter bolt"); // LocalContext is a local-mode context that can be used to initialize // components in the development environment. LocalContext splitterCtx = LocalContext.Get(); // Get a new instance of the bolt Splitter splitter = Splitter.Get(splitterCtx, emptyDictionary); // Set the data stream to the data created by the spout splitterCtx.ReadFromFileToMsgQueue("sentences.txt"); // Get a batch of tuples from the stream List <SCPTuple> batch = splitterCtx.RecvFromMsgQueue(); // Process each tuple in the batch foreach (SCPTuple tuple in batch) { splitter.Execute(tuple); } // Use LocalContext to persist the data stream to file splitterCtx.WriteMsgQueueToFile("splitter.txt"); Console.WriteLine("Splitter bolt finished"); } #endregion #region Test the counter bolt { Console.WriteLine("Starting counter bolt"); // LocalContext is a local-mode context that can be used to initialize // components in the development environment. LocalContext counterCtx = LocalContext.Get(); // Get a new instance of the bolt Counter counter = Counter.Get(counterCtx, emptyDictionary); // Set the data stream to the data created by splitter bolt counterCtx.ReadFromFileToMsgQueue("splitter.txt"); // Get a batch of tuples from the stream List <SCPTuple> batch = counterCtx.RecvFromMsgQueue(); // Process each tuple in the batch foreach (SCPTuple tuple in batch) { counter.Execute(tuple); } // Use LocalContext to persist the data stream to file counterCtx.WriteMsgQueueToFile("counter.txt"); Console.WriteLine("Counter bolt finished"); } #endregion }
public void HookEntityMetadata_MetadataWithContext() { var context = new LocalContext(); var result = new HookEntityMetadata(EntityState.Modified, context); Assert.AreEqual(context, result.CurrentContext); }
public virtual void UpdateGlobal( ) { if (IsUpdating) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "New update received while update was in progress. Please refresh."); return; } IsUpdating = true; var getStream = Client.StreamGetAsync(Client.StreamId, null).Result; NickName = getStream.Resource.Name; Layers = getStream.Resource.Layers.ToList(); Client.Stream = getStream.Resource; // add or update the newly received stream in the cache. LocalContext.AddOrUpdateStream(Client.Stream, Client.BaseUrl); this.Message = "Getting objects!"; // pass the object list through a cache check LocalContext.GetCachedObjects(Client.Stream.Objects, Client.BaseUrl); // filter out the objects that were not in the cache and still need to be retrieved var payload = Client.Stream.Objects.Where(o => o.Type == "Placeholder").Select(obj => obj._id).ToArray(); // how many objects to request from the api at a time int maxObjRequestCount = 42; // list to hold them into var newObjects = new List <SpeckleObject>(); // jump in `maxObjRequestCount` increments through the payload array for (int i = 0; i < payload.Length; i += maxObjRequestCount) { // create a subset var subPayload = payload.Skip(i).Take(maxObjRequestCount).ToArray(); // get it sync as this is always execed out of the main thread var res = Client.ObjectGetBulkAsync(subPayload, "omit=displayValue").Result; // put them in our bucket newObjects.AddRange(res.Resources); this.Message = JsonConvert.SerializeObject(String.Format("{0}/{1}", i, payload.Length)); } foreach (var obj in newObjects) { var locationInStream = Client.Stream.Objects.FindIndex(o => o._id == obj._id); try { Client.Stream.Objects[locationInStream] = obj; } catch { } } // add objects to cache async Task.Run(() => { foreach (var obj in newObjects) { LocalContext.AddCachedObject(obj, Client.BaseUrl); } }); // set ports UpdateOutputStructure(); this.Message = "Converting..."; SpeckleObjects.Clear(); ConvertedObjects = SpeckleCore.Converter.Deserialise(Client.Stream.Objects); this.Message = "Got data\n@" + DateTime.Now.ToString("hh:mm:ss"); IsUpdating = false; Rhino.RhinoApp.MainApplicationWindow.Invoke(expireComponentAction); }
public void UpdateGlobal( ) { Context.NotifySpeckleFrame("client-log", StreamId, JsonConvert.SerializeObject("Global update received.")); try { var streamGetResponse = Client.StreamGetAsync(StreamId, null).Result; if (streamGetResponse.Success == false) { Context.NotifySpeckleFrame("client-error", StreamId, streamGetResponse.Message); // TODO // Try and get from cache // First stream // Then objects } else { Client.Stream = streamGetResponse.Resource; Context.NotifySpeckleFrame("client-metadata-update", StreamId, Client.Stream.ToJson()); Context.NotifySpeckleFrame("client-is-loading", StreamId, ""); // add or update the newly received stream in the cache. LocalContext.AddOrUpdateStream(Client.Stream, Client.BaseUrl); // pass the object list through a cache check LocalContext.GetCachedObjects(Client.Stream.Objects, Client.BaseUrl); // filter out the objects that were not in the cache and still need to be retrieved var payload = Client.Stream.Objects.Where(o => o.Type == "Placeholder").Select(obj => obj._id).ToArray(); // how many objects to request from the api at a time int maxObjRequestCount = 20; // list to hold them into var newObjects = new List <SpeckleObject>(); // jump in `maxObjRequestCount` increments through the payload array for (int i = 0; i < payload.Length; i += maxObjRequestCount) { // create a subset var subPayload = payload.Skip(i).Take(maxObjRequestCount).ToArray(); // get it sync as this is always execed out of the main thread var res = Client.ObjectGetBulkAsync(subPayload, "omit=displayValue").Result; // put them in our bucket newObjects.AddRange(res.Resources); Context.NotifySpeckleFrame("client-log", StreamId, JsonConvert.SerializeObject(String.Format("Got {0} out of {1} objects.", i, payload.Length))); } // populate the retrieved objects in the original stream's object list foreach (var obj in newObjects) { var locationInStream = Client.Stream.Objects.FindIndex(o => o._id == obj._id); try { Client.Stream.Objects[locationInStream] = obj; } catch { } } // add objects to cache async Task.Run(() => { foreach (var obj in newObjects) { LocalContext.AddCachedObject(obj, Client.BaseUrl); } }); DisplayContents(); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); } } catch (Exception err) { Context.NotifySpeckleFrame("client-error", Client.Stream.StreamId, JsonConvert.SerializeObject(err.Message)); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); return; } }
public EmployeewsOfLocalPOS(string connectionString) { context = new LocalContext(connectionString); }
private List<ICompletionListItem> HandlePrefixCompletion(LocalContext context) { return prefixes; }
public override void AddedToDocument(GH_Document document) { base.AddedToDocument(document); Document = OnPingDocument(); if (Client == null) { Locked = true; NickName = "Initialising"; Account account = null; try { account = LocalContext.GetDefaultAccount(); RestApi = account.RestApi; Client = new SpeckleApiClient(account.RestApi); Client.IntializeSender(account.Token, Document.DisplayName, "Grasshopper", Document.DocumentID.ToString()).ContinueWith(task => { Rhino.RhinoApp.InvokeOnUiThread(ExpireComponentAction); }); } catch (Exception err) { } if (account == null) { var signInWindow = new SpecklePopup.SignInWindow(true); var helper = new System.Windows.Interop.WindowInteropHelper(signInWindow); helper.Owner = Rhino.RhinoApp.MainWindowHandle(); signInWindow.ShowDialog(); if (signInWindow.AccountListBox.SelectedIndex != -1) { account = signInWindow.accounts[signInWindow.AccountListBox.SelectedIndex]; RestApi = account.RestApi; Client = new SpeckleApiClient(account.RestApi); Client.IntializeSender(account.Token, Document.DisplayName, "Grasshopper", Document.DocumentID.ToString()).ContinueWith(task => { Rhino.RhinoApp.InvokeOnUiThread(ExpireComponentAction); }); } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Account selection failed."); return; } } } else { } Client.OnReady += (sender, e) => { StreamId = Client.StreamId; if (!WasSerialised) { Locked = false; NickName = "Anonymous Stream"; } ////this.UpdateMetadata(); Rhino.RhinoApp.InvokeOnUiThread(ExpireComponentAction); }; Client.OnWsMessage += OnWsMessage; Client.OnLogData += (sender, e) => { Log += DateTime.Now.ToString("dd:HH:mm:ss ") + e.EventData + "\n"; }; Client.OnError += (sender, e) => { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.EventName + ": " + e.EventData); Log += DateTime.Now.ToString("dd:HH:mm:ss ") + e.EventData + "\n"; }; ExpireComponentAction = () => ExpireSolution(true); ObjectChanged += (sender, e) => UpdateMetadata(); foreach (var param in Params.Input) { param.ObjectChanged += (sender, e) => UpdateMetadata(); } MetadataSender = new System.Timers.Timer(1000) { AutoReset = false, Enabled = false }; MetadataSender.Elapsed += MetadataSender_Elapsed; DataSender = new System.Timers.Timer(2000) { AutoReset = false, Enabled = false }; DataSender.Elapsed += DataSender_Elapsed; ObjectCache = new Dictionary <string, SpeckleObject>(); Grasshopper.Instances.DocumentServer.DocumentRemoved += DocumentServer_DocumentRemoved; }
private List<ICompletionListItem> HandlePropertyCompletion(LocalContext context) { return blockLevel; }
private TangoService() { _context = LocalContext.Current; }
public UsingDirectiveState(LocalContext context, CombinedSyntaxNode contextNode) : base(context, contextNode) { }
protected MixedNestableMemberStateBase( LocalContext context, CombinedSyntaxNode contextNode) : base(context, contextNode) { }
protected override bool ActionBody(BaseProcess action) { bool isProcessed = true; IAction updateAction = null; try { Guid enterpriseId = GetValue <Guid>(ARG_PAGE_ENTERPRISE_ID); bool removeIsAbsent = GetValue <bool>(ARG_REMOVE_IS_ABSENT); var stockEntriesOutbound = GetValue <IEnumerable <Guid> >(ARG_STOCK_ENTRY_IDS); LocalContext.SaveLog( $"{MoscowDateTimeOffset().ToString()} Начало обработки ответов от системы Меркурий."); // Получение последнего номера шага IList <MercuryQueueStepModel> responses = StepService.GetStepsByStatus(QueryId, null, 0, "0.0", null); IList <MercuryQueueStepModel> completed = responses.Where(r => r.StatusName == MQSStatus.COMPLETE.ToString() && r.ProcessMark != Consts.PROCESSED_MARK).ToList(); bool anyError = responses.Any(x => x.StatusName != MQSStatus.COMPLETE.ToString()); List <Guid> updIds = GetValue <List <Guid> >(ARG_UPDATED_STOCK_ENTRY_IDS); List <Guid> skippedIds = GetValue <List <Guid> >(ARG_SKIPEED_STOCK_ENTRY_IDS); // Обработка успешных ответов if (completed.Count > 0) { foreach (MercuryQueueStepModel step in completed) { if (NeedStopSteps()) { LocalContext.SaveLog( $" Выполннение прервано (StopQueueSteps). Выполнение будет продолжено после запуска очереди."); SetValue("Status", MQSStatus.STOPPED); return(true); } MercuryNS.Body body = ParseMercuryHelper.ParseBodyResponseFile(Path.Combine(MercurySettings.ResponseDirectory, step.FileResponse)); if (body.ReceiveApplicationResultResponse != null && body.ReceiveApplicationResultResponse.Application != null) { MercuryNS.GetStockEntryListResponse response = body.ReceiveApplicationResultResponse.Application.Result as MercuryNS.GetStockEntryListResponse; MercuryNS.StockEntryList stockEntriesFromMerc = response?.StockEntryList; if (stockEntriesFromMerc != null && stockEntriesFromMerc.Count > 0) { LocalContext.SaveLog( $" Обработка файла ответа от Меркурия. Имя файла {step.FileResponse}."); var queryForPullStockEntryGuids = new DocumentQuery(GetService <IMethaStorage>(), GetService <IQueryGenerator>(), GetService <ICacheManager>()); queryForPullStockEntryGuids .ResultField("SE", "@Id") .ResultField("SE", "GUID") .Using("StockEntry", "SE", ObjectStatus.osActive); queryForPullStockEntryGuids.Where(w => w.Or(o => { foreach (var seId in stockEntriesOutbound) { o.EQ("@Id", seId); } })); var seOutboundIds = LocalReader.QueryDocuments(queryForPullStockEntryGuids).Result.Select(d => d["GUID"]); var stockEntriesFromMip = LoadStockEntriesFromMIP(stockEntriesFromMerc); foreach (var se in stockEntriesFromMerc.Where(d => seOutboundIds.Contains(d.GUID))) { var seFromMIP = stockEntriesFromMip.FirstOrDefault(d => (string)d["GUID"] == (string)se.GUID); if ((double)se.Batch.Volume < (double)seFromMIP["Volume"]) { isProcessed = false; LocalContext.SaveLog( $" Выписка уже производилась"); } if ((string)se.UUID != (string)seFromMIP["UUID"]) { isProcessed = false; LocalContext.SaveLog( $" Выписка уже производилась"); } } } else { LocalContext.SaveLog( $" Файл ответа {step.FileResponse} от системы 'Меркурий' не содержит информацию о складских записях."); } } else { anyError = true; body.Fault.ToString(); // TODO сохранить ошибку в логе //body.Fault ResultDescription = "Система 'Меркурий' вернула исключение"; } } } else { isProcessed = false; ResultDescription = "Нет успешно обработанных ответов"; LocalContext.SaveLog(ResultDescription); } var notCompleted = responses.Where(r => r.StatusName != MQSStatus.COMPLETE.ToString()); foreach (var nc in notCompleted) { AppendUserErrorInfoFromXML(nc, Guid.Empty, null, null); } if (string.IsNullOrWhiteSpace(ResultDescription)) { ResultDescription = "Обработаны ответы от системы 'Меркурий'."; } } catch (ConcurrencyDocException except) { isProcessed = false; DefaultConcurrentExceptionLog(except); } catch (Exception e) { AppendUserErrorInfo(Guid.Empty, null, UserErrorConsts.ET_MIP, UserErrorConsts.StockList.RTE_PROCESS_RESPONSE, UserErrorConsts.DEFAULT_LAS_SUPPRT_ERROR); isProcessed = false; LocalContext.SaveLog(e.ToString()); ResultDescription = "Ошибка анализа результатов"; } LocalContext.SaveLog( $"{MoscowDateTimeOffset().ToString()} Окончание обработки ответов от системы 'Меркурий'."); return(isProcessed); }
static void Main() { LocalContext x = new LocalContext(); x.Fold("a"); }
private void CreateObjectsOnServer(List <SpeckleObject> bucketObjects, string baseUrl, ref int numErrors) { // Separate objects into sizeable payloads var payloads = CreatePayloads(bucketObjects); if (totalProgress != null) { totalProgress.Report(payloads.Count()); } if (bucketObjects.Count(o => o.Type == "Placeholder") == bucketObjects.Count) { numErrors = 0; return; } // Send objects which are in payload and add to local DB with updated IDs for (var j = 0; j < payloads.Count(); j++) { ResponseObject res = null; //Make a copy so that the task below doesn't use the j variable, which could change (by looping) by the time the task is run var payload = payloads[j].ToList(); try { res = apiClient.ObjectCreateAsync(payload, apiTimeoutOverride).Result; if (incrementProgress != null) { incrementProgress.Report(1); } } catch (Exception ex) { numErrors++; var speckleExceptionContext = ExtractSpeckleExceptionContext(ex); var errContext = speckleExceptionContext.Concat(new[] { "StreamId=" + StreamId, "Endpoint=ObjectCreateAsync", "PayloadBytes=" + Converter.getBytes(payload).Length, "Error in updating the server with a payload of " + payload.Count() + " objects" });; messenger.Message(MessageIntent.TechnicalLog, MessageLevel.Error, ex, errContext.ToArray()); } if (res != null && res.Resources.Count() > 0) { for (int i = 0; i < payload.Count(); i++) { payload[i]._id = res.Resources[i]._id; } } Task.Run(() => { //Don't save results to the hard disk as they take up a huge amount of space and are likely to change very often foreach (SpeckleObject obj in payload.Where(o => o.Hash != null && o._id != null && !o.Type.Contains("Result"))) { tryCatchWithEvents(() => LocalContext.AddSentObject(obj, baseUrl), "", "Error in updating local db"); } }); } int successfulPayloads = payloads.Count() - numErrors; messenger.Message(MessageIntent.Display, MessageLevel.Information, "Successfully sent " + successfulPayloads + "/" + payloads.Count() + " payloads to the server"); messenger.Message(MessageIntent.TechnicalLog, MessageLevel.Information, "Sent payloads to server", "NumSuccessful=" + successfulPayloads, "NumErrored=" + numErrors); }
public FileContextState(LocalContext context, CombinedSyntaxNode contextNode) : base(context, contextNode) { }
public OneInventoryObjectViewModel(MainWindowViewModel mainWindowViewModel, LocalContext localContext) { AllInstruments = true; MainWindowViewModel = mainWindowViewModel; LocalContext = localContext; }
/// <summary> /// Sends the update to the server. /// </summary> private void SendUpdate() { if (MetadataSender.Enabled) { // start the timer again, as we need to make sure we're updating DataSender.Start(); return; } if (IsSendingUpdate) { return; } IsSendingUpdate = true; Message = String.Format("Converting {0} \n objects", BucketObjects.Count); var convertedObjects = Converter.Serialise(BucketObjects).ToList(); Message = String.Format("Creating payloads"); LocalContext.PruneExistingObjects(convertedObjects, Client.BaseUrl); List <SpeckleObject> persistedObjects = new List <SpeckleObject>(); if (convertedObjects.Count(obj => obj.Type == "Placeholder") != convertedObjects.Count) { // create the update payloads int count = 0; var objectUpdatePayloads = new List <List <SpeckleObject> >(); long totalBucketSize = 0; long currentBucketSize = 0; var currentBucketObjects = new List <SpeckleObject>(); var allObjects = new List <SpeckleObject>(); foreach (SpeckleObject convertedObject in convertedObjects) { if (count++ % 100 == 0) { Message = "Converted " + count + " objects out of " + convertedObjects.Count() + "."; } // size checking & bulk object creation payloads creation long size = Converter.getBytes(convertedObject).Length; currentBucketSize += size; totalBucketSize += size; currentBucketObjects.Add(convertedObject); // Object is too big? if (size > 2e6) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "This stream contains a super big object. These will fail. Sorry for the bad error message - we're working on improving this."); currentBucketObjects.Remove(convertedObject); } if (currentBucketSize > 5e5) // restrict max to ~500kb; should it be user config? anyway these functions should go into core. at one point. { Debug.WriteLine("Reached payload limit. Making a new one, current #: " + objectUpdatePayloads.Count); objectUpdatePayloads.Add(currentBucketObjects); currentBucketObjects = new List <SpeckleObject>(); currentBucketSize = 0; } } // add in the last bucket if (currentBucketObjects.Count > 0) { objectUpdatePayloads.Add(currentBucketObjects); } Debug.WriteLine("Finished, payload object update count is: " + objectUpdatePayloads.Count + " total bucket size is (kb) " + totalBucketSize / 1000); // create bulk object creation tasks int k = 0; List <ResponseObject> responses = new List <ResponseObject>(); foreach (var payload in objectUpdatePayloads) { Message = String.Format("{0}/{1}", k++, objectUpdatePayloads.Count); try { var objResponse = Client.ObjectCreateAsync(payload).Result; responses.Add(objResponse); persistedObjects.AddRange(objResponse.Resources); int m = 0; foreach (var oL in payload) { oL._id = objResponse.Resources[m++]._id; } // push sent objects in the cache non-blocking Task.Run(() => { foreach (var oL in payload) { if (oL.Type != "Placeholder") { LocalContext.AddSentObject(oL, Client.BaseUrl); } } }); } catch (Exception err) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, err.Message); return; } } } else { persistedObjects = convertedObjects; } // create placeholders for stream update payload List <SpeckleObject> placeholders = new List <SpeckleObject>(); //foreach ( var myResponse in responses ) foreach (var obj in persistedObjects) { placeholders.Add(new SpecklePlaceholder() { _id = obj._id }); } SpeckleStream updateStream = new SpeckleStream() { Layers = BucketLayers, Name = BucketName, Objects = placeholders }; // set some base properties (will be overwritten) var baseProps = new Dictionary <string, object>(); baseProps["units"] = Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem.ToString(); baseProps["tolerance"] = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance; baseProps["angleTolerance"] = Rhino.RhinoDoc.ActiveDoc.ModelAngleToleranceRadians; updateStream.BaseProperties = baseProps; var response = Client.StreamUpdateAsync(Client.StreamId, updateStream).Result; Client.BroadcastMessage("stream", Client.StreamId, new { eventType = "update-global" }); Log += response.Message; AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data sent at " + DateTime.Now); Message = "Data sent\n@" + DateTime.Now.ToString("hh:mm:ss"); IsSendingUpdate = false; State = "Ok"; }
// NOTE: This is actually triggered when clicking "Push!" // TODO: Orchestration // Create buckets, send sequentially, notify ui re upload progress // NOTE: Problems with local context and cache: we seem to not sucesffuly pass through it // perhaps we're not storing the right sent object (localcontext.addsentobject) public override void PushSender(string args) { var client = JsonConvert.DeserializeObject <dynamic>(args); //if it's a category or property filter we need to refresh the list of objects //if it's a selection filter just use the objects that were stored previously ISelectionFilter filter = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(client.filter), GetFilterType(client.filter.Type.ToString())); IEnumerable <SpeckleObject> objects = new List <SpeckleObject>(); objects = GetSelectionFilterObjects(filter, client._id.ToString(), client.streamId.ToString()); var apiClient = new SpeckleApiClient((string)client.account.RestApi) { AuthToken = (string)client.account.Token }; var convertedObjects = new List <SpeckleObject>(); var placeholders = new List <SpeckleObject>(); var units = CurrentDoc.Document.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits.ToString().ToLower().Replace("dut_", ""); InjectScaleInKits(GetScale(units)); // this is used for feet to sane units conversion. int i = 0; long currentBucketSize = 0; var errorMsg = ""; var failedToConvert = 0; var errors = new List <SpeckleError>(); foreach (var obj in objects) { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, isLoadingIndeterminate = false, loadingProgress = 1f * i++ / objects.Count() * 100, loadingBlurb = string.Format("Converting and uploading objects: {0} / {1}", i, objects.Count()) })); var id = 0; Element revitElement = null; try { revitElement = CurrentDoc.Document.GetElement((string)obj.Properties["revitUniqueId"]); id = revitElement.Id.IntegerValue; } catch (Exception e) { errors.Add(new SpeckleError { Message = "Could not retrieve element", Details = e.Message }); continue; } try { var conversionResult = SpeckleCore.Converter.Serialise(new List <object>() { revitElement }); var byteCount = Converter.getBytes(conversionResult).Length; currentBucketSize += byteCount; if (byteCount > 2e6) { errors.Add(new SpeckleError { Message = "Element is too big to be sent", Details = $"Element {id} is bigger than 2MB, it will be skipped" }); continue; } convertedObjects.AddRange(conversionResult); if (currentBucketSize > 5e5 || i >= objects.Count()) // aim for roughly 500kb uncompressed { LocalContext.PruneExistingObjects(convertedObjects, apiClient.BaseUrl); try { var chunkResponse = apiClient.ObjectCreateAsync(convertedObjects).Result.Resources; int m = 0; foreach (var objConverted in convertedObjects) { objConverted._id = chunkResponse[m++]._id; placeholders.Add(new SpecklePlaceholder() { _id = objConverted._id }); if (objConverted.Type != "Placeholder") { LocalContext.AddSentObject(objConverted, apiClient.BaseUrl); } } } catch (Exception e) { errors.Add(new SpeckleError { Message = $"Failed to send {convertedObjects.Count} objects", Details = e.Message }); } currentBucketSize = 0; convertedObjects = new List <SpeckleObject>(); // reset the chunkness } } catch (Exception e) { failedToConvert++; errors.Add(new SpeckleError { Message = $"Failed to convert {revitElement.Name}", Details = $"Element id: {id}" }); //NotifyUi("update-client", JsonConvert.SerializeObject(new //{ // _id = (string)client._id, // errors = "Failed to convert " + failedConvert + " objects." //})); } } if (errors.Any()) { if (failedToConvert > 0) { errorMsg += string.Format("Failed to convert {0} objects ", failedToConvert, failedToConvert == 1 ? "" : "s"); } else { errorMsg += string.Format("There {0} {1} error{2} ", errors.Count() == 1 ? "is" : "are", errors.Count(), errors.Count() == 1 ? "" : "s"); } errorMsg += "<nobr>" + Globals.GetRandomSadFace() + "</nobr>"; } var myStream = new SpeckleStream() { Objects = placeholders }; var ug = UnitUtils.GetUnitGroup(UnitType.UT_Length); var baseProps = new Dictionary <string, object>(); baseProps["units"] = units; baseProps["unitsDictionary"] = GetAndClearUnitDictionary(); myStream.BaseProperties = baseProps; //myStream.BaseProperties = JsonConvert.SerializeObject(baseProps); NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = true, isLoadingIndeterminate = true, loadingBlurb = "Updating stream." })); var response = apiClient.StreamUpdateAsync((string)client.streamId, myStream).Result; var plural = objects.Count() == 1 ? "" : "s"; NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = (string)client._id, loading = false, loadingBlurb = "", message = $"Done sending {objects.Count()} object{plural}.", errorMsg, errors })); SpeckleTelemetry.RecordStreamUpdated("Revit"); }
private void ProcessSocket(ThreadArgument param) { LocalContext context = param.ClientContext; Thread.CurrentThread.Name = "worker_proc"; // Start up. if (param.StartCallback != null) { param.StartCallback(context); } try { int pollTimeout = 200000; // 1/5 of a second in microseconds while (!context.ShouldStopWorkerThread) { if (context == null || context.ClientSocket == null) { InternalConnectedEvent.WaitOne(); // Wait for reconnection. } try { // Check whether the previous read indicated a client disconnection. if (context.ClientSocket == null) { break; } bool canWrite = context.ClientSocket.Poll(pollTimeout, SelectMode.SelectWrite); // true if: // - A Connect method call has been processed, and the connection has succeeded. // - Data can be sent. if (canWrite) { // Dequeue data from write queue and send it. if (!context.OutBuffer.IsEmpty) { byte[] buffer = null; context.OutBuffer.TryDequeue(out buffer); //logger.Debug("BeginSend: {0}", Encoding.UTF8.GetString(buffer)); try { context.ClientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(EndSend), context); } catch (SocketException ex) { logger.Error("BeginSend failed: {0}", ex.Message); HandleSocketError(ex.SocketErrorCode, context); } } } } catch (ObjectDisposedException) { // Socket was already closed. InternalConnectedEvent.WaitOne(); // Wait for reconnection. TryBeginReceive(context); // Start receiving. } Thread.Sleep(1); } } catch (ThreadInterruptedException) { // Handle interruption. logger.Debug("Interrupted thread {0}", Thread.CurrentThread.Name); } finally { logger.Debug("Cleaning up thread {0}", Thread.CurrentThread.Name); // Clean up. if (param.FinishCallback != null) { param.FinishCallback(context); } } }
public ComponentController(LocalContext context) { _context = context; }
public JogoHub(IJogo local, LocalContext banco, IHelper help) { _local = local; _banco = banco; _help = help; }
public LocalDeclarationState(LocalContext context, CombinedSyntaxNode contextNode) : base(context, contextNode) { }
public ArrangeCourseRepository(LocalContext localContext) : base(localContext) { this._localContext = localContext; }
private LocalContext GetContext(ScintillaControl sci, int position) { var ctx = new LocalContext(sci); int i = position - 1; int style = sci.StyleAt(i-1); if (style == (int)CSS.COMMENT) // inside comments { ctx.InComments = true; return ctx; } int inString = 0; if (style == 14) inString = 1; if (style == 13) inString = 2; bool inWord = true; bool inComment = false; bool inPar = false; string word = ""; int lastCharPos = i; while (i > 1) { char c = (char)sci.CharAt(i--); if (wordChars.IndexOf(c) >= 0) { lastCharPos = i + 1; if (inWord) word = c + word; } else inWord = false; if (inString > 0) { if (inString == 1 && c == '\'') inString = 0; else if (inString == 2 && c == '"') inString = 0; continue; } if (inComment) { if (c == '*' && i > 0 && (char)sci.CharAt(i) == '/') inComment = false; continue; } if (c == '/' && i > 0 && (char)sci.CharAt(i) == '*') // entering comment inComment = true; if (c == '\'') inString = 1; // entering line else if (c == '"') inString = 2; else if (c == ')') inPar = true; else if (inPar) { if (c == '(') inPar = false; continue; } else if (c == ':') { ctx.Separator = c; ctx.Position = lastCharPos; string attr = ReadAttribute(sci, i); if (attr.Length > 1) { if (attr[0] == features.Trigger || IsVarDecl(sci, i)) ctx.IsVar = true; else if (!IsTag(attr)) { ctx.InValue = true; ctx.Property = attr; } } break; } else if (c == ';' || c == '{') { ctx.Separator = c; ctx.Position = lastCharPos; ctx.InBlock = !IsVarDecl(sci, i); break; } else if (c == '}' || c == ',' || c == '.' || c == '#') { ctx.Separator = c; ctx.Position = lastCharPos; break; } else if (c == '(') { string tok = ReadWordLeft(sci, i); if (tok == "url") { ctx.Separator = '('; ctx.InUrl = true; ctx.Position = i + 1; word = ""; for (int j = i + 2; j < position; j++) word += (char)sci.CharAt(j); break; } } } if (word.Length > 0) { if (word[0] == '-') { Match m = reNavPrefix.Match(word); if (m.Success) word = m.Groups[1].Value; } } ctx.Word = word; return ctx; }
public ListOfObjectsViewModel(LocalContext localContext) => LocalContext = localContext;
private List<ICompletionListItem> HandlePseudoCompletion(LocalContext context) { return pseudos; }
protected override bool ActionBody(BaseProcess action) { bool isProcessed = true; try { messageGenerator = GetService <IMercuryMessageBodyGenerator>(); int pageSize = GetValue <int>(ARG_PAGE_SIZE); int pageCount = GetValue <int>(ARG_PAGE_COUNT); int pageStart = GetValue <int>(ARG_PAGE_START); Guid enterpriseId = GetValue <Guid>(ARG_PAGE_ENTERPRISE_ID); operationName = GetValue <string>(ARG_OPERATION_NAME); mercuryLogin = GetValue <string>(ARG_MERCURY_LOGIN); string suffix = GetValue <string>(ARG_SUFFIX); int? iteration = GetValue <int?>(ARG_ITERATION); DateTimeOffset?beginDate = GetValue <DateTimeOffset?>(ARG_BEGIN_DATE); DateTimeOffset?endDate = GetValue <DateTimeOffset?>(ARG_END_DATE); LocalContext.SaveLog($"{MoscowDateTimeOffset().ToString()} Начало формирования запросов в систему Меркурий."); #region Проверка параметров if (pageCount <= 0) { isProcessed = false; LocalContext.SaveLog($" Количество страниц должно быть > 0."); AppendUserErrorInfo(Guid.Empty, null, UserErrorConsts.ET_VALIDATION, UserErrorConsts.StockList.RTE_MAKE_REQUEST, "Количество страниц должно быть > 0"); } if (pageSize <= 0) { isProcessed = false; LocalContext.SaveLog($" Размер страниц должно быть > 0."); AppendUserErrorInfo(Guid.Empty, null, UserErrorConsts.ET_VALIDATION, UserErrorConsts.StockList.RTE_MAKE_REQUEST, "Размер страниц должно быть > 0"); } if (pageStart <= 0) { isProcessed = false; LocalContext.SaveLog($" Начальная страница должна быть > 0."); AppendUserErrorInfo(Guid.Empty, null, UserErrorConsts.ET_VALIDATION, UserErrorConsts.StockList.RTE_MAKE_REQUEST, "Начальная страница должна быть > 0"); } Document enterpriseDoc = LocalReader.LoadDocumentByType(enterpriseId, "Enterprise"); string enterpriseGUID = (string)enterpriseDoc["GUID"]; string enterpriseCode = (string)enterpriseDoc["Code"]; if (enterpriseDoc == null) { isProcessed = false; AppendUserErrorInfo(Guid.Empty, null, UserErrorConsts.ET_VALIDATION, UserErrorConsts.StockList.VALID_NO_ENTERPRISE, $"Не найдена площадка с ИД {enterpriseId.ToString()}/{enterpriseId.ToStringNumber()}"); LocalContext.SaveLog($" Не найдена площадка с ИД {enterpriseId.ToString()}/{enterpriseId.ToStringNumber()}."); } #endregion if (isProcessed) { List <StepContext> steps = new List <StepContext>(); LocalContext.SaveLog($" Площадка для формирования запросов {enterpriseCode}."); LocalContext.SaveLog($" Стартовая страница {pageStart}, количество страниц для получения {pageCount}, размер страницы {pageSize}."); for (int i = 0; i < pageCount; i++) { LocalContext.SaveLog($" Формирование страницы {(i + pageStart - 1) * pageSize} - {(i + pageStart) * pageSize}."); StepContext requestContext = CreateStep(QueryId, MQSOperationType.COMMUNICATE); requestContext.MercuryQueueStep.Status = MQSStatus.NEW; if (iteration.HasValue) { requestContext.MercuryQueueStep.StepId = "0.0_" + iteration.Value.ToString("D3"); } else { requestContext.MercuryQueueStep.StepId = "0.0"; } requestContext.MercuryQueueStep.StepNo = LocalContext.MercuryQueueStep.StepNo + 1; requestContext.MercuryQueueStep.StepName = Consts.STEP_NAME_MERCURY_COMMUNICATE; requestContext.MercuryQueueStep.Description = "Сформирован запрос"; requestContext.MercuryQueueStep.OperationGroup = Consts.OP_GROUP_CHECK_FOR_COMPLETED_OUTBOUND + suffix; requestContext.GenerateFileNames(operationName); var req = GenerateRequest(i + pageStart, pageSize, LocalContext.MercurySettings, mercuryLogin, enterpriseGUID, enterpriseCode, beginDate, endDate); requestContext.SaveRequest(req); var args = new Dictionary <string, ActionArgument>(); args.Add("PageNo", new ActionArgument(typeof(int), "PageNo", i)); requestContext.MercuryQueueStep.Parameters = ArgumentSerializer.SerializeArguments(args); steps.Add(requestContext); LocalContext.SaveLog($" Страница {i + pageStart - 1} сформирована."); } // Сохранение информации о сгенерированных запросах using (IDatabaseConnector connector = GetService <IDatabaseConnector>()) { IMercuryQueueStepService transactionPersist = this.GetService <IMercuryQueueStepService>(connector); transactionPersist.RegisterSteps(steps); transactionPersist.SaveFinish(LocalContext.MercuryQueueStep.Id, MQSStatus.COMPLETE, "Выполнено формирование запросов.", DateTimeOffset.UtcNow); connector.Commit(); breakAutosave = true; SetValue("Status", MQSStatus.COMPLETE); } } else { LocalContext.SaveLog($" Заданы не все параметры для формирования запроса(-ов)."); LocalContext.SaveLog($" Операция отменена."); ResultDescription = "Ошибка. Не верные параметры."; } } catch (Exception e) { isProcessed = false; AppendUserErrorInfo(Guid.Empty, null, UserErrorConsts.ET_MIP, UserErrorConsts.StockList.RTE_MAKE_REQUEST, UserErrorConsts.DEFAULT_LAS_SUPPRT_ERROR); ResultDescription = "Ошибка процесса формирования запросов в систему 'Меркурий'."; LocalContext.SaveLog(e.ToString()); } LocalContext.SaveLog($"{MoscowDateTimeOffset().ToString()} Окончание формирования запросов в систему 'Меркурий'."); return(isProcessed); }
private List<ICompletionListItem> HandleVariableCompletion(LocalContext context) { string src = context.Sci.Text; if (context.Sci.CurrentPos < src.Length) src = src.Substring(0, context.Sci.CurrentPos); MatchCollection matches = features.Pattern.Matches(src); if (matches.Count == 0) return null; var tokens = new Dictionary<string, Match>(); foreach (Match m in matches) tokens[m.Groups[1].Value] = m; var items = new List<ICompletionListItem>(); foreach (string token in tokens.Keys) { string desc = GetVariableValue(src, tokens[token]); items.Add(new CompletionItem(token, ItemKind.Variable, desc)); } items.Sort(); return items; }
public InactiveState(LocalContext context) : base(context, null) { }
private List<ICompletionListItem> HandleSelectorCompletion(LocalContext context) { return htmlTags; }
public TeacherRepository(LocalContext localContext) : base(localContext) { this._localContex = localContext; }