Exemplo n.º 1
0
 public void Process(ISemanticProcessor semProc, IMembrane membrane, ISemanticType t)
 {
     if ( (!(t is ST_Log)) && (!(t is ST_Exception)) )
     {
         Console.WriteLine("Publishing type: " + t.GetType().Name);
     }
 }
Exemplo n.º 2
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Log log)
 {
     this.BeginInvoke(() =>
         {
             tbLog.AppendText(log.Message+"\r\n");
         });
 }
Exemplo n.º 3
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, FontResponse resp)
 {
     resp.Context.Response.ContentType = resp.ContentType;
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     resp.Context.Response.ContentLength64 = resp.BinaryData.Length;
     resp.Context.Response.OutputStream.Write(resp.BinaryData, 0, resp.BinaryData.Length);
     resp.Context.Response.Close();
 }
 protected void Process(ISemanticProcessor proc, IMembrane membrane, ST_NoData nothing)
 {
     dgView.FindForm().BeginInvoke(() =>
     {
         dgView.DataSource = null;
         label.Text = "Collection: ";
     });
 }
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_AddNewSubtype data)
 {
     TreeNode sttn = selectedNode;
     Schema parentSchema = (Schema)sttn.Parent.Tag;
     Schema schema = new Schema() { Name = data.Name, Alias = data.Alias, Parent = parentSchema };
     parentSchema.Subtypes.Add(schema);
     AddSchemaNode(sttn, schema);
 }
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Associations assoc)
 {
     this.BeginInvoke(() =>
         {
             RemoveAssociationButtons();
             int n = CreateForwardAssociationButtons(assoc.ForwardSchemaNames);
             CreateReverseAssociationButtons(assoc.ReverseSchemaNames, n);
         });
 }
Exemplo n.º 7
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, JsonResponse resp)
 {
     resp.Context.Response.StatusCode = resp.StatusCode;
     resp.Context.Response.ContentType = "text/json";
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     resp.Context.Response.ContentLength64 = resp.Json.Length;
     resp.Context.Response.OutputStream.Write(resp.Json.to_Utf8(), 0, resp.Json.Length);
     resp.Context.Response.Close();
 }
Exemplo n.º 8
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_JavascriptResponse resp)
 {
     byte[] utf8data = resp.Javascript.to_Utf8();
     resp.Context.Response.ContentType = "text/javascript";
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     resp.Context.Response.ContentLength64 = utf8data.Length;
     resp.Context.Response.OutputStream.Write(utf8data, 0, utf8data.Length);
     resp.Context.Response.Close();
 }
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Data data)
 {
     DataView dv = new DataView(data.Table);
     view.FindForm().BeginInvoke(() =>
         {
             view.DataSource = dv;
             label.Text = "Collection: " + data.Table.TableName;
         });
 }
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_AddConcreteType data)
 {
     TreeNode cttn = selectedNode;
     Schema schema = (Schema)cttn.Parent.Tag;
     // TODO: Get actual type at some point.
     ConcreteType ct = new ConcreteType() { Name = data.Name, Alias = data.Alias, Type = typeof(string) };
     schema.ConcreteTypes.Add(ct);
     AddConcreteTypeToNode(cttn, ct);
 }
Exemplo n.º 11
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, HtmlPageRoute context)
        {
            bool handled = proc.ServiceManager.Get<IWebFileResponse>().ProcessFileRequest(context.Context);

            if (!handled)
            {
                RouteNotFoundResponse(proc, context.Context);
            }
        }
Exemplo n.º 12
0
 protected void Log <T>(IMembrane membrane, T obj)
     where T : ISemanticType
 {
     // Prevent recursion, don't log exceptions, as these get handled by the exception type.
     if ((!(membrane is LoggerMembrane)) && (!(obj is ST_Exception)))
     {
         ProcessInstance(Logger, obj);
     }
 }
Exemplo n.º 13
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, StringResponse resp)
 {
     resp.Context.Response.StatusCode = resp.StatusCode;
     resp.Context.Response.ContentType = "text/text";
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     byte[] byteData = resp.Message.to_Utf8();
     resp.Context.Response.ContentLength64 = byteData.Length;
     resp.Context.Response.OutputStream.Write(byteData, 0, byteData.Length);
     resp.Context.Response.Close();
 }
