Example #1
0
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                JToken t = JToken.FromObject(value);

                if (t.Type != JTokenType.Object)
                {
                    t.WriteTo(writer);
                }
                else
                {
                    JObject        o             = (JObject)t;
                    IList <string> propertyNames = o.Properties().Select(p => p.Name).ToList();

                    o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));

                    o.WriteTo(writer);
                }
            }
Example #2
0
            /// <inheritdoc cref="JsonConverter.WriteJson" />
            public override void WriteJson
            (
                JsonWriter writer,
                object value,
                JsonSerializer serializer
            )
            {
                CharSet charSet = (CharSet)value;

                JObject o = new JObject();

                o.AddFirst(new JProperty
                           (
                               "charset",
                               charSet.ToString()
                           ));

                o.WriteTo(writer);
            }
Example #3
0
        public static IOwinResponse WithODataEntityResponseBody(this IOwinResponse owinResponse, string baseAddress,
                                                                string entitySetName, JObject response, params JProperty[] additionalProperties)
        {
            if (response == null)
            {
                return(owinResponse);
            }

            foreach (var additionalProperty in additionalProperties.Reverse())
            {
                response.AddFirst(additionalProperty);
            }

            response.AddOdataContext(baseAddress, entitySetName);

            owinResponse.Write(response.ToString());

            return(owinResponse);
        }
Example #4
0
        private JObject SerializeEntity(INode subject, IEnumerable <IEntityQuad> quads, INode graphName, bool nativeTypes, bool useRdfType, JObject listsInGraph)
        {
            var groups = from quad in quads
                         where quad.Subject.Equals(subject) && (Equals(quad.Graph, graphName) || (quad.Graph.Equals(graphName)))
                         group quad.Object by quad.Predicate into g
                         select new { Predicate = (g.Key.Equals(RdfType) ? useRdfType ? RdfType : Node.ForLiteral(Type) : g.Key), Objects = g }
            into selection
            orderby selection.Predicate
            select selection;

            var result = new JObject();
            int i      = 0;

            foreach (var objectGroup in groups)
            {
                JProperty res;
                if (objectGroup.Predicate.Equals(RdfType) || objectGroup.Predicate.Equals(Node.ForLiteral(Type)))
                {
                    if (useRdfType)
                    {
                        res = new JProperty(new JProperty(RdfType.ToString(), new JArray(from o in objectGroup.Objects select GetPropertyValue(o, nativeTypes, listsInGraph))));
                    }
                    else
                    {
                        res = new JProperty(new JProperty(Type, new JArray(from o in objectGroup.Objects select o.ToString())));
                    }
                }
                else
                {
                    res = new JProperty(new JProperty(objectGroup.Predicate.Uri.ToString(), new JArray(from o in objectGroup.Objects select GetPropertyValue(o, nativeTypes, listsInGraph))));
                }

                if (i == 0)
                {
                    result.AddFirst(new JProperty(Id, subject.IsBlank ? "_:" + subject.BlankNode : subject.ToString()));
                    i++;
                }

                result.Add(res);
            }

            return(result);
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JToken t = JToken.FromObject(value);

            if (t.Type != JTokenType.Object)
            {
                t.WriteTo(writer);
            }
            else
            {
                JObject o      = (JObject)t;
                var     entity = value as Maintenance;
                if (entity?.groups != null)
                {
                    o.AddFirst(new JProperty("groupids", new JArray(entity.groups.Select(g => g.Id))));
                }
                o.WriteTo(writer);
            }
        }
Example #6
0
        /*
         * // this approach works but has the problem of creating messy files
         * public static bool CanIWrite(string inPath)
         * {
         *  bool canWrite = false;
         *  try
         *  {
         *      if (GlobalVar.NoMess || !GlobalVar.OnlineChecks)
         *      {
         *          return false;
         *      }
         *      else
         *      {
         *          GlobalVar.CleanupList.Add(inPath);
         *          FileStream stream = File.OpenWrite(inPath);
         *          canWrite = stream.CanWrite;
         *          stream.Close();
         *      }
         *  }
         *  catch (System.UnauthorizedAccessException)
         *  {
         *      if (GlobalVar.DebugMode)
         *      {
         *          Utility.DebugWrite("Tested write perms for " + inPath + " and couldn't write.");
         *      }
         *  }
         *  catch (System.ArgumentException)
         *  {
         *      if (GlobalVar.DebugMode)
         *      {
         *          Utility.DebugWrite("Tested write perms for " + inPath +
         *                             " but it doesn't seem to be a valid file path.");
         *      }
         *  }
         *  catch (Exception e)
         *  {
         *      if (GlobalVar.DebugMode)
         *      {
         *          Utility.DebugWrite(e.ToString());
         *      }
         *  }
         *  return canWrite;
         * }
         */

        public static JObject InvestigateFileContents(string inString)
        {
            string fileString = File.ReadAllText(inString).ToLower();

            // feed the whole thing through Utility.InvestigateString
            JObject investigatedFileContents = Utility.InvestigateString(fileString);

            if (investigatedFileContents["InterestLevel"] != null)
            {
                if (((int)investigatedFileContents["InterestLevel"]) >= GlobalVar.IntLevelToShow)
                {
                    investigatedFileContents.Remove("Value");
                    investigatedFileContents.AddFirst(new JProperty("File Path", inString));
                    return(investigatedFileContents);
                }
            }

            return(null);
        }