Exemplo n.º 14
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, UpdateField msg)
        {
            ContextValueDictionary cvd = CreateOrGetContextValueDictionary(proc, msg.Context);
            var instancePath           = msg.ID.Split(".").Select(Guid.Parse).ToList();
            var typePath = msg.TypePath.Split("|").ToList();
            var cv       = new ContextValue(msg.Value, instancePath, typePath.Select(t => Type.GetType(t)).ToList(), msg.RecordNumber);

            cvd.AddOrUpdate(cv);
            JsonResponse(proc, msg, new OKResponse());
        }
Exemplo n.º 15
0
 /// <summary>
 /// The HtmlResponse process is the only process that invokes the workflow post router for final
 /// processing of the HTML.
 /// </summary>
 public void Process(ISemanticProcessor proc, IMembrane membrane, HtmlResponse resp)
 {
     proc.ServiceManager.IfExists <IWebWorkflowService>(wws => wws.PostRouter(resp.Context, resp));
     byte[] utf8data = resp.Html.to_Utf8();
     resp.Context.Response.ContentType     = "text/html";
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     resp.Context.Response.ContentLength64 = utf8data.Length;
     resp.Context.Response.OutputStream.Write(utf8data, 0, utf8data.Length);
     resp.Context.Response.Close();
 }
Exemplo n.º 16
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, CmdClearCanvas cmd)
        {
            var controller = proc.ServiceManager.Get <IFlowSharpCanvasService>().ActiveController;

            controller.Canvas.FindForm().BeginInvoke(() =>
            {
                controller.Clear();
                controller.Canvas.Invalidate();
            });
        }
Exemplo n.º 17
0
        // Ex: localhost:8001:flowsharp?cmd=CmdShowShape&Name=btnTest
        public void Process(ISemanticProcessor proc, IMembrane membrane, CmdShowShape cmd)
        {
            BaseController controller = proc.ServiceManager.Get <IFlowSharpCanvasService>().ActiveController;
            var            el         = controller.Elements.Where(e => e.Name == cmd.Name).FirstOrDefault();

            el?.Canvas.Invoke(() =>
            {
                controller.FocusOn(el);
            });
        }
Exemplo n.º 18
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_JsonResponse resp)
 {
     resp.Context.Response.StatusCode      = resp.StatusCode;
     resp.Context.Response.ContentType     = "text/json";
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     byte[] byteData = resp.Json.to_Utf8();
     resp.Context.Response.ContentLength64 = byteData.Length;
     resp.Context.Response.OutputStream.Write(byteData, 0, byteData.Length);
     resp.Context.Response.Close();
 }
Exemplo n.º 19
0
        // FlowSharpCodeOutputWindowService required for this behavior.
        // Ex: localhost:8001/flowsharp?cmd=CmdOutputMessage&Text=foobar
        public void Process(ISemanticProcessor proc, IMembrane membrane, CmdOutputMessage cmd)
        {
            BaseController controller = proc.ServiceManager.Get <IFlowSharpCanvasService>().ActiveController;
            var            w          = proc.ServiceManager.Get <IFlowSharpCodeOutputWindowService>();

            controller.Canvas.FindForm().BeginInvoke(() =>
            {
                cmd.Text.Split('\n').Where(s => !String.IsNullOrEmpty(s.Trim())).ForEach(s => w.WriteLine(s.Trim()));
            });
        }
Exemplo n.º 20
0
        /// <summary>
        /// Any public properties that are of ISemanticType type and not null are also emitted into the membrane.
        /// </summary>
        protected void ProcessInnerTypes(IMembrane membrane, IMembrane caller, ISemanticType obj, bool processOnCallerThread)
        {
            var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(pi => pi.PropertyType.GetInterfaces().Contains(typeof(ISemanticType)));

            properties.ForEach(pi =>
            {
                ISemanticType prop = (ISemanticType)pi.GetValue(obj);
                prop.IfNotNull((p) => ProcessInstance(membrane, caller, p, processOnCallerThread));
            });
        }
Exemplo n.º 21
0
        /// <summary>
        /// Returns HTML rendering the current state of the dictionary tree.
        /// </summary>
        public void Process(ISemanticProcessor proc, IMembrane membrane, GetDictionaryTreeHtml msg)
        {
            ContextValueDictionary cvd  = CreateOrGetContextValueDictionary(proc, msg.Context);
            StringBuilder          sb   = new StringBuilder();
            List <Guid>            path = new List <Guid>();

            NavigateChildren(sb, cvd.Root.Children, 0, path, msg.ShowInstanceIDs);

            JsonResponse(proc, msg, new { Status = "OK", html = sb.ToBase64String() });
        }
Exemplo n.º 22
0
        public void Unregister(IMembrane membrane, IReceptor receptor)
        {
            if (receptor is IDisposable)
            {
                ((IDisposable)receptor).Dispose();
            }

            statefulReceptors.Remove(receptor);
            membraneReceptorInstances[membrane].Remove(receptor);
        }
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_AddExistingSubtype data)
 {
     TreeNode sttn = selectedNode;
     Schema parentSchema = (Schema)sttn.Parent.Tag;
     Schema schema = data.Schema.DeepClone();
     schema.Parent = parentSchema;
     parentSchema.Subtypes.Add(schema);
     TreeNode tn = AddSchemaNode(sttn, schema);
     AddConcreteTypes(tn.Nodes[0], schema);
     schema.Subtypes.ForEach(st => AddSubTypesToNode(tn.Nodes[1], st));
 }
Exemplo n.º 24
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ExceptionResponse resp)
 {
     // proc.ServiceManager.Get<ILoggerService>().Log(LogMessage.Create(resp.Exception.Message));
     proc.ServiceManager.Get<ISemanticProcessor>().ProcessInstance<LoggerMembrane, ST_Exception>(ex => ex.Exception = resp.Exception);
     resp.Context.Response.StatusCode = 500;
     resp.Context.Response.ContentType = "text/text";
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     resp.Context.Response.ContentLength64 = resp.Exception.Message.Length;
     resp.Context.Response.OutputStream.Write(resp.Exception.Message.to_Utf8(), 0, resp.Exception.Message.Length);
     resp.Context.Response.Close();
 }
Exemplo n.º 25
0
        public void RegisterMembrane(IMembrane membrane)
        {
            Type m = membrane.GetType();

            if (!membranes.ContainsKey(m))
            {
                membranes[m] = membrane;
                membraneReceptorTypes[membrane]     = new List <Type>();
                membraneReceptorInstances[membrane] = new List <IReceptor>();
            }
        }
Exemplo n.º 26
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ExceptionResponse resp)
 {
     // proc.ServiceManager.Get<ILoggerService>().Log(LogMessage.Create(resp.Exception.Message));
     proc.ServiceManager.Get <ISemanticProcessor>().ProcessInstance <LoggerMembrane, ST_Exception>(ex => ex.Exception = resp.Exception);
     resp.Context.Response.StatusCode      = 500;
     resp.Context.Response.ContentType     = "text/text";
     resp.Context.Response.ContentEncoding = Encoding.UTF8;
     resp.Context.Response.ContentLength64 = resp.Exception.Message.Length;
     resp.Context.Response.OutputStream.Write(resp.Exception.Message.to_Utf8(), 0, resp.Exception.Message.Length);
     resp.Context.Response.Close();
 }
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Data data)
 {
     schema = data.Schema;
     DataView dv = new DataView(data.Table);
     dgView.FindForm().BeginInvoke(() =>
         {
             dgView.DataSource = dv;
             dgView.Columns[0].Visible = false;			// Hide the ID field.
             label.Text = "Semantic Type: " + data.Table.TableName;
         });
 }
Exemplo n.º 28
0
        public InAppRunner()
        {
            sp = new SemanticProcessor();

            // membrane = new HopeMembrane();
            // membrane = sp.RegisterMembrane<HopeMembrane>();
            // membrane = new App.HopeMembrane();
            membrane = sp.RegisterMembrane <App.HopeMembrane>();

            sp.Processing += ProcessingSemanticType;
        }
Exemplo n.º 29
0
        // Ex: localhost:8001/flowsharp?cmd=CmdGetShapeFiles
        public void Process(ISemanticProcessor proc, IMembrane membrane, CmdGetShapeFiles cmd)
        {
            BaseController controller = proc.ServiceManager.Get <IFlowSharpCanvasService>().ActiveController;

            // Invoke, because we have to get the filenames before we respond.
            controller.Canvas.FindForm().Invoke(() =>
            {
                var els = controller.Elements.Where(e => e is IFileBox);
                cmd.Filenames.AddRange(els.Cast <IFileBox>().Where(el => !String.IsNullOrEmpty(el.Filename)).Select(el => el.Filename));
            });
        }