Example #7
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JToken jTokens = JToken.FromObject(value);

            if (jTokens.Type == JTokenType.Object)
            {
                JObject        jObjects = (JObject)jTokens;
                IList <string> list     = (
                    from p in jObjects.Properties()
                    where (p.Name == "inverse" ? false : p.Name != "transpose")
                    select p.Name).ToList <string>();
                jObjects.AddFirst(new JProperty("Keys", new JArray(list)));
                jObjects.WriteTo(writer, new JsonConverter[0]);
            }
            else
            {
                jTokens.WriteTo(writer, new JsonConverter[0]);
            }
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JToken jtoken = JToken.FromObject(value);

            if (jtoken.GetType().Name == "JObject")
            {
                JObject jobject = (JObject)jtoken;
                string  key     = this.HashData.FirstOrDefault <KeyValuePair <string, object> >((Func <KeyValuePair <string, object>, bool>)(x => x.Value == value)).Key;
                if (!jobject.ContainsKey("BlazId"))
                {
                    jobject.AddFirst((object)new JProperty("BlazId", (object)key));
                }
                jobject.WriteTo(writer);
            }
            else
            {
                jtoken.WriteTo(writer);
            }
        }
        private void ResolveLinks(JObject json, JObject entryToken, ISet <string> processedIds)
        {
            var id = ((JValue)entryToken.SelectToken("$.sys.id")).Value.ToString();

            entryToken.AddFirst(new JProperty("$id", new JValue(id)));
            processedIds.Add(id);
            var links = entryToken.SelectTokens("$.fields..sys").ToList();

            //Walk through and add any included entries as direct links.
            foreach (var linkToken in links)
            {
                var    linkId           = ((JValue)linkToken["id"]).Value.ToString();
                JToken replacementToken = null;
                if (processedIds.Contains(linkId))
                {
                    replacementToken = new JObject
                    {
                        ["$ref"] = linkId
                    };
                }
                else if (!string.IsNullOrEmpty(linkToken["linkType"]?.ToString()))
                {
                    replacementToken = json.SelectTokens($"$.includes.{linkToken["linkType"]}[?(@.sys.id=='{linkToken["id"]}')]").FirstOrDefault();

                    if (replacementToken == null)
                    {
                        //This could be due to the referenced entry being part of the original request (circular reference), so scan through that as well.
                        replacementToken = json.SelectTokens($"$.items.[?(@.sys.id=='{linkToken["id"]}')]").FirstOrDefault();
                    }
                }
                if (replacementToken != null)
                {
                    var grandParent = (JObject)linkToken.Parent.Parent;
                    grandParent.RemoveAll();
                    grandParent.Add(replacementToken.Children());

                    if (!processedIds.Contains(linkId))
                    {
                        ResolveLinks(json, grandParent, processedIds);
                    }
                }
            }
        }
Example #10
0
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                var o = new JObject();

                o.AddFirst(new JProperty("$type", GetSerializedTypeName(_type)));

                var jsonSerializer = new JsonSerializer
                {
                    TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
                    TypeNameHandling       = TypeNameHandling.Objects,
                    Converters             = { new JsonTypeConverter() }
                };

                foreach (var property in _propertyNames)
                {
                    o.Add(property, JToken.FromObject(GetPropValue(value, property), jsonSerializer));
                }

                o.WriteTo(writer);
            }
Example #11
0
        override protected JObject WriteAndRead()
        {
            JObject rmtd = new JObject();
            float   flow = sr118.ReadData(SR188.MeterAddr.BroadcastAddress);

            //Debug.WriteLine("jbsb data is :  \r\n"+ flow);

            if (flow >= 0)
            {
                if (!flow.ToString().Equals(LXSGZ20Flow))
                {
                    LXSGZ20Flow = flow.ToString();
                    rmtd.Add("LXSGZ20Flow", LXSGZ20Flow);
                }

                rmtd.AddFirst(new JProperty("LXSGZ20CommState", "0"));
            }

            return(rmtd);
        }
Example #12
0
        /*
         * Helper for above.
         */
        static JToken SerializeNode(ApplicationContext context, Node node)
        {
            if (node.Count == 0)
            {
                return(node.Value == null ? null : JToken.FromObject(node.Value)); // Simple object.
            }
            if (node.FirstChild.Name == "" && node.Value == null)
            {
                return(new JArray(node.Children.Select(ix => ArrayHelper(context, ix))));
            }

            // Complex object.
            var retVal = new JObject(node.Children.Select(ix => new JProperty(ix.Name, SerializeNode(context, ix))));

            if (node.Value != null)
            {
                retVal.AddFirst(new JProperty("__value", JToken.FromObject(node.Value)));    // Value AND Children, preserving value as "__value".
            }
            return(retVal);
        }
        public override void WriteJson(
            JsonWriter writer,
            object value,
            JsonSerializer serializer)
        {
            ThrowIf.Null(writer, "writer");

            JObject wrapperJObject = new JObject();

            JObject safetyCheckJObject = JObject.FromObject(value);

            // Enforce order of properties
            JProperty kindJProperty = safetyCheckJObject.Property(JsonSerializerImplConstants.Kind);

            safetyCheckJObject.Remove(JsonSerializerImplConstants.Kind);
            safetyCheckJObject.AddFirst(kindJProperty);

            wrapperJObject.Add(JsonSerializerImplConstants.SafetyCheck, safetyCheckJObject);

            wrapperJObject.WriteTo(writer);
        }