Exemplo n.º 30
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, CssResponse resp)
 {
     // resp.Context.Response.ContentLength64 = resp.Script.Length;
     if (resp.Context.Request.AcceptEncoding)
     {
         resp.Context.Response.WriteCompressed(resp.Script, "text/css");
     }
     else
     {
         resp.Context.Response.Write(resp.Script, "text/css");
     }
 }
Exemplo n.º 31
0
 public void MoveMembraneToMembrane(IMembrane sourceMembrane, IMembrane targetMembrane)
 {
     // Remove the source membrane from its parent container.
     sourceMembrane.ParentMembrane.Membranes.Remove(sourceMembrane);
     // Change the parent to the target membrane.
     sourceMembrane.ParentMembrane = targetMembrane;
     // Add the source membrane to the target's membrane list.
     targetMembrane.Membranes.Add(sourceMembrane);
     sourceMembrane.ParentMembrane.UpdatePermeability();
     sourceMembrane.UpdatePermeability();
     ((Membrane)targetMembrane).UpdatePermeability();
 }
Exemplo n.º 32
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, ISemanticType type)
        {
            // Don't log our log message, otherwise we get an infinite loop!
            if (!(type is ST_Log))
            {
                // One way, with instances:
                // proc.ProcessInstance(proc.Logger, new ST_Log() { Message = type.GetType().ToString() });

                // Another way, strictly with types:
                proc.ProcessInstance <LoggerMembrane, ST_Log>(log => log.Message = type.GetType().ToString());
            }
        }
Exemplo n.º 33
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, ISemanticType type)
        {
            // Don't log our log message, otherwise we get an infinite loop!
            if (!(type is ST_Log))
            {
                // One way, with instances:
                // proc.ProcessInstance(proc.Logger, new ST_Log() { Message = type.GetType().ToString() });

                // Another way, strictly with types:
                proc.ProcessInstance<LoggerMembrane, ST_Log>(log => log.Message = type.GetType().ToString());
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// The HtmlResponse process is the only process that invokes the workflow post router for final
        /// processing of the HTML.
        /// </summary>
        public void Process(ISemanticProcessor proc, IMembrane membrane, HtmlResponse resp)
        {
            proc.ServiceManager.IfExists <IWebWorkflowService>(wws => wws.PostRouter(resp.Context, resp));
            // resp.Context.Response.ContentLength64 = resp.Html.Length;

            if (resp.Context.Request.AcceptEncoding)
            {
                resp.Context.Response.WriteCompressed(resp.Html, "text/html");
            }
            else
            {
                resp.Context.Response.Write(resp.Html, "text/html");
            }
        }
        public void Process(ISemanticProcessor proc, IMembrane membrane, ST_AddSchema data)
        {
            Schema schema = new Schema() { Name = data.Name, Alias = data.Alias };
            model.Schemata.Add(schema);
            TreeNode tn = new TreeNode(Helpers.GetSchemaNodeText(schema));
            tn.Tag = schema;
            tn.Nodes.Add("Concrete Types");
            tn.Nodes.Add("Subtypes");

            tv.FindForm().BeginInvoke(() =>
                {
                    tv.Nodes[0].Nodes.Add(tn);
                });
        }
Exemplo n.º 36
0
        public static void CreateCarriers(IMembrane dropInto, XElement el)
        {
            Dictionary <string, ICarrier> carriers = new Dictionary <string, ICarrier>();

            el.Descendants().ForEach(xelem =>
            {
                string protocolName          = xelem.Attribute("Protocol").Value;
                ISemanticTypeStruct protocol = Program.Skin.SemanticTypeSystem.GetSemanticTypeStruct(protocolName);
                dynamic signal = Program.Skin.SemanticTypeSystem.Create(protocolName);

                // Use reflection to assign all property values since they're defined in the XML.
                xelem.Attributes().Where(a => a.Name != "Protocol").ForEach(attr =>
                {
                    Type t          = signal.GetType();
                    PropertyInfo pi = t.GetProperty(attr.Name.ToString());

                    if (attr.Value.BeginsWith("{"))                                     // a reference (only references to carriers are supported at the moment)
                    {
                        ICarrier refCarrier = carriers[attr.Value.Between('{', '}')];
                        pi.SetValue(signal, refCarrier);
                    }
                    else
                    {
                        object val = attr.Value;

                        TypeConverter tcFrom = TypeDescriptor.GetConverter(pi.PropertyType);
                        //TypeConverter tcTo = TypeDescriptor.GetConverter(typeof(string));

                        //if (tcTo.CanConvertTo(t))
                        //{
                        //	tcTo.ConvertTo(val, pi.PropertyType);
                        //}

                        if (tcFrom.CanConvertFrom(typeof(string)))
                        {
                            val = tcFrom.ConvertFromInvariantString(attr.Value);
                            pi.SetValue(signal, val);
                        }
                        else
                        {
                            throw new ApplicationException("Cannot convert string to type " + t.Name);
                        }
                    }
                });

                ICarrier carrier = dropInto.CreateCarrier(Program.Skin["DropReceptor"].Instance, protocol, signal);
                carriers[protocol.DeclTypeName] = carrier;
            });
        }
Exemplo n.º 37
0
        // Ex: http://localhost/renderContext?ContextName=MeaningExplorer.PersonContext
        // Ex: http://localhost/renderContext?ContextName=MeaningExplorer.PersonContext&isSearch=true
        public void Process(ISemanticProcessor proc, IMembrane membrane, RenderContext msg)
        {
            try
            {
                Type t = Type.GetType(msg.ContextName);
                Clifton.Meaning.IContext context = (Clifton.Meaning.IContext)Activator.CreateInstance(t);
                string html;

                try
                {
                    Parser parser = new Parser();
                    parser.Log = logMsg => Console.WriteLine(logMsg);
                    parser.Parse(context);

                    if (parser.AreDeclarationsValid)
                    {
                        ShowGroups(parser.Groups);
                        // The CVD is needed for rendering lookup values.
                        ContextValueDictionary cvd = CreateOrGetContextValueDictionary(proc, msg.Context);
                        html = Renderer.CreatePage(parser, msg.IsSearch ? Renderer.Mode.Search : Renderer.Mode.NewRecord, cvd);
                    }
                    else
                    {
                        html = "<p>Context declarations are not valid.  Missing entities:</p>" +
                               String.Join("<br>", parser.MissingDeclarations.Select(pt => pt.Name));
                    }
                }
                catch (Exception ex)
                {
                    html = "<p>Context declarations are not valid.</p><p>" + ex.Message + "</p>";
                    html = html + "<p>" + ex.StackTrace.Replace("\r\n", "<br>");
                }

                proc.ProcessInstance <WebServerMembrane, HtmlResponse>(r =>
                {
                    r.Context = msg.Context;
                    r.Html    = html;
                });
            }
            catch (Exception ex)
            {
                proc.ProcessInstance <WebServerMembrane, HtmlResponse>(r =>
                {
                    r.Context = msg.Context;
                    r.Html    = ex.Message + "<br>" + ex.StackTrace.Replace("\r\n", "<br>");
                });
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Any public properties that are of ISemanticType type and not null are also emitted into the membrane.
        /// </summary>
        protected void ProcessInnerTypes(IMembrane membrane, IMembrane caller, ISemanticType obj, bool processOnCallerThread, IMembrane fromMembrane, IReceptor fromReceptor)
        {
            // TODO: Setup like we do for main ProcessInstance above so exceptions are caught and we get a ProcStates return.
            // ProcStates ps = ProcStates.NotProcessed;
            var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(pi => pi.PropertyType.GetInterfaces().Contains(typeof(ISemanticType)));

            properties.ForEach(pi =>
            {
                ISemanticType prop = (ISemanticType)pi.GetValue(obj);

                if (prop != null)
                {
                    // TODO: Setup like we do for main ProcessInstance above so exceptions are caught and we get a ProcStates return.
                    ProcessInstanceWithInvoke(membrane, caller, prop, processOnCallerThread);
                }
            });
        }
Exemplo n.º 39
0
        public void Register <M, T>(Action <IReceptor> receptorInitializer)
            where M : IMembrane, new()
            where T : IReceptor
        {
            Register <T>();
            Type      receptorType = typeof(T);
            IMembrane membrane     = RegisterMembrane <M>();

            membraneReceptorTypes[membrane].Add(receptorType);
            receptorInitializers[new MembraneReceptor()
                                 {
                                     Membrane = membrane, ReceptorType = receptorType
                                 }] = new ReceptorInitializer()
            {
                Initializer = receptorInitializer
            };
        }
Exemplo n.º 40
0
        // Ex: localhost:8001:flowsharp?cmd=CmdUpdateProperty&Name=btnTest&PropertyName=Text&Value=Foobar
        public void Process(ISemanticProcessor proc, IMembrane membrane, CmdUpdateProperty cmd)
        {
            BaseController controller = proc.ServiceManager.Get <IFlowSharpCanvasService>().ActiveController;
            var            els        = controller.Elements.Where(e => e.Name == cmd.Name);

            els.ForEach(el =>
            {
                PropertyInfo pi = el.GetType().GetProperty(cmd.PropertyName);
                object cval     = Converter.Convert(cmd.Value, pi.PropertyType);

                el?.Canvas.Invoke(() =>
                {
                    pi.SetValue(el, cval);
                    controller.Redraw(el);
                });
            });
        }
        public void Process(ISemanticProcessor proc, IMembrane membrane, RegistrationToken token)
        {
            IDbContextService  db  = proc.ServiceManager.Get <IDbContextService>();
            List <UserAccount> uas = db.Context.Query <UserAccount>(r => r.RegistrationToken == token.Token);
            bool validated         = uas.Count == 1;

            proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(token.Context, "TokenValidated", validated);

            if (validated)
            {
                uas[0].RegistrationToken = null;
                uas[0].Registered        = true;
                db.Context.Update(uas[0]);
            }

            // Continue processing the get request to display the /account/finishRegistration page.
            proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = token.Context);
        }
        public void Process(ISemanticProcessor proc, IMembrane membrane, ISemanticType obj)
        {
            string url  = String.Format("http://localhost:{0}/semanticType", outboundPort);
            string json = JsonConvert.SerializeObject(obj);

            // Insert our type name:
            json = "{\"_type_\":\"" + obj.GetType().FullName + "\"," + json.Substring(1);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method        = "POST";
            request.ContentType   = "application/json";
            request.ContentLength = json.Length;
            Stream st = request.GetRequestStream();

            byte[] bytes = Encoding.UTF8.GetBytes(json);
            st.Write(bytes, 0, bytes.Length);
            st.Close();
        }
Exemplo n.º 43
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, ViewContext msg)
        {
            var instancePath           = msg.InstancePath.Split(".").Select(s => Guid.Parse(s)).ToList();
            ContextValueDictionary cvd = CreateOrGetContextValueDictionary(proc, msg.Context);
            // var (parser, context) = cvd.CreateContext(instancePath);

            // TODO: WHY ARE WE EVEN DOING THIS?  IT SEEMS ALL WE NEED TO DO IS CREATE THE PARSER!
            // var (parser, fullInstancePath) = cvd.CreateContext(instancePath.First());

            Guid   rootId   = instancePath.First();
            Type   rootType = cvd.GetRootType(rootId);
            Parser parser   = new Parser();
            var    context  = (Context)Activator.CreateInstance(rootType);

            parser.Parse(context);

            string html = Renderer.CreatePage(parser, Renderer.Mode.View, cvd, rootId);

            JsonResponse(proc, msg, new { Status = "OK", html = html.ToString().ToBase64String() });
        }
        public void Process(ISemanticProcessor proc, IMembrane membrane, ForgotPasswordToken token)
        {
            IDbContextService  db  = proc.ServiceManager.Get <IDbContextService>();
            List <UserAccount> uas = db.Context.Query <UserAccount>(r => r.PasswordRecoveryToken == token.Token);
            bool validated         = uas.Count == 1;

            if (validated)
            {
                proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(token.Context, "UserPasswordRecoveryId", uas[0].Id);
                uas[0].PasswordRecoveryToken = null;
                db.Context.Update(uas[0]);
            }
            else
            {
                proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(token.Context, "UserPasswordRecoveryId", null);
            }

            // Continue processing the get request to display the /account/passwordRecovery page.
            proc.ProcessInstance <WebServerMembrane, UnhandledContext>(c => c.Context = token.Context);
        }
        public void Process(ISemanticProcessor proc, IMembrane membrane, NewPassword token)
        {
            int?id = proc.ServiceManager.Get <IWebSessionService>().GetSessionObject <int?>(token.Context, "UserPasswordRecoveryId");

            if (id != null)
            {
                IDbContextService  db  = proc.ServiceManager.Get <IDbContextService>();
                List <UserAccount> uas = db.Context.Query <UserAccount>(r => r.Id == (int)id);

                if (uas.Count == 1)
                {
                    uas[0].PasswordHash          = PasswordHash.CreateHash(token.Password);
                    uas[0].PasswordRecoveryToken = null;
                    db.Context.Update(uas[0]);
                    proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(token.Context, "OneTimeAlert", "Your password has been reset.  Please login.");
                    proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(token.Context, "UserPasswordRecoveryId", null);
                    JsonResponse(proc, token, "{'state': 'OK'}");
                }
            }
        }
Exemplo n.º 46
0
        /// <summary>
        /// Register a stateful receptor contained within the specified membrane.
        /// </summary>
        public void Register(IMembrane membrane, IReceptor receptor)
        {
            statefulReceptors.Add(receptor);
            Type ttarget = receptor.GetType();

            MethodInfo[] methods = ttarget.GetMethods();

            foreach (MethodInfo method in methods)
            {
                // TODO: Use attribute, not specific function name.
                if (method.Name == "Process")
                {
                    ParameterInfo[] parameters = method.GetParameters();
                    InstanceNotify(receptor, parameters[2].ParameterType);
                }
            }

            membranes[membrane.GetType()] = membrane;
            membraneReceptorInstances[membrane].Add(receptor);
        }
        public void Process(ISemanticProcessor proc, IMembrane membrane, UpdateAccountInfo acctInfo)
        {
            IWebSessionService session = proc.ServiceManager.Get <IWebSessionService>();
            UserAccount        ua      = session.GetSessionObject <UserAccount>(acctInfo.Context, "UserAccount");

            ua.FirstName = acctInfo.FirstName;
            ua.LastName  = acctInfo.LastName;
            ua.Email     = acctInfo.Email;
            session.SetSessionObject(acctInfo.Context, "UserName", ua.FullName);

            if (!String.IsNullOrEmpty(acctInfo.Password))
            {
                ua.PasswordHash = PasswordHash.CreateHash(acctInfo.Password);
            }

            IDbContextService db = proc.ServiceManager.Get <IDbContextService>();

            db.Context.Update(ua);
            proc.ServiceManager.Get <IWebSessionService>().SetSessionObject(acctInfo.Context, "OneTimeAlert", "Your account information has been updated.");
            JsonResponse(proc, acctInfo, "{'state': 'OK'}");
        }
Exemplo n.º 48
0
		public MembraneEventArgs(IMembrane m)
		{
			Membrane = m;
		}
 // TODO: Mostly duplicate code
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_AssociatedData data)
 {
     model.ToData = data.Table;
     schema = data.Schema;
     DataView dv = new DataView(data.Table);
     dgView.FindForm().BeginInvoke(() =>
     {
         dgView.DataSource = dv;
         dgView.Columns[0].Visible = false;								// Hide the ID field.
         dgView.Columns[dgView.Columns.Count - 1].Visible = false;		// Also hide the last two ID fields, which are the ID's of the master and detail records.
         dgView.Columns[dgView.Columns.Count - 2].Visible = false;		// Also hide the last two ID fields, which are the ID's of the master and detail records.
         label.Text = "Semantic Type: " + data.Table.TableName;
     });
 }
Exemplo n.º 50
0
		/// <summary>
		/// Constructor, initializes internal collections.
		/// </summary>
		public ReceptorsContainer(ISemanticTypeSystem sts, IMembrane membrane = null)
		{
			Membrane = membrane;
			SemanticTypeSystem = sts;
			Initialize();
		}
Exemplo n.º 51
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Exception exception)
 {
     proc.ServiceManager.Get<IEmailExceptionLoggerService>().Log(exception.Exception);
 }