Example #14
0
        /// <summary>
        /// Inserts metadata about the log file into a Json object.  Also sets a custom id field.
        /// </summary>
        /// <param name="json">A Json object containing log information.</param>
        /// <returns>The Json object with available file context, id and line metadata added.</returns>
        public virtual JObject InsertMetadata(JObject json)
        {
            if (FileContext != null)
            {
                string id = String.Format(@"{0}/{1}", FileContext.FileLocationRelativeToRoot.Replace('\\', '/'), FileContext.LogicalFileName);
                if (UseLineNumbers)
                {
                    id = String.Format("{0}-{1}", id, LineCounter.CurrentValue);
                }
                json.AddFirst(new JProperty("_id", id));
                json.Add(new JProperty("file_path", FileContext.FileLocationRelativeToRoot));
                json.Add(new JProperty("file", FileContext.LogicalFileName));
                json.Add(new JProperty("worker", FileContext.WorkerIndex));
            }

            if (UseLineNumbers)
            {
                json.Add(new JProperty("line", LineCounter.CurrentValue));
            }

            return(json);
        }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JToken t = JToken.FromObject(value);

        if (t.Type != JTokenType.Object)
        {
            t.WriteTo(writer);
        }
        else
        {
            JObject        o             = (JObject)t;
            IList <string> propertyNames = o.Properties().Select(p => p.Name).ToList();

            JObject root = new JObject();

            JObject props = JObject.Parse(@"{""prop"" : ""A"", ""value"":""B""}");
            root.AddFirst(new JProperty(o["DeviceId"].Value <object>().ToString(), props));


            root.WriteTo(writer);
        }
    }
        public override void WriteJson(JsonWriter w, object o, JsonSerializer szr)
        {
            var settings      = JsonBlueprints.CreateSettings(null);
            var newSerializer = JsonSerializer.Create(settings);
            var j             = new JObject();

            j.AddFirst(new JProperty("$type", JsonBlueprints.GetTypeName(o.GetType())));
            foreach (var memberInfo in JsonBlueprints.GetUnitySerializableMembers(o.GetType()))
            {
                object value = null;
                if (memberInfo.MemberType == MemberTypes.Field)
                {
                    value = ((FieldInfo)memberInfo).GetValue(o);
                }
                else if (memberInfo.MemberType == MemberTypes.Property)
                {
                    value = ((PropertyInfo)memberInfo).GetValue(o);
                }
                j.Add(memberInfo.Name, value != null ? JToken.FromObject(value, newSerializer) : null);
            }
            j.WriteTo(w);
        }
 static async Task ExecuteGraphOperationAsync(JObject operationParams, string operationName, JProperty apiVersionProperty)
 {
     try
     {
         if (operationParams == null)
         {
             PrintMessage("opParams object is missing", ConsoleColor.Red);
             PrintMessage("Press Enter to continue", ConsoleColor.Yellow);
             Console.ReadLine();
         }
         else
         {
             JObject lvaGraphObject = operationParams;
             lvaGraphObject.AddFirst(apiVersionProperty);
             await InvokeMethodWithPayloadAsync(operationName, lvaGraphObject.ToString());
         }
     }
     catch (Exception ex)
     {
         PrintMessage(ex.ToString(), ConsoleColor.Red);
     }
 }
Example #18
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var converters = serializer.Converters.Where(x => !(x is BeContractQueryConverter)).ToArray();
            //Create a whole new JObject for exception: Self referencing loop throws by JObject.FromObject
            var query     = value as Query;
            var jObject   = new JObject();
            var jMappings = new JArray();

            query?.Mappings?.ForEach(m =>
            {
                var jMapping = new JObject
                {
                    new JProperty("InputKey", m.InputKey),
                    new JProperty("LookupInputId", m.LookupInputId),
                    new JProperty("LookupInputKey", m.LookupInputKey)
                };
                jMappings.Add(jMapping);
            });
            jObject.AddFirst(new JProperty("Contract", query?.Contract?.Id));
            jObject.Add(new JProperty("Mappings", jMappings));
            jObject.WriteTo(writer, converters);
        }
        private JObject PrepareInput(
            string deviceid, string[] properties, DateTime from, DateTime to)
        {
            var       result                  = new JObject();
            JObject   inlineVariable          = new JObject();
            JProperty propholder              = null;
            JArray    projectedVariablesArray = new JArray();

            if (properties != null && properties.Length > 0)
            {
                foreach (var prop in properties)
                {
                    propholder = new JProperty(prop, new JObject(
                                                   new JProperty(PROPERTY_KIND, PROPERTY_KIND_VALUE),
                                                   new JProperty(TIME_SERIES_EXPRESSION_VALUE,
                                                                 new JObject(new JProperty(TIME_SERIES_EXPRESSION, "$event.[" + prop + "]"))),
                                                   new JProperty(TIME_SERIES_EXPRESSION_FILTER, null),
                                                   new JProperty(TIME_SERIES_EXPRESSION_AGGREGATION,
                                                                 new JObject(new JProperty(TIME_SERIES_EXPRESSION, "avg($value)")))
                                                   ));

                    projectedVariablesArray.Add(prop);
                    inlineVariable.AddFirst(propholder);
                }
            }

            result.Add(AGGREGATE_SERIES, new JObject(
                           new JProperty(SEARCH_SPAN_KEY, new JObject(
                                             new JProperty(FROM_KEY, from.ToString(TSI_DATE_FORMAT)),
                                             new JProperty(TO_KEY, to.ToString(TSI_DATE_FORMAT)))),
                           new JProperty(TIME_SERIES_ID, new JArray(deviceid)),          //incase you have multiple devices please pass it as array
                           new JProperty(TIME_SERIES_INTERVAL, TIME_SERIES_AGGREGATION), //give your time aggregation here
                           new JProperty(TIME_SERIES_INLINE_VARIABLES, inlineVariable),
                           new JProperty(TIME_SERIES_PROJECTED_VARIABLES, projectedVariablesArray)
                           ));

            return(result);
        }