Exemplo n.º 52
0
        public void Process(ISemanticProcessor proc, IMembrane membrane, Route route)
        {
            IPublicRouterService routerService = proc.ServiceManager.Get<IPublicRouterService>();
            HttpListenerContext context = route.Context;
            HttpVerb verb = context.Verb();
            UriPath path = context.Path();
            string searchRoute = GetSearchRoute(verb, path);
            RouteInfo routeInfo;

            // Semantic routes can be either public or authenticated.
            if (routerService.Routes.TryGetValue(searchRoute, out routeInfo))
            {
                string data = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd();
                Type receptorSemanticType = routeInfo.ReceptorSemanticType;
                SemanticRoute semanticRoute = (SemanticRoute)Activator.CreateInstance(receptorSemanticType);
                semanticRoute.PostData = data;

                if (!String.IsNullOrEmpty(data))
                {
                    // Is it JSON?
                    if (data[0] == '{')
                    {
                        JsonConvert.PopulateObject(data, semanticRoute);
                    }
                    else
                    {
                        // Example: "username=sdfsf&password=sdfsdf&LoginButton=Login"
                        string[] parms = data.Split('&');

                        foreach (string parm in parms)
                        {
                            string[] keyVal = parm.Split('=');
                            PropertyInfo pi = receptorSemanticType.GetProperty(keyVal[0], BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

                            if (pi != null)
                            {
                                // TODO: Convert to property type.
                                // TODO: value needs to be re-encoded to handle special characters.
                                pi.SetValue(semanticRoute, keyVal[1]);
                            }
                        }
                    }
                }
                else if (verb.Value == "GET")
                {
                    // Parse parameters
                    NameValueCollection nvc = context.Request.QueryString;

                    foreach(string key in nvc.AllKeys)
                    {
                        PropertyInfo pi = receptorSemanticType.GetProperty(key, BindingFlags.Public | BindingFlags.Instance);

                        if (pi != null)
                        {
                            // TODO: Convert to property type.
                            // TODO: value needs to be re-encoded to handle special characters.
                            pi.SetValue(semanticRoute, nvc[key]);
                        }
                    }
                }

                // Must be done AFTER populating the object -- sometimes the json converter nulls the base class!
                semanticRoute.Context = context;
                proc.ProcessInstance<WebServerMembrane>(semanticRoute, true);		// TODO: Why execute on this thread?
            }
            else if (verb.Value == "GET")
            {
                // Only issue the UnhandledContext if this is not an authenticated route.
                if (!proc.ServiceManager.Get<IAuthenticatingRouterService>().IsAuthenticatedRoute(searchRoute))
                {
                    // Put the context on the bus for some service to pick up.
                    // All unhandled context are assumed to be public routes.
                    proc.ProcessInstance<WebServerMembrane, UnhandledContext>(c => c.Context = context);
                }
            }
            else
            {
                proc.ProcessInstance<WebServerMembrane, ExceptionResponse>(e =>
                    {
                        e.Context = context;
                        e.Exception = new Exception("Route " + searchRoute + " not defined.");
                    });
            }
        }
Exemplo n.º 53
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Log log)
 {
     string hms = DateTime.Now.ToString("HH:mm:ss");
     tbLog.FindForm().BeginInvoke(() => tbLog.AppendText("\r\n" + hms + " " + log.Message));
 }