Example #20
0
        public object Machine(object data)
        {
            try
            {
                var json = new JObject();
                if (data != null)
                {
                    var  jsonSerialized = JsonConvert.SerializeObject(data);
                    bool valid          = _queueForwarder.Forward(jsonSerialized);
                    if (!valid)
                    {
                        return(StatusCode(HttpStatusCode.PreconditionFailed));
                    }
                }

                json.AddFirst(new JProperty("imported", true));
                return(Json(json));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Example #21
0
        public static string SerializeChaosEvents(ChaosEventsSegment events)
        {
            // we will convert the chaos events to a dto that follows the required format in native.
            JsonSerializer serializer = JsonSerializer.Create(chaosEventsDescriptionSerializationSettings);

            JObject eventsDTO = JObject.FromObject(events, serializer);

            for (int i = 0; i < ((JArray)eventsDTO["History"]).Count; ++i)
            {
                // turns each ChaosEvent in history from { ChaosEvent stuff} into { ChaosEvent: { ChaosEvent stuff } }
                JObject chaosEventWrapper = new JObject();
                JObject chaosEventDTO     = (JObject)((JArray)eventsDTO["History"])[i];

                JProperty kindProperty = new JProperty(chaosEventDTO.Property("Kind"));
                chaosEventDTO.Property("Kind").Remove();
                chaosEventDTO.AddFirst(kindProperty);

                chaosEventWrapper["ChaosEvent"]   = chaosEventDTO;
                ((JArray)eventsDTO["History"])[i] = chaosEventWrapper;
            }

            return(JsonConvert.SerializeObject(eventsDTO, chaosEventsDescriptionSerializationSettings));
        }
Example #22
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var properties = value.GetType()
                             .GetProperties()
                             .Where
                             (
                p => p.PropertyType != typeof(DynamicObject) &&
                p.GetIndexParameters().Length == 0 &&
                !Attribute.IsDefined(p, typeof(JsonIgnoreAttribute))
                             ).ToList();

            JObject o = (JObject)JToken.FromObject(value, serializer);

            foreach (PropertyInfo property in properties)
            {
                if (o[property.Name] == null)
                {
                    o.AddFirst(new JProperty(property.Name, property.GetValue(value)));
                }
            }

            o.WriteTo(writer);
        }
Example #23
0
        /// <summary>
        ///     Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The Newtonsoft.Json.JsonWriter to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(
            JsonWriter writer,
            object value,
            JsonSerializer serializer)
        {
            JToken t            = JToken.FromObject(value);
            string instanceType = null;

            if (value != null)
            {
                if (string.Compare(value.GetType().ToString(), typeof(RecoveryPlanAutomationRunbookActionDetails).ToString()) == 0)
                {
                    instanceType = RecoveryPlanActionDetailsType.AutomationRunbookActionDetails.ToString();
                }
                else if (string.Compare(value.GetType().ToString(), typeof(RecoveryPlanManualActionDetails).ToString()) == 0)
                {
                    instanceType = RecoveryPlanActionDetailsType.ManualActionDetails.ToString();
                }
                else if (string.Compare(value.GetType().ToString(), typeof(RecoveryPlanScriptActionDetails).ToString()) == 0)
                {
                    instanceType = RecoveryPlanActionDetailsType.ScriptActionDetails.ToString();
                }
            }
            if (t.Type != JTokenType.Object)
            {
                t.WriteTo(writer);
            }
            else
            {
                JObject        o             = (JObject)t;
                IList <string> propertyNames = o.Properties().Select(p => p.Name).ToList();

                o.AddFirst(new JProperty(Constants.InstanceType, instanceType));

                o.WriteTo(writer);
            }
        }
Example #24
0
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex   = Server.GetLastError();
            string    str  = GetStringFromFile("Errors.xml");
            string    time = "_" + DateTime.Now.ToString() + "_";

            if (str == "" || str == "File not exist" || str == null || str == "\r\n")
            {
                //Handle new or empty file
                JObject     obj = new JObject(new JProperty(time, JsonConvert.SerializeObject(ex.Message)));
                XmlDocument doc = JsonConvert.DeserializeXmlNode(obj.ToString(), "root");
                PutStringToFile("Errors.xml", doc.OuterXml);
            }
            else
            {   //Write the error to file
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(str);
                string  jsonText = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);
                JObject errors   = JObject.Parse(jsonText);
                errors.AddFirst(new JProperty(time, JsonConvert.SerializeObject(ex.Message)));
                doc = JsonConvert.DeserializeXmlNode(errors.ToString(), "root");
                PutStringToFile("Errors.xml", doc.OuterXml);
            }
        }
        public static JObject AssessServiceGenSetting(JToken svcGenSettings)
        {
            JObject svcGenSettingsJObject = (JObject)svcGenSettings;

            JObject assessedSvcGenSettings = new JObject();

            int inc = 0;

            foreach (KeyValuePair <string, JToken> svcGenSetting in svcGenSettingsJObject)
            {
                inc++;
                int    interestLevel = 3;
                string serviceName   = svcGenSetting.Key.Trim('"', '\\');
                JArray svcSettings   = (JArray)svcGenSetting.Value;
                string startupType   = svcSettings[0].ToString().Trim('"', '\\');
                string sddl          = svcSettings[1].ToString().Trim('"', '\\');

                string startupString = "";
                switch (startupType)
                {
                case "2":
                    startupString = "Automatic";
                    break;

                case "3":
                    startupString = "Manual";
                    break;

                case "4":
                    startupString = "Disabled";
                    break;
                }

                JObject assessedSddl = new JObject();
                // go parse the SDDL
                if (sddl.Length > 4)
                {
                    JObject parsedSddl = ParseSddl.ParseSddlString(sddl, SecurableObjectType.WindowsService);

                    // then assess the results based on interestLevel


                    if (parsedSddl["Owner"] != null)
                    {
                        assessedSddl.Add("Owner", parsedSddl["Owner"].ToString());
                        interestLevel = 2;
                    }

                    if (parsedSddl["Group"] != null)
                    {
                        assessedSddl.Add("Group", parsedSddl["Group"].ToString());
                        interestLevel = 2;
                    }

                    if (parsedSddl["DACL"] != null)
                    {
                        JObject assessedDacl = new JObject();

                        string[] boringSidEndings = new string[]
                        {
                            "-3-0", "-5-9", "5-18", "-512", "-519", "SY", "BA", "DA", "CO", "ED", "PA", "CG", "DD",
                            "EA", "LA",
                        };
                        string[] interestingSidEndings = new string[]
                        { "DU", "WD", "IU", "BU", "AN", "AU", "BG", "DC", "DG", "LG" };
                        string[] interestingRights = new string[] { "WRITE_PROPERTY", "WRITE_DAC", "WRITE_OWNER" };

                        foreach (JProperty ace in parsedSddl["DACL"].Children())
                        {
                            int    aceInterestLevel = 0;
                            string trusteeSid       = ace.Value["SID"].ToString();

                            bool boringUserPresent = false;

                            bool interestingRightPresent = false;

                            foreach (string interestingRight in interestingRights)
                            {
                                foreach (JToken right in ace.Value["Rights"])
                                {
                                    if (interestingRight == right.ToString())
                                    {
                                        interestingRightPresent = true;
                                        break;
                                    }

                                    if (interestingRightPresent)
                                    {
                                        break;
                                    }
                                }
                            }

                            foreach (string boringSidEnding in boringSidEndings)
                            {
                                if (trusteeSid.EndsWith(boringSidEnding))
                                {
                                    boringUserPresent = true;
                                    break;
                                }
                            }

                            bool interestingUserPresent = false;
                            foreach (string interestingSidEnding in interestingSidEndings)
                            {
                                if (trusteeSid.EndsWith(interestingSidEnding))
                                {
                                    interestingUserPresent = true;
                                    break;
                                }
                            }

                            // first look if both match
                            if (interestingUserPresent && interestingRightPresent)
                            {
                                aceInterestLevel = 10;
                            }
                            // then skip if they're dumb defaults
                            else if (interestingRightPresent && boringUserPresent)
                            {
                                aceInterestLevel = 0;
                            }
                            // then catch all the non-default but high-privs
                            else if (interestingRightPresent && !interestingUserPresent)
                            {
                                aceInterestLevel = 7;
                            }
                            // then give them a nudge if they're non-default
                            else if (interestingUserPresent && !interestingRightPresent)
                            {
                                aceInterestLevel = 1;
                            }

                            if (aceInterestLevel >= GlobalVar.IntLevelToShow)
                            {
                                // pass the whole thing on
                                assessedSddl.Add(ace);
                            }
                        }

                        if ((assessedDacl != null) && (assessedDacl.HasValues))
                        {
                            assessedSddl.Add("DACL", assessedDacl);
                        }
                    }
                }

                if (interestLevel >= GlobalVar.IntLevelToShow)
                {
                    if (assessedSddl.HasValues)
                    {
                        assessedSddl.AddFirst(new JProperty("Service", serviceName));
                        assessedSddl.Add("Startup Type", startupString);
                        assessedSvcGenSettings.Add(inc.ToString(), assessedSddl);
                    }
                }
            }

            if (assessedSvcGenSettings.Count <= 0)
            {
                return(null);
            }

            return(assessedSvcGenSettings);
        }