Exemplo n.º 54
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Exception exception)
 {
     proc.ServiceManager.Get<IPaperTrailAppLoggerService>().Log(exception.Tid, exception.Exception);
 }
Exemplo n.º 55
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Log msg)
 {
     proc.ServiceManager.Get<IConsoleLoggerService>().Log(msg.Message);
 }
Exemplo n.º 56
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Log msg)
 {
     proc.ServiceManager.Get<IPaperTrailAppLoggerService>().Log(msg.Tid, msg.Message);
 }
Exemplo n.º 57
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_ExceptionObject exception)
 {
     proc.ServiceManager.Get<IConsoleLoggerService>().Log(exception.ExceptionMessage.Value);
 }
Exemplo n.º 58
0
 public void Process(ISemanticProcessor proc, IMembrane membrane, ST_CompilerError error)
 {
     proc.ServiceManager.Get<IConsoleLoggerService>().Log(error.Error);
 }
Exemplo n.º 59
0
 public void Process(ISemanticProcessor semProc, IMembrane membrane, ST_Exception msg)
 {
     Log(msg.Exception.Message);
     Log(msg.Exception.StackTrace);
 }
Exemplo n.º 60
0
 public void Process(ISemanticProcessor semProc, IMembrane membrane, ST_Log msg)
 {
     Log(msg.Message);
 }