Example #26
0
        private void ResolveLinks(JObject json, JObject entryToken, ISet <string> processedIds, Type type)
        {
            var id = ((JValue)entryToken.SelectToken("$.sys.id"))?.Value?.ToString();

            if (id == null)
            {
                //No id token present, not possible to resolve links. Probably because the sys property has been excluded with a select statement.
                return;
            }

            ResolveContentTypes(entryToken);

            if (entryToken["$type"] != null)
            {
                type = Type.GetType(entryToken["$type"].Value <string>());
            }

            if (!processedIds.Contains(id))
            {
                entryToken.AddFirst(new JProperty("$id", new JValue(id)));
                processedIds.Add(id);
            }

            var links = entryToken.SelectTokens("$.fields..sys").ToList();

            //Walk through and add any included entries as direct links.
            foreach (var linkToken in links)
            {
                var propName = (linkToken.Parent.Parent.Ancestors().FirstOrDefault(a => a is JProperty) as JProperty)?.Name;

                var    linkId           = ((JValue)linkToken["id"]).Value.ToString();
                JToken replacementToken = null;
                if (processedIds.Contains(linkId))
                {
                    replacementToken = new JObject
                    {
                        ["$ref"] = linkId
                    };
                }
                else if (!string.IsNullOrEmpty(linkToken["linkType"]?.ToString()))
                {
                    replacementToken = json.SelectTokens($"$.includes.{linkToken["linkType"]}[?(@.sys.id=='{linkId}')]").FirstOrDefault();

                    if (replacementToken == null)
                    {
                        //This could be due to the referenced entry being part of the original request (circular reference), so scan through that as well.
                        replacementToken = json.SelectTokens($"$.items.[?(@.sys.id=='{linkId}')]").FirstOrDefault();
                    }
                }

                var grandParent = (JObject)linkToken.Parent.Parent;

                if (replacementToken != null)
                {
                    grandParent.RemoveAll();
                    grandParent.Add(replacementToken.Children());
                    PropertyInfo prop = null;

                    if (ResolveEntriesSelectively)
                    {
                        prop = type?.GetRuntimeProperties().FirstOrDefault(p => (p.Name.Equals(propName, StringComparison.OrdinalIgnoreCase) ||
                                                                                 p.GetCustomAttribute <JsonPropertyAttribute>()?.PropertyName == propName));
                        if (prop == null)
                        {
                            //the property does not exist in the entry. Skip it in resolving references.
                            continue;
                        }
                    }

                    if (!processedIds.Contains(linkId))
                    {
                        Type propType = null;

                        if (ResolveEntriesSelectively)
                        {
                            propType = prop?.PropertyType;

                            if (propType != null && typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(propType.GetTypeInfo()) && propType.IsConstructedGenericType)
                            {
                                propType = propType.GetTypeInfo().GenericTypeArguments[0];
                            }
                        }

                        ResolveLinks(json, grandParent, processedIds, propType);
                    }
                }
                else
                {
                    var errorToken = json.SelectTokens($"$.errors.[?(@.details.id=='{linkId}')]").FirstOrDefault();

                    // The include is missing and present in the errors (possibly it was removed in contentful), we skip it to make sure it deserializes to null
                    if (errorToken != null)
                    {
                        var itemToSkip = grandParent.Parent is JProperty ? grandParent.Parent : grandParent;
                        itemToSkip.Remove();
                    }
                }
            }
        }
Example #27
0
        // Posts a publication message on a channel.
        public void PostPublicationMessage(string sessionId, string body, ref string responseContent, ref HttpStatusCode statusCode, ref string reasonPhrase)
        {
            try
            {
                // Create a new Database Handler
                DatabaseHandler myDatabaseHandler = new DatabaseHandler();

                // SQL Statement to read session with matching sessionId
                string  sqlStatement    = "Select * from Sessions where Session_UUID = '" + sessionId + "'";
                DataSet SessionsDataset = myDatabaseHandler.Select(sqlStatement);

                string status = SessionsDataset.Tables[0].Rows[0]["Status"].ToString();

                // Skip posting publication if no matching open session
                if (SessionsDataset.Tables[0].Rows.Count != 0 && status == "Open")
                {
                    string channelType = SessionsDataset.Tables[0].Rows[0]["Channel_Type"].ToString();
                    string subscriber  = SessionsDataset.Tables[0].Rows[0]["Subscribed_By"].ToString();

                    // Continue posting publication if the channelType is "Publication" and subsriber is "provider"
                    if (channelType == "Publication" && subscriber == "Provider")
                    {
                        string messageId = Guid.NewGuid().ToString();
                        string channelId = SessionsDataset.Tables[0].Rows[0]["Channel_UUID"].ToString();

                        // Load HTTP request content into Newtonsoft JObject
                        JObject jsonBody = JObject.Parse(body);
                        // Add messageId to the message
                        jsonBody.Property("topics").AddAfterSelf(new JProperty("messageId", messageId));

                        // Generate modified message from the JObject
                        string messageBody = jsonBody.ToString(Formatting.None);

                        // Get Azure Bus SAS token string from Web.Config
                        string ServiceBusConnectionString = ConfigurationManager.ConnectionStrings["AzureBus"].ConnectionString;
                        // Create a new message sender
                        MessageSender myMessageSender = new MessageSender();
                        // Use PublishMessage method to send Azure Bus message
                        myMessageSender.PublishMessage(ServiceBusConnectionString, messageBody, messageId, channelId);

                        // Format response content using Newtonsoft JObject
                        JObject jsonMessageId = new JObject();
                        jsonMessageId.AddFirst(new JProperty("messageId", messageId));
                        // Generate JSON string from the JObject
                        responseContent = JsonConvert.SerializeObject(jsonMessageId);

                        // Set HTTP status code and reason phrase
                        // 2xx for success
                        statusCode   = (HttpStatusCode)201;
                        reasonPhrase = "The message has been successfully posted to the channel.Returns only the ID of the message.";
                    }

                    else
                    {
                        // Set HTTP status code and reason phrase
                        // 4xx for Client Error
                        statusCode   = (HttpStatusCode)422;
                        reasonPhrase = "The Session is not of type Publication Provider";
                    }
                }

                else
                {
                    // Set HTTP status code and reason phrase
                    // 4xx for Client Error
                    statusCode   = (HttpStatusCode)404;
                    reasonPhrase = "The session does not exist or has been closed.";
                }
            }

            catch (Exception e)
            {
                // Set HTTP status code and reason phrase
                // 5xx for server error not defined by ISBM
                statusCode   = (HttpStatusCode)500;
                reasonPhrase = "Internal Server Error";

                return;
            }
        }
Example #28
0
        // Opens a subscription session for a channel.
        public void OpenConsumerPublicationSession(string channelId, string body, ref string responseContent, ref HttpStatusCode statusCode, ref string reasonPhrase)
        {
            try
            {
                // Replace percent encoding characters
                channelId = System.Uri.UnescapeDataString(channelId);

                // Create a new Database Handler
                DatabaseHandler myDatabaseHandler = new DatabaseHandler();

                // SQL Statement to read channel with matching channelId
                string  sqlStatement   = "Select * from Channels where Channel_Id = '" + channelId + "'";
                DataSet channelDataset = myDatabaseHandler.Select(sqlStatement);

                // Skip opening a publication session if no record returned
                if (channelDataset.Tables[0].Rows.Count != 0)
                {
                    string channelType = "";
                    channelType = channelDataset.Tables[0].Rows[0]["Channel_Type"].ToString();
                    // Skip opening a publication session if channelType is not of type Publication
                    if (channelType == "Publication")
                    {
                        string subscribedBy = "Consumer";
                        string status       = "Open";

                        string sessionUUID = Guid.NewGuid().ToString();
                        string channelUUID = channelDataset.Tables[0].Rows[0]["Channel_UUID"].ToString();

                        // SQL Statement to create the new session on database
                        sqlStatement = "Insert into Sessions (Session_UUID, Channel_UUID, Channel_Type, Subscribed_By, Status) values ('" + sessionUUID + "', '" + channelUUID + "', '" + channelType + "', '" + subscribedBy + "', '" + status + "')";
                        myDatabaseHandler.Insert(sqlStatement);

                        // Load HTTP request content into Newtonsoft JObject
                        JObject jsonBody = JObject.Parse(body);
                        JArray  topics   = (JArray)jsonBody["topics"];
                        int     length   = topics.Count;

                        // Create a record for each topic on the database
                        // Topic filtering will be done by the ISBM adapter in the future release
                        for (int i = 0; i < length; i++)
                        {
                            string topic = (string)topics[i];

                            // SQL Statement to create the new session topic on database
                            sqlStatement = "Insert into SessionTopics (Session_UUID, Topic) values ('" + sessionUUID + "', '" + topic + "')";
                            myDatabaseHandler.Insert(sqlStatement);
                        }

                        // Format response content using Newtonsoft JObject
                        JObject jsonSessionId = new JObject();
                        jsonSessionId.AddFirst(new JProperty("sessionId", sessionUUID));
                        // Generate JSON string from the jArray object
                        responseContent = JsonConvert.SerializeObject(jsonSessionId);

                        // Get Azure Bus SAS token string from Web.Config
                        string ServiceBusConnectionString = ConfigurationManager.ConnectionStrings["AzureBus"].ConnectionString;
                        // Create a new Azure Management
                        AzureManagement myAzureManagement = new AzureManagement();
                        // Create an Azure Bus topic subscription in the form of UUID corresponding to channel record
                        // ISBM channels are mapped to Azure Bus topics
                        myAzureManagement.CreateTopicSubscriptions(ServiceBusConnectionString, channelUUID, sessionUUID);

                        // Set HTTP status code and reason phrase
                        // 2xx for success
                        statusCode   = (HttpStatusCode)201;
                        reasonPhrase = "The subscription session has been successfully opened on the channel. Only the SessionID is to be returned.";
                    }
                    else
                    {
                        // Set HTTP status code and reason phrase
                        // 4xx for Client Error
                        statusCode   = (HttpStatusCode)422;
                        reasonPhrase = "The Channel is not of type Publication.";
                    }
                }
                else
                {
                    // Set HTTP status code and reason phrase
                    // 4xx for Client Error
                    statusCode   = (HttpStatusCode)404;
                    reasonPhrase = "The Channel does not exists.";
                }
            }

            catch (Exception e)
            {
                // Set HTTP status code and reason phrase
                // 5xx for server error not defined by ISBM
                statusCode   = (HttpStatusCode)500;
                reasonPhrase = "Internal Server Error";

                return;
            }
        }
Example #29
0
        // Opens a publication session for a channel.
        public void OpenProviderPublicationSession(string channelId, ref string responseContent, ref HttpStatusCode statusCode, ref string reasonPhrase)
        {
            try
            {
                // Repace percent enconding characters
                channelId = System.Uri.UnescapeDataString(channelId);

                // Create a new Database Handler
                DatabaseHandler myDatabaseHandler = new DatabaseHandler();

                // SQL Statement to read channel with matching channelId
                string  sqlStatement   = "Select * from Channels where Channel_Id = '" + channelId + "'";
                DataSet channelDataset = myDatabaseHandler.Select(sqlStatement);

                // Skip opening a publication session if no record returned
                if (channelDataset.Tables[0].Rows.Count != 0)
                {
                    string channelType = "";
                    channelType = channelDataset.Tables[0].Rows[0]["Channel_Type"].ToString();
                    // Skip opening a publication session if channelType is not of type Publication
                    if (channelType == "Publication")
                    {
                        string subscribedBy = "Provider";
                        string status       = "Open";

                        string sessionUUID = Guid.NewGuid().ToString();
                        string channelUUID = channelDataset.Tables[0].Rows[0]["Channel_UUID"].ToString();

                        // SQL Statement to create the new session on database
                        sqlStatement = "Insert into Sessions (Session_UUID, Channel_UUID, Channel_Type, Subscribed_By, Status) values ('" + sessionUUID + "', '" + channelUUID + "', '" + channelType + "', '" + subscribedBy + "', '" + status + "')";
                        myDatabaseHandler.Insert(sqlStatement);

                        // Format response content using Newtonsoft JObject
                        JObject jsonSessionId = new JObject();
                        jsonSessionId.AddFirst(new JProperty("sessionId", sessionUUID));
                        // Generate JSON string from the jArray object
                        responseContent = JsonConvert.SerializeObject(jsonSessionId);

                        // Set HTTP status code and reason phrase
                        // 2xx for success
                        statusCode   = (HttpStatusCode)201;
                        reasonPhrase = "The publication session has been successfully opened on the channel. Only the SessionID is to be returned.";
                    }
                    else
                    {
                        // Set HTTP status code and reason phrase
                        // 4xx for Client Error
                        statusCode   = (HttpStatusCode)422;
                        reasonPhrase = "The Channel is not of type Publication.";
                    }
                }
                else
                {
                    // Set HTTP status code and reason phrase
                    // 4xx for Client Error
                    statusCode   = (HttpStatusCode)404;
                    reasonPhrase = "The Channel does not exists.";
                }
            }

            catch (Exception e)
            {
                // Set HTTP status code and reason phrase
                // 5xx for server error not defined by ISBM
                statusCode   = (HttpStatusCode)500;
                reasonPhrase = "Internal Server Error";

                return;
            }
        }
Example #30
0
        public static async Task <Configuration> LoadConfigurationAsync(string configurationFilenameOrUrl)
        {
            JObject localconfiguration = null;

            if (!string.IsNullOrWhiteSpace(configurationFilenameOrUrl))
            {
                string configurationContent;

                // Load the job definition from a url or locally
                try
                {
                    if (configurationFilenameOrUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        configurationContent = await _httpClient.GetStringAsync(configurationFilenameOrUrl);
                    }
                    else
                    {
                        configurationContent = File.ReadAllText(configurationFilenameOrUrl);
                    }
                }
                catch
                {
                    throw new RegressionBotException($"Configuration '{configurationFilenameOrUrl}' could not be loaded.");
                }

                // Detect file extension
                string configurationExtension = null;

                if (configurationFilenameOrUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    // Remove any query string to detect the correct extension
                    var questionMarkIndex = configurationFilenameOrUrl.IndexOf("?");
                    if (questionMarkIndex != -1)
                    {
                        var filename = configurationFilenameOrUrl.Substring(0, questionMarkIndex);
                        configurationExtension = Path.GetExtension(filename);
                    }
                    else
                    {
                        configurationExtension = Path.GetExtension(configurationFilenameOrUrl);
                    }
                }
                else
                {
                    configurationExtension = Path.GetExtension(configurationFilenameOrUrl);
                }

                switch (configurationExtension)
                {
                case ".json":
                    localconfiguration = JObject.Parse(configurationContent);
                    break;

                case ".yml":
                case ".yaml":

                    var deserializer = new DeserializerBuilder()
                                       .WithNodeTypeResolver(new JsonTypeResolver())
                                       .Build();

                    object yamlObject;

                    try
                    {
                        yamlObject = deserializer.Deserialize(new StringReader(configurationContent));
                    }
                    catch (YamlDotNet.Core.SyntaxErrorException e)
                    {
                        throw new RegressionBotException($"Error while parsing '{configurationFilenameOrUrl}'\n{e.Message}");
                    }

                    var serializer = new SerializerBuilder()
                                     .JsonCompatible()
                                     .Build();

                    var json = serializer.Serialize(yamlObject);

                    // Format json in case the schema validation fails and we need to render error line numbers
                    localconfiguration = JObject.Parse(json);

                    var schemaJson = File.ReadAllText(Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "regressionbot.schema.json"));
                    var schema     = new Manatee.Json.Serialization.JsonSerializer().Deserialize <JsonSchema>(JsonValue.Parse(schemaJson));

                    var jsonToValidate    = JsonValue.Parse(json);
                    var validationResults = schema.Validate(jsonToValidate, new JsonSchemaOptions {
                        OutputFormat = SchemaValidationOutputFormat.Detailed
                    });

                    if (!validationResults.IsValid)
                    {
                        // Create a json debug file with the schema
                        localconfiguration.AddFirst(new JProperty("$schema", "https://raw.githubusercontent.com/dotnet/crank/master/src/Microsoft.Crank.RegressionBot/regressionbot.schema.json"));

                        var debugFilename = Path.Combine(Path.GetTempPath(), "configuration.debug.json");
                        File.WriteAllText(debugFilename, localconfiguration.ToString(Formatting.Indented));

                        var errorBuilder = new StringBuilder();

                        errorBuilder.AppendLine($"Invalid configuration file '{configurationFilenameOrUrl}' at '{validationResults.InstanceLocation}'");
                        errorBuilder.AppendLine($"{validationResults.ErrorMessage}");
                        errorBuilder.AppendLine($"Debug file created at '{debugFilename}'");

                        throw new RegressionBotException(errorBuilder.ToString());
                    }

                    break;

                default:
                    throw new RegressionBotException($"Unsupported configuration format: {configurationExtension}");
                }

                return(localconfiguration.ToObject <Configuration>());
            }
            else
            {
                throw new RegressionBotException($"Invalid file path or url: '{configurationFilenameOrUrl}'");
            }
        }