Exemplo n.º 1
0
        /// <summary>
        /// This helper function parses an RSA private key using the ASN.1 format
        /// </summary>
        /// <param name="privateKeyBytes">Byte array containing PEM string of private key.</param>
        /// <returns>An instance of <see cref="RSACryptoServiceProvider"/> rapresenting the requested private key.
        /// Null if method fails on retriving the key.</returns>
        public static RSACryptoServiceProvider DecodeRsaPrivateKey(string privateKey,string password="")
        {
            Dictionary<string, string> extras = new Dictionary<string, string>();
            byte[] bytes = Helpers.GetBytesFromPEM(privateKey, out extras);

            if (extras.Any(x => x.Value.Contains("ENCRYPTED")) && extras.Any(x => x.Key.Contains("DEK-Inf")))
            {
                String saltstr = extras.First(x => x.Key.Contains("DEK-Inf")).Value.Split(',')[1].Trim();
                byte[] salt = new byte[saltstr.Length / 2];

                for (int i = 0; i < salt.Length; i++)
                    salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16);
                SecureString despswd = new SecureString(); // GetSecPswd("Enter password to derive 3DES key==>");
                foreach (char c in password)
                    despswd.AppendChar(c);
                byte[] decoded = DecryptRSAPrivatePEM(bytes, salt, despswd);
                bytes = decoded;
            }

            return DecodeRsaPrivateKey(bytes);
        }
Exemplo n.º 2
0
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            _strokeThicknesses = this.Resources.OfType<DictionaryEntry>()
                .Where(x => x.Value is double)
                .Where(x => x.Key.ToString().ToLower().Contains("strokethickness"))
                .ToDictionary(x => x.Key.ToString(), x => (double)x.Value);

            if (!_strokeThicknesses.Any())
                return;

            var parentGrid = VisualTreeHelper.GetParent(this) as Grid;
            if (parentGrid != null)
            {
                this.SetBinding(
                    ScaleFactorProperty,
                    new Binding("RenderTransform.ScaleX") { Source = parentGrid });
            }
        }
        /// <summary>
        /// Trying to serialize something that the user passed in. Sometimes this is used to serialize what we know is additional debug and sometimes it is the primary logged item. This is why the serializeSimpleTypes exists. For additional debug stuff we always serialize it. For the primary logged object we won't because it doesn't make any sense to put a string in the json as well as the main message. It's meant for objects.
        /// </summary>
        /// <param name="logObject"></param>
        /// <param name="serializeSimpleTypes"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public static string SerializeDebugData(object logObject, bool serializeSimpleTypes, Dictionary<string, object> properties = null)
        {
            Type t = null;

            JObject jObject = null;

            try
            {
                if (logObject == null)
                {
                }
                else
                {
                    t = logObject.GetType();

                    if (logObject is string || t.FullName == "log4net.Util.SystemStringFormat" )
                    {
                        if (serializeSimpleTypes)
                        {
                            jObject = new JObject();
                            jObject.Add("logArg", new JValue(logObject.ToString()));
                        }
                    }
                    else if (t.IsPrimitive || t.BaseType == typeof(ValueType))
                    {
                        if (serializeSimpleTypes)
                        {
                            jObject = new JObject();
                            try
                            {
                                jObject.Add("logArg", new JValue(logObject));
                            }
                            catch (ArgumentException)
                            {
                                jObject.Add("logArg", new JValue(logObject.ToString()));
                            }
                        }
                    }
                    //look for some things we don't want to touch
                    else if (logObject is IDisposable || logObject is MarshalByRefObject)
                    {

                    }
                    else if (!_BadTypes.Contains(t.ToString()))
                    {
                        var token = JToken.FromObject(logObject, serializer);

                        if (token is JObject)
                        {
                            jObject = (JObject)token;
                            var type = logObject.GetType();

                            //do we log the objectType? Not logging it for simple things
                            if (type.IsPrimitive || type.Name == "String" || type.BaseType == typeof(ValueType) || type.Name.Contains("AnonymousType") || type.FullName.Contains("System.Collections.Generic.Dictionary"))
                            {

                            }
                            else
                            {
                                jObject.Add("objectType", type.FullName);
                            }
                        }
                        else if (token is JArray)
                        {
                            jObject = new JObject();
                            jObject.Add("logArg", token);

                            var type = logObject.GetType();

                            if (type.IsArray)
                            {
                                var array = (Array)logObject;

                                if (array.Length > 0)
                                {
                                    var child = array.GetValue(0);

                                    var childtype = child.GetType();

                                    if (childtype.IsPrimitive || childtype.Name == "String" || childtype.BaseType == typeof(ValueType))
                                    {

                                    }
                                    else
                                    {
                                        jObject.Add("objectType", childtype.FullName);
                                    }
                                }
                            }
                            else
                            {
                                var genericArgs = type.GetGenericArguments();

                                if (genericArgs.Any())
                                {
                                    var childtype = genericArgs.First();
                                    if (childtype.IsPrimitive || childtype.Name == "String" || childtype.BaseType == typeof(ValueType))
                                    {

                                    }
                                    else
                                    {
                                        jObject.Add("objectType", childtype.FullName);
                                    }
                                }
                                else
                                {
                                    jObject.Add("objectType", type.FullName);
                                }
                            }

                        }
                        else if (token is JValue)
                        {
                            if (serializeSimpleTypes)
                            {
                                jObject = new JObject();
                                jObject.Add("logArg", token);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lock (_BadTypes)
                {
                    _BadTypes.Add(t.ToString());
                }
                Utils.StackifyAPILogger.Log(ex.ToString());
            }

            string data = null;
            if (properties != null && properties.Any())
            {

                if (jObject == null)
                {
                    jObject = new JObject();
                }

                JObject props = new JObject();
                foreach (var prop in properties)
                {
                    try
                    {
                        if (IsValueType(prop.Value))
                        {
                            props.Add(prop.Key, new JValue(prop.Value));
                        }
                        else
                        {
                            props.Add(prop.Key, JObject.FromObject(prop.Value,serializer));
                        }

                    }
                    catch (Exception ex)
                    {
                        StackifyAPILogger.Log(ex.ToString());
                    }

                }

                jObject.Add("context", props);

            }

            if (jObject != null)
            {
                return JsonConvert.SerializeObject(jObject,
                                                   new JsonSerializerSettings()
                                                       {
                                                           NullValueHandling = NullValueHandling.Ignore
                                                       });
            }

            return null;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Device Detect
        /// </summary>
        /// <param name="data">Data for device detection : HTTP Headers usually</param>
        /// <returns>true on success, false otherwise. Use getReply to inspect results on success.</returns>
        public bool DeviceDetect(Dictionary<string, dynamic> data = null)
        {
            int id = 0;
            if (data == null || !data.Any() || !data.ContainsKey("id"))
            {
                id = Convert.ToInt32(Config["site_id"]);
            }
            else
            {
                id = Convert.ToInt32(data["id"]);
            }

            Dictionary<string, dynamic> requestBody = new Dictionary<string, dynamic>();
            foreach (KeyValuePair<string, dynamic> item in data)
            {
                if (requestBody.ContainsKey(item.Key.ToLower()))
                {
                    requestBody[item.Key.ToLower()] = item.Value;
                }
                else
                {
                    requestBody.Add(item.Key.ToLower(), item.Value);
                }
            }

            string fastKey = "";
            // If caching enabled then check cache
            if (Cacherequests)
            {
                IOrderedEnumerable<dynamic> headersKeys = requestBody.Values.Select(c => c).OrderBy(c => c);
                fastKey = Jss.Serialize(headersKeys).Replace(" ", "");
                Dictionary<string, dynamic> objReply = _cache.Read<Dictionary<string, dynamic>>(fastKey);
                if (objReply.Count > 0)
                {
                    Reply = objReply;
                    SetRawReply();
                    return SetError(0, "OK");
                }
            }

            try
            {
                bool result = false;
                if (UseLocal)
                {
                    result = _device.LocalDetect(requestBody);
                    // Log unknown headers if enabled
                    SetError(_device.GetStatus(), _device.GetMessage());
                }
                else
                {
                    result = Remote(string.Format("/device/detect/{0}", id), requestBody);
                }
                if (Cacherequests)
                {
                    _cache.Write(fastKey, GetReply());
                }
                return result;
            }
            catch (Exception ex)
            {
                SetError(299, "Exception : " + ex.Message + " " + ex.StackTrace);
                return false;
            }
        }
Exemplo n.º 5
0
        void ParseAidrMetatags(List<Hashtable> tweets)
        {
            var hasNominalLabels = tweets.Where(n => !n.ContainsKey(IGNORE) && tweetHasAidrTags(n));
            if (!hasNominalLabels.Any())
                return;

            Dictionary<long, List<AidrLabel>> tweetLabels = new Dictionary<long, List<AidrLabel>>();
            foreach (var item in hasNominalLabels)
            {
                long tweetID = Convert.ToInt64(item["id_str"]);
                Hashtable aidr = (Hashtable)item["aidr"];
                ArrayList nominalLabels = (ArrayList)aidr["nominal_labels"];
                foreach (Hashtable labelData in nominalLabels)
                {
                    AidrLabel label = new AidrLabel();
                    label.AttributeCode = labelData["attribute_code"].ToString();
                    label.AttributeName = labelData["attribute_name"].ToString();
                    label.LabelCode = labelData["label_code"].ToString();
                    label.LabelName = labelData["label_name"].ToString();
                    label.Confidence = Convert.ToDouble(labelData["confidence"], CultureInfo.InvariantCulture);

                    //Don't store null tags or tags with low confidence
                    if (label.LabelCode == "null" || label.Confidence < Settings.TweetParser_MinAidrLabelConficence)
                        continue;

                    if (!tweetLabels.ContainsKey(tweetID))
                        tweetLabels.Add(tweetID, new List<AidrLabel>());
                    tweetLabels[tweetID].Add(label);
                }
            }

            if (!tweetLabels.Any())
                return;

            //Group all tweetLabels into an attribute->label structure
            var attributeDefinitions =
                from item in tweetLabels.Values.SelectMany(n => n)
                group item by item.AttributeCode into attributeGroup
                select new {
                    AttributeCode = attributeGroup.Key,
                    AttributeName = attributeGroup.First().AttributeName,
                    Labels = from label in attributeGroup.ToList()
                            group label by label.LabelCode into labelGroup
                            select new {
                                LabelCode = labelGroup.Key,
                                LabelName = labelGroup.First().LabelName
                            }
                    };

            //Insert attribute definitions
            StringBuilder sbAttr = new StringBuilder();
            sbAttr.Append("insert into AidrAttribute (AttributeCode, AttributeName) values ");
            bool firstLine = true;
            foreach (var attribute in attributeDefinitions)
            {
                if (firstLine)
                    firstLine = false;
                else
                    sbAttr.Append(",");

                sbAttr.Append("('");
                sbAttr.Append(attribute.AttributeCode);
                sbAttr.Append("','");
                sbAttr.Append(attribute.AttributeName);
                sbAttr.Append("')");
            }
            sbAttr.Append(" on duplicate key update AttributeName=values(AttributeName)");
            Helpers.RunSqlStatement(Name, sbAttr.ToString(), false);

            //Get attribute IDs
            //string attributeCodesStr = string.Join("','", attributeDefinitions.Select(n => n.AttributeCode).ToArray());
            Dictionary<string, uint> attributeIDs = new Dictionary<string,uint>();
            Helpers.RunSelect(Name,
                "select AttributeID, AttributeCode from AidrAttribute",
                attributeIDs,
                (values, reader) => attributeIDs.Add(reader.GetString("AttributeCode"), reader.GetUInt32("AttributeID")));

            //Insert label definitions
            var labelDefinitions =
                from attrDef in attributeDefinitions
                from lblDef in attrDef.Labels
                select new
                {
                    AttributeID = attributeIDs[attrDef.AttributeCode],
                    LabelCode = lblDef.LabelCode,
                    LabelName = lblDef.LabelName
                };

            StringBuilder sbLabel = new StringBuilder();
            sbLabel.Append("insert into AidrLabel (AttributeID, LabelCode, LabelName) values ");
            firstLine = true;
            foreach (var label in labelDefinitions)
            {
                if (firstLine)
                    firstLine = false;
                else
                    sbLabel.Append(",");

                sbLabel.Append("(");
                sbLabel.Append(label.AttributeID);
                sbLabel.Append(",'");
                sbLabel.Append(label.LabelCode);
                sbLabel.Append("','");
                sbLabel.Append(label.LabelName);
                sbLabel.Append("')");
            }
            sbLabel.Append(" on duplicate key update LabelName=values(LabelName)");
            Helpers.RunSqlStatement(Name, sbLabel.ToString(), false);

            //Get IDs for labels
            Dictionary<uint, Dictionary<string, uint>> labelIDs = new Dictionary<uint, Dictionary<string, uint>>();
            Helpers.RunSelect(Name,
                "select AttributeID, LabelCode, LabelID from AidrLabel",
                labelIDs,
                (values, reader) =>
                {
                    uint attrId = reader.GetUInt32("AttributeID");
                    string lblCode = reader.GetString("LabelCode");
                    uint lblId = reader.GetUInt32("LabelID");
                    if (!labelIDs.ContainsKey(attrId))
                        labelIDs.Add(attrId, new Dictionary<string,uint>());
                    labelIDs[attrId].Add(lblCode, lblId);
                });

            //Insert tweet tags
            StringBuilder sbTweetTag = new StringBuilder();
            sbTweetTag.Append("insert ignore into TweetAidrAttributeTag (TweetID, LabelID, Confidence) values ");
            firstLine = true;
            foreach (var tweet in tweetLabels)
            {
                foreach (var label in tweet.Value)
                {
                    if (firstLine)
                        firstLine = false;
                    else
                        sbTweetTag.Append(",");

                    sbTweetTag.Append("(");
                    sbTweetTag.Append(tweet.Key);
                    sbTweetTag.Append(",");
                    sbTweetTag.Append(labelIDs[attributeIDs[label.AttributeCode]][label.LabelCode]);
                    sbTweetTag.Append(",");
                    sbTweetTag.Append(label.Confidence.ToString(CultureInfo.InvariantCulture));
                    sbTweetTag.Append(")");
                }
            }
            Helpers.RunSqlStatement(Name, sbTweetTag.ToString(), false);

            Helpers.RunSqlStatement(Name, "update Tweet set ProcessedMetatags=0 where TweetID in ("
                + String.Join(",", tweetLabels.Keys.Select(n => n.ToString()).ToArray()) + ")", false);
        }
Exemplo n.º 6
0
        static void AssignStoryIDToNewClusters(ref long nextStoryID, Dictionary<long, SimpleTweetCluster> clusters, Dictionary<long, SimpleStory> stories)
        {
            if (!clusters.Any())
                return;

            foreach (SimpleTweetCluster cluster in clusters.Values)
            {
                //Get the distribution of similarity scores between this cluster and each of the most active stories
                var similarities = stories.Values
                    .Select(n => new { StoryID = n.StoryID, Similarity = n.WordVector * cluster.WordVector })
                    .OrderByDescending(n => n.Similarity)
                    .ToList();

                //Check if there is a rapid drop somewhere in the similarity distribution
                bool distrHasRapidDrop = false;
                if (similarities.Count > 1)
                {
                    for (int i = 1; i < similarities.Count; i++)
                    {
                        if (similarities[i].Similarity > 0.01 && similarities[i].Similarity < Settings.TweetClusterer_SW_MergeDropScale * similarities[i - 1].Similarity)
                        {
                            distrHasRapidDrop = true;
                            break;
                        }
                        if (similarities[i].Similarity < Settings.TweetClusterer_SW_MergeThresholdWithDrop)
                            break;
                    }
                }

                //Assign a story ID to the cluster
                if (stories.Count > 0
                    && (similarities[0].Similarity > Settings.TweetClusterer_SW_MergeThreshold
                        || similarities[0].Similarity > Settings.TweetClusterer_SW_MergeThresholdWithDrop && distrHasRapidDrop))
                {
                    cluster.StoryID = similarities[0].StoryID;
                }
                else
                {
                    cluster.StoryID = nextStoryID;
                    cluster.isNewStory = true;
                    nextStoryID++;
                }
            }
        }
 protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) {
     IDictionary<string, Exception> errors = new Dictionary<string, Exception>(StringComparer.OrdinalIgnoreCase);
     QueryableDataSourceEditData editData = BuildUpdateObjects(keys, values, oldValues, errors);
     if (errors.Any()) {
         HandleValidationErrors(errors, DataSourceOperation.Update);
     }
     else {
         return UpdateObject(editData.OriginalDataObject, editData.NewDataObject);
     }
     return -1;
 }
Exemplo n.º 8
0
        private void ApplyColorCollection(ColorCollection collection, bool randomOrder)
        {
            if (!collection.Color.Any())
                return;

            bool skipElements = false;
            int index = 0;

            foreach (Element elem in TimelineControl.SelectedElements)
            {
                if (!SupportsColor(elem))
                {
                    skipElements = true;
                    continue;
                }
                var colors = GetSupportedColorsFromCollection(elem, collection.Color);

                var properties = MetadataRepository.GetProperties(elem.EffectNode.Effect).Where(x => (x.PropertyType == typeof(Color) ||
                    x.PropertyType == typeof(ColorGradient) || x.PropertyType == typeof(List<ColorGradient>) || x.PropertyType == typeof(List<GradientLevelPair>)) && x.IsBrowsable);

                Dictionary<Element, Tuple<Object, PropertyDescriptor>> elementValues = new Dictionary<Element, Tuple<object, PropertyDescriptor>>();

                foreach (var propertyData in properties)
                {

                    if (propertyData.PropertyType == typeof (Color))
                    {
                        var color = randomOrder ? GetRandomColorFromCollection(colors) : colors[index++ % colors.Count];
                        elementValues.Add(elem,
                            new Tuple<object, PropertyDescriptor>(propertyData.Descriptor.GetValue(elem.EffectNode.Effect),
                                propertyData.Descriptor));
                        UpdateEffectProperty(propertyData.Descriptor, elem, color);
                    }
                    else
                    {
                        //The rest take a gradient.
                        if (propertyData.PropertyType == typeof(ColorGradient))
                        {
                            var color = randomOrder ? GetRandomColorFromCollection(colors) : colors[index++ % colors.Count];
                            elementValues.Add(elem,
                                new Tuple<object, PropertyDescriptor>(propertyData.Descriptor.GetValue(elem.EffectNode.Effect),
                                    propertyData.Descriptor));
                            UpdateEffectProperty(propertyData.Descriptor, elem, new ColorGradient(color));
                        }
                        else if (propertyData.PropertyType == typeof(List<ColorGradient>))
                        {
                            var gradients = propertyData.Descriptor.GetValue(elem.EffectNode.Effect) as List<ColorGradient>;
                            if (gradients != null)
                            {
                                var newGradients = gradients.ToList();
                                for (int i = 0; i < newGradients.Count; i++)
                                {
                                    newGradients[i] =
                                        new ColorGradient(randomOrder ? GetRandomColorFromCollection(colors) : colors[index++ % colors.Count]);
                                }
                                elementValues.Add(elem,
                                    new Tuple<object, PropertyDescriptor>(gradients,
                                        propertyData.Descriptor));
                                UpdateEffectProperty(propertyData.Descriptor, elem, newGradients);
                            }

                        }
                        else if (propertyData.PropertyType == typeof(List<GradientLevelPair>))
                        {
                            var gradients = propertyData.Descriptor.GetValue(elem.EffectNode.Effect) as List<GradientLevelPair>;
                            if (gradients != null)
                            {
                                var newGradients = gradients.ToList();
                                for (int i = 0; i < newGradients.Count; i++)
                                {
                                    newGradients[i] = new GradientLevelPair(new ColorGradient(randomOrder ? GetRandomColorFromCollection(colors) : colors[index++ % colors.Count]), new Curve(gradients[i].Curve));
                                }
                                elementValues.Add(elem,
                                    new Tuple<object, PropertyDescriptor>(gradients,
                                        propertyData.Descriptor));
                                UpdateEffectProperty(propertyData.Descriptor, elem, newGradients);
                            }

                        }

                    }
                }

                if (elementValues.Any())
                {
                    var undo = new EffectsPropertyModifiedUndoAction(elementValues);
                    AddEffectsModifiedToUndo(undo);
                }
            }

            if (skipElements)
            {
                MessageBoxForm.msgIcon = SystemIcons.Information; //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("One or more effects were selected that do not support colors.\nAll effects that do were updated.",
                                    @"Information", true, false);
                messageBox.ShowDialog();
            }
            SequenceModified();
        }
Exemplo n.º 9
0
        private void ConfigureLayerMenu(ContextSelectedEventArgs e)
        {
            if ((e.ElementsUnderCursor != null && e.ElementsUnderCursor.Any()) || TimelineControl.SelectedElements.Any())
            {
                var layers = Sequence.GetAllLayers();
                if (layers.Count() > 1)
                {
                    ToolStripMenuItem contextMenuToLayer = new ToolStripMenuItem("Layer")
                    {
                        Enabled = true,
                        Image = Resources.layers,
                        ToolTipText = @"Assign effects to a layer"
                    };

                    HashSet<Guid> layersUsed = new HashSet<Guid>();
                    var sequenceLayers = Sequence.GetSequenceLayerManager();
                    if (TimelineControl.SelectedElements.Any())
                    {
                        foreach (var selectedElement in TimelineControl.SelectedElements)
                        {
                            var curentLayer = sequenceLayers.GetLayer(selectedElement.EffectNode);
                            if (layersUsed.Contains(curentLayer.Id) == false)
                            {
                                layersUsed.Add(curentLayer.Id);
                                if (layersUsed.Count == sequenceLayers.Count)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (var elementUnderCursor in e.ElementsUnderCursor)
                        {
                            var curentLayer = sequenceLayers.GetLayer(elementUnderCursor.EffectNode);
                            if (layersUsed.Contains(curentLayer.Id) == false)
                            {
                                layersUsed.Add(curentLayer.Id);
                                if (layersUsed.Count == sequenceLayers.Count)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    Bitmap checkMarkColor;
                    int iconSize = (int)(24 * ScalingTools.GetScaleFactor());
                    if (layersUsed.Count == 1)
                    {
                        checkMarkColor = Tools.GetIcon(Resources.check_mark, iconSize);
                    }
                    else
                    {
                        checkMarkColor = Tools.GetIcon(Resources.check_markMedium, iconSize);
                    }

                    foreach (var layer in layers.Reverse())
                    {
                        var item = new ToolStripMenuItem(layer.LayerName);
                        item.Tag = layer;
                        item.ToolTipText = layer.FilterName;

                        if (layersUsed.Contains(layer.Id))
                        {
                            item.Image = checkMarkColor;
                        }

                        contextMenuToLayer.DropDownItems.Add(item);
                        item.Click += (sender, args) =>
                        {
                            var el = e.ElementsUnderCursor;
                            Dictionary<IEffectNode, ILayer> modifiedNodes = new Dictionary<IEffectNode, ILayer>();
                            var newLayer = (ILayer) item.Tag;
                            //First try to apply to selected elements
                            if (TimelineControl.SelectedElements.Any())
                            {
                                foreach (var selectedElement in TimelineControl.SelectedElements)
                                {
                                    var curentLayer = sequenceLayers.GetLayer(selectedElement.EffectNode);
                                    if (newLayer != curentLayer)
                                    {
                                        modifiedNodes.Add(selectedElement.EffectNode, curentLayer);
                                        sequenceLayers.AssignEffectNodeToLayer(selectedElement.EffectNode, newLayer);
                                    }
                                }
                            }
                            else if (el != null && el.Any())
                            {
                                //if there are no selected elements, then try to apply to the element under the cursor
                                foreach (var selectedElement in el)
                                {
                                    var curentLayer = sequenceLayers.GetLayer(selectedElement.EffectNode);
                                    if (newLayer != curentLayer)
                                    {
                                        modifiedNodes.Add(selectedElement.EffectNode, curentLayer);
                                        sequenceLayers.AssignEffectNodeToLayer(selectedElement.EffectNode, newLayer);
                                    }
                                }
                            }

                            if (modifiedNodes.Any())
                            {
                                var undo = new EffectsLayerChangedUndoAction(this, modifiedNodes);
                                _undoMgr.AddUndoAction(undo);
                                SequenceModified();
                            }
                        };
                    }
                    _contextMenuStrip.Items.Add(contextMenuToLayer);
                }
            }
        }
Exemplo n.º 10
0
 internal static bool AnyVariablesCouldBeAllScope(Dictionary<string, int> variableNames)
 {
     return variableNames.Any<KeyValuePair<string, int>>(keyValuePair => _allScopeVariables.ContainsKey(keyValuePair.Key));
 }
        private void BatchUpdate(string tableName, IEnumerable<JObject> items, List<ColumnDefinition> columns)
        {
            if (columns.Count <= 1)
            {
                return; // For update to work there has to be at least once column besides Id that needs to be updated
            }

            ValidateParameterCount(columns.Count);

            string sqlBase = String.Format("UPDATE {0} SET ", SqlHelpers.FormatTableName(tableName));

            foreach (JObject item in items)
            {
                var sql = new StringBuilder(sqlBase);
                var parameters = new Dictionary<string, object>();

                ColumnDefinition idColumn = columns.FirstOrDefault(c => c.Name.Equals(MobileServiceSystemColumns.Id));
                if (idColumn == null)
                {
                    continue;
                }

                foreach (var column in columns.Where(c => c != idColumn))
                {
                    string paramName = AddParameter(item, parameters, column);

                    sql.AppendFormat("{0} = {1}", SqlHelpers.FormatMember(column.Name), paramName);
                    sql.Append(",");
                }

                if (parameters.Any())
                {
                    sql.Remove(sql.Length - 1, 1); // remove the trailing comma

                }

                sql.AppendFormat(" WHERE {0} = {1}", SqlHelpers.FormatMember(MobileServiceSystemColumns.Id), AddParameter(item, parameters, idColumn));

                this.ExecuteNonQuery(sql.ToString(), parameters);
            }
        }
Exemplo n.º 12
0
        private IEnumerable<DatObject> ParseObjects(IEnumerable<string> lines)
        {
            var objects = new List<DatObject>();
            var elements = new Dictionary<string, string>();

            foreach (string line in lines.Where(line => !string.IsNullOrEmpty(line) && line[0] != '#'))
            {
                // Separator means finish the current object and start assembling a new one
                if (line[0] == '-')
                {
                    if (elements.Any())
                        objects.Add(new DatObject(elements, Pak, this));

                    elements = new Dictionary<string, string>();
                    continue;
                }

                var equalsIndex = line.IndexOf('=');
                if (equalsIndex < 0 || line.Length == equalsIndex + 1)
                    continue;

                var name = line.Substring(0, equalsIndex).TrimStart(' ').TrimEnd(' ').ToLower();
                var value = line.Substring(equalsIndex + 1).TrimStart(' ').TrimEnd(' ').ToLower();

                while (elements.ContainsKey(name))
                    name += "_dup";

                elements.Add(name, value);
            }

            // Flush last object if no trailing separator
            if (elements.Any())
                objects.Add(new DatObject(elements, Pak, this));

            return objects;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates the labels.
        /// </summary>
        /// <param name="dataKeyArray">The data key array.</param>
        /// <returns></returns>
        private void ProcessLabels( DataKeyArray checkinArray )
        {
            // Make sure we can save the attendance and get an attendance code
            if ( RunSaveAttendance )
            {
                var attendanceErrors = new List<string>();
                if ( ProcessActivity( "Save Attendance", out attendanceErrors ) )
                {
                    SaveState();
                }
                else
                {
                    string errorMsg = "<ul><li>" + attendanceErrors.AsDelimited( "</li><li>" ) + "</li></ul>";
                    maAlert.Show( errorMsg, Rock.Web.UI.Controls.ModalAlertType.Warning );
                    return;
                }

                RunSaveAttendance = false;
            }

            var printQueue = new Dictionary<string, StringBuilder>();
            bool printIndividually = GetAttributeValue( "PrintIndividualLabels" ).AsBoolean();
            var designatedLabelGuid = GetAttributeValue( "DesignatedSingleLabel" ).AsGuidOrNull();

            foreach ( var selectedFamily in CurrentCheckInState.CheckIn.Families.Where( p => p.Selected ) )
            {
                List<CheckInLabel> labels = new List<CheckInLabel>();
                List<CheckInPerson> selectedPeople = selectedFamily.People.Where( p => p.Selected ).ToList();
                List<CheckInGroupType> selectedGroupTypes = selectedPeople.SelectMany( gt => gt.GroupTypes )
                    .Where( gt => gt.Selected ).ToList();
                List<CheckInGroup> availableGroups = null;
                List<CheckInLocation> availableLocations = null;
                List<CheckInSchedule> availableSchedules = null;
                List<CheckInSchedule> personSchedules = null;

                foreach ( DataKey dataKey in checkinArray )
                {
                    var personId = Convert.ToInt32( dataKey["PersonId"] );
                    var groupId = Convert.ToInt32( dataKey["GroupId"] );
                    var locationId = Convert.ToInt32( dataKey["LocationId"] );
                    var scheduleId = Convert.ToInt32( dataKey["ScheduleId"] );

                    int groupTypeId = selectedGroupTypes.Where( gt => gt.Groups.Any( g => g.Group.Id == groupId ) )
                        .Select( gt => gt.GroupType.Id ).FirstOrDefault();
                    availableGroups = selectedGroupTypes.SelectMany( gt => gt.Groups ).ToList();
                    availableLocations = availableGroups.SelectMany( l => l.Locations ).ToList();
                    availableSchedules = availableLocations.SelectMany( s => s.Schedules ).ToList();
                    personSchedules = selectedPeople.SelectMany( p => p.PossibleSchedules ).ToList();

                    // Make sure only the current item is selected in the merge object
                    if ( printIndividually || checkinArray.Count == 1 )
                    {
                        // Note: This depends on PreSelected being set properly to undo changes later
                        selectedPeople.ForEach( p => p.Selected = ( p.Person.Id == personId ) );
                        selectedGroupTypes.ForEach( gt => gt.Selected = ( gt.GroupType.Id == groupTypeId ) );
                        availableGroups.ForEach( g => g.Selected = ( g.Group.Id == groupId ) );
                        availableLocations.ForEach( l => l.Selected = ( l.Location.Id == locationId ) );
                        availableSchedules.ForEach( s => s.Selected = ( s.Schedule.Id == scheduleId ) );
                        personSchedules.ForEach( s => s.Selected = ( s.Schedule.Id == scheduleId ) );
                    }

                    // Create labels for however many items are currently selected
                    // #TODO: Rewrite CreateLabels so it would accept a list of ID's
                    var labelErrors = new List<string>();
                    if ( ProcessActivity( "Create Labels", out labelErrors ) )
                    {
                        SaveState();
                    }

                    // mark the person as being checked in
                    var selectedSchedules = availableLocations.Where( l => l.Selected )
                        .SelectMany( s => s.Schedules ).Where( s => s.Selected ).ToList();
                    foreach ( var selectedSchedule in selectedSchedules )
                    {
                        var serviceStart = (DateTime)selectedSchedule.StartTime;
                        selectedSchedule.LastCheckIn = serviceStart.AddMinutes( (double)selectedSchedule.Schedule.CheckInEndOffsetMinutes );
                    }

                    // Add valid grouptype labels, excluding the one-time label (if set)
                    if ( printIndividually )
                    {
                        var selectedPerson = selectedPeople.FirstOrDefault( p => p.Person.Id == personId );
                        if ( selectedPerson != null )
                        {
                            labels.AddRange( selectedPerson.GroupTypes.Where( gt => gt.Labels != null )
                                .SelectMany( gt => gt.Labels )
                                .Where( l => ( !RemoveFromQueue || l.FileGuid != designatedLabelGuid ) )
                            );
                        }

                        RemoveFromQueue = RemoveFromQueue || labels.Any( l => l.FileGuid == designatedLabelGuid );
                    }
                    else
                    {
                        labels.AddRange( selectedGroupTypes.Where( gt => gt.Labels != null )
                            .SelectMany( gt => gt.Labels )
                            .Where( l => ( !RemoveFromQueue || l.FileGuid != designatedLabelGuid ) )
                        );

                        // don't continue processing if printing all info on one label
                        break;
                    }
                }

                // Print client labels
                if ( labels.Any( l => l.PrintFrom == PrintFrom.Client ) )
                {
                    var clientLabels = labels.Where( l => l.PrintFrom == PrintFrom.Client ).ToList();
                    var urlRoot = string.Format( "{0}://{1}", Request.Url.Scheme, Request.Url.Authority );
                    clientLabels.ForEach( l => l.LabelFile = urlRoot + l.LabelFile );
                    AddLabelScript( clientLabels.ToJson() );
                    pnlContent.Update();
                }

                // Print server labels
                if ( labels.Any( l => l.PrintFrom == PrintFrom.Server ) )
                {
                    string delayCut = @"^XB";
                    string endingTag = @"^XZ";
                    var printerIp = string.Empty;
                    var labelContent = new StringBuilder();

                    // make sure labels have a valid ip
                    var lastLabel = labels.Last();
                    foreach ( var label in labels.Where( l => l.PrintFrom == PrintFrom.Server && !string.IsNullOrEmpty( l.PrinterAddress ) ) )
                    {
                        var labelCache = KioskLabel.Read( label.FileGuid );
                        if ( labelCache != null )
                        {
                            if ( printerIp != label.PrinterAddress )
                            {
                                printQueue.AddOrReplace( label.PrinterAddress, labelContent );
                                printerIp = label.PrinterAddress;
                                labelContent = new StringBuilder();
                            }

                            var printContent = labelCache.FileContent;
                            foreach ( var mergeField in label.MergeFields )
                            {
                                if ( !string.IsNullOrWhiteSpace( mergeField.Value ) )
                                {
                                    printContent = Regex.Replace( printContent, string.Format( @"(?<=\^FD){0}(?=\^FS)", mergeField.Key ), ZebraFormatString( mergeField.Value ) );
                                }
                                else
                                {
                                    printContent = Regex.Replace( printContent, string.Format( @"\^FO.*\^FS\s*(?=\^FT.*\^FD{0}\^FS)", mergeField.Key ), string.Empty );
                                    printContent = Regex.Replace( printContent, string.Format( @"\^FD{0}\^FS", mergeField.Key ), "^FD^FS" );
                                }
                            }

                            // send a Delay Cut command at the end to prevent cutting intermediary labels
                            if ( label != lastLabel )
                            {
                                printContent = Regex.Replace( printContent.Trim(), @"\" + endingTag + @"$", delayCut + endingTag );
                            }

                            labelContent.Append( printContent );
                        }
                    }

                    printQueue.AddOrReplace( printerIp, labelContent );

                    if ( printQueue.Any() )
                    {
                        PrintLabels( printQueue );
                        printQueue.Clear();
                    }
                    else
                    {   // give the user feedback when no server labels are configured
                        phPrinterStatus.Controls.Add( new LiteralControl( "No labels were created.  Please verify that the grouptype is configured with labels and cache is reset." ) );
                    }
                }

                if ( printIndividually || checkinArray.Count == 1 )
                {
                    // reset selections to what they were before queue
                    selectedPeople.ForEach( p => p.Selected = p.PreSelected );
                    personSchedules.ForEach( s => s.Selected = s.PreSelected );
                    selectedGroupTypes.ForEach( gt => gt.Selected = gt.PreSelected );
                    availableGroups.ForEach( g => g.Selected = g.PreSelected );
                    availableLocations.ForEach( l => l.Selected = l.PreSelected );
                    availableSchedules.ForEach( s => s.Selected = s.PreSelected );
                }
            }

            // refresh the currently checked in flag
            BindGrid();
        }
Exemplo n.º 14
0
		internal static object GetPrefetchingQueueStatusForDebug(DocumentDatabase database)
		{
			var result = new List<object>();

			foreach (var prefetchingBehavior in database.IndexingExecuter.PrefetchingBehaviors)
			{
				var prefetcherDocs = prefetchingBehavior.DebugGetDocumentsInPrefetchingQueue().ToArray();
				var futureBatches = prefetchingBehavior.DebugGetDocumentsInFutureBatches();

				var compareToCollection = new Dictionary<Etag, int>();

				for (int i = 1; i < prefetcherDocs.Length; i++)
					compareToCollection.Add(prefetcherDocs[i - 1].Etag, prefetcherDocs[i].Etag.CompareTo(prefetcherDocs[i - 1].Etag));

				if (compareToCollection.Any(x => x.Value < 0))
				{
				    result.Add(new
				    {
						AdditionaInfo = prefetchingBehavior.AdditionalInfo,
                        HasCorrectlyOrderedEtags = false,
                        IncorrectlyOrderedEtags = compareToCollection.Where(x => x.Value < 0),
                        EtagsWithKeys = prefetcherDocs.ToDictionary(x => x.Etag, x => x.Key),
						FutureBatches = futureBatches
				    });
				}
				else
				{
                    var prefetcherDocsToTake = Math.Min(5, prefetcherDocs.Count());
                    var etagsWithKeysTail = Enumerable.Range(0, prefetcherDocsToTake).Select(
                        i => prefetcherDocs[prefetcherDocs.Count() - prefetcherDocsToTake + i]).ToDictionary(x => x.Etag, x => x.Key);

                    result.Add(new
                    {
                        AdditionaInfo = prefetchingBehavior.AdditionalInfo,
                        HasCorrectlyOrderedEtags = true,
                        EtagsWithKeysHead = prefetcherDocs.Take(5).ToDictionary(x => x.Etag, x => x.Key),
                        EtagsWithKeysTail = etagsWithKeysTail,
                        EtagsWithKeysCount = prefetcherDocs.Count(),
						FutureBatches = futureBatches
                    });
				}
			}

			return result;
		}
Exemplo n.º 15
0
        public List<TasksItem> GetTasksItems(string k2User, int? page, int? pageSize, out int totalCount, string procInstID = null, string folio = null, DateTime? startDate = null, DateTime? endDate = null, string[] processNames = null, Dictionary<string, string> sorting = null)
        {
            k2User = K2User.ApplySecurityLabel(k2User);
            totalCount = 0;

            Client.WorklistCriteria filter = new Client.WorklistCriteria();
            filter.Platform = "ASP";
            filter.Count = (pageSize == null || pageSize <= 0) ? -1 : pageSize.Value;
            filter.StartIndex = (page == null || page <= 0) ? 0 : (page.Value - 1) * filter.Count;

            filter.AddFilterField(Client.WCField.WorklistItemStatus, Client.WCCompare.Equal, Client.WorklistStatus.Available);
            filter.AddFilterField(Client.WCLogical.Or, Client.WCField.WorklistItemStatus, Client.WCCompare.Equal, Client.WorklistStatus.Open);
            filter.AddFilterField(Client.WCLogical.And, Client.WCField.WorklistItemOwner, "Me", Client.WCCompare.Equal, Client.WCWorklistItemOwner.Me); //This will return all the user’s items
            filter.AddFilterField(Client.WCLogical.Or, Client.WCField.WorklistItemOwner, "Other", Client.WCCompare.Equal, Client.WCWorklistItemOwner.Other); //This will return all the user’s shared items

            if (startDate != null)
                filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessStartDate, Client.WCCompare.GreaterOrEqual, startDate);

            if (endDate != null)
                filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessStartDate, Client.WCCompare.LessOrEqual, endDate);

            if (!string.IsNullOrEmpty(folio))
                filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessFolio, Client.WCCompare.Like, string.Format("%{0}%", folio));

            if (!string.IsNullOrEmpty(procInstID))
                filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessID, Client.WCCompare.Equal, procInstID);

            if (processNames != null && processNames.Any())
            {
                int index = 0;
                foreach (var processName in processNames)
                {
                    index++;
                    if (index == 1)
                        filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessFullName, Client.WCCompare.Equal, processName);
                    else
                        filter.AddFilterField(Client.WCLogical.Or, Client.WCField.ProcessFullName, Client.WCCompare.Equal, processName);
                }

            }

            if (sorting == null || !sorting.Any())
                filter.AddSortField(Client.WCField.EventStartDate, Client.WCSortOrder.Descending);
            else
            {
                foreach (var field in sorting.Keys)
                {
                    filter.AddSortField((Client.WCField)Enum.Parse(typeof(Client.WCField), field), (Client.WCSortOrder)Enum.Parse(typeof(Client.WCSortOrder), sorting[field]));
                }
            }

            var worklit = Runtime.Worklist.OpenWorklist(_k2ConnectionString, k2User, new ArrayList(), filter, false, false, 0, null);
            List<TasksItem> tasks = new List<TasksItem>();
            foreach (Client.WorklistItem item in worklit)
            {
                Actions actions = new Actions();
                foreach (Client.Action act in item.Actions)
                {
                    var action = new ApproveAction();

                    action.Name = act.Name;
                    action.MetaData = act.MetaData;
                    actions.Add(action);
                }
                TasksItem task = new TasksItem()
                {
                    ProcInstID = item.ProcessInstance.ID,
                    ActivityName = item.ActivityInstanceDestination.Name,
                    Destination = K2User.DelApplySecurityLabel(k2User),
                    Folio = item.ProcessInstance.Folio,
                    Originator = item.ProcessInstance.Originator.FQN,
                    //OriginatorDisName = item.ProcessInstance.Originator.DisplayName,
                    SN = item.SerialNumber,
                    StartDate = item.ProcessInstance.StartDate.ToString("yyyy-MM-dd HH:mm"),
                    SharedUser = item.AllocatedUser.Equals(k2User, StringComparison.OrdinalIgnoreCase) ? null : K2User.DelApplySecurityLabel(item.AllocatedUser), //判断是否SharedUser
                    Actions = actions
                };
                tasks.Add(task);
            }
            return tasks;
        }
Exemplo n.º 16
0
        public List<WorklistItem> GetWorklistItems(string k2User, int? page, int? pageSize, out int totalCount, string sn = null, string folio = null, DateTime? startDate = null, DateTime? endDate = null, string[] processNames = null, Dictionary<string, string> sorting = null)
        {
            totalCount = 0;

            Client.WorklistCriteria filter = new Client.WorklistCriteria();
            filter.Platform = "ASP";
            filter.Count = (pageSize == null || pageSize <= 0) ? -1 : pageSize.Value;
            filter.StartIndex = (page == null || page <= 0) ? 0 : (page.Value - 1) * filter.Count;

            filter.AddFilterField(Client.WCField.WorklistItemStatus, Client.WCCompare.Equal, Client.WorklistStatus.Available);
            filter.AddFilterField(Client.WCLogical.Or, Client.WCField.WorklistItemStatus, Client.WCCompare.Equal, Client.WorklistStatus.Open);
            filter.AddFilterField(Client.WCLogical.And, Client.WCField.WorklistItemOwner, "Me", Client.WCCompare.Equal, Client.WCWorklistItemOwner.Me); //This will return all the user’s items
            filter.AddFilterField(Client.WCLogical.Or, Client.WCField.WorklistItemOwner, "Other", Client.WCCompare.Equal, Client.WCWorklistItemOwner.Other); //This will return all the user’s shared items

            if (startDate != null)
                filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessStartDate, Client.WCCompare.GreaterOrEqual, startDate);

            if (endDate != null)
                filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessStartDate, Client.WCCompare.LessOrEqual, endDate);

            if (!string.IsNullOrEmpty(folio))
                filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessFolio, Client.WCCompare.Like, string.Format("%{0}%", folio));

            if (!string.IsNullOrEmpty(sn))
                filter.AddFilterField(Client.WCLogical.And, Client.WCField.SerialNumber, Client.WCCompare.Equal, sn);

            if (processNames != null && processNames.Any())
            {
                int index = 0;
                foreach (var processName in processNames)
                {
                    index++;
                    if (index == 1)
                        filter.AddFilterField(Client.WCLogical.And, Client.WCField.ProcessFullName, Client.WCCompare.Equal, processName);
                    else
                        filter.AddFilterField(Client.WCLogical.Or, Client.WCField.ProcessFullName, Client.WCCompare.Equal, processName);
                }

            }

            if (sorting == null || !sorting.Any())
                filter.AddSortField(Client.WCField.EventStartDate, Client.WCSortOrder.Descending);
            else
            {
                foreach (var field in sorting.Keys)
                {
                    filter.AddSortField((Client.WCField)Enum.Parse(typeof(Client.WCField), field), (Client.WCSortOrder)Enum.Parse(typeof(Client.WCSortOrder), sorting[field]));
                }
            }

            var worklit = Runtime.Worklist.OpenWorklist(_k2ConnectionString, k2User, new ArrayList(), filter, false, false, 0, null);

            totalCount = worklit.TotalCount;
            return this.ToWorklistItems(k2User, worklit, true, false, true);
        }
Exemplo n.º 17
0
        public Dictionary<string, IRelationship> CreateRelationships(object objectGraph, string parentId, IResourceMapping resourceMapping, Context context)
        {
            var relationships = new Dictionary<string, IRelationship>();
            foreach (var linkMapping in resourceMapping.Relationships)
            {
                var relationshipName = linkMapping.RelationshipName;
                var rel = new Relationship();
                var relLinks = new RelationshipLinks();

                relLinks.Self = linkBuilder.RelationshipSelfLink(context, parentId, resourceMapping, linkMapping);
                relLinks.Related = linkBuilder.RelationshipRelatedLink(context, parentId, resourceMapping, linkMapping);

                if (!linkMapping.IsCollection)
                {
                    string relatedId = null;
                    object relatedInstance = null;
                    if (linkMapping.RelatedResource != null)
                    {
                        relatedInstance = linkMapping.RelatedResource(objectGraph);
                        if (relatedInstance != null)
                            relatedId = linkMapping.ResourceMapping.IdGetter(relatedInstance).ToString();
                    }
                    if (linkMapping.RelatedResourceId != null && relatedId == null)
                    {
                        var id = linkMapping.RelatedResourceId(objectGraph);
                        if (id != null)
                            relatedId = id.ToString();
                    }

                    if (linkMapping.InclusionRule != ResourceInclusionRules.ForceOmit)
                    {
                        // Generating resource linkage for to-one relationships
                        if (relatedInstance != null)
                            rel.Data = new SingleResourceIdentifier
                            {
                                Id = relatedId,
                                Type = configuration.GetMapping(relatedInstance.GetType()).ResourceType // This allows polymorphic (subtyped) resources to be fully represented
                            };
                        else if (relatedId == null || linkMapping.InclusionRule == ResourceInclusionRules.ForceInclude)
                            rel.Data = new NullResourceIdentifier(); // two-state null case, see NullResourceIdentifier summary
                    }
                }
                else
                {
                    IEnumerable relatedInstance = null;
                    if (linkMapping.RelatedResource != null)
                        relatedInstance = (IEnumerable)linkMapping.RelatedResource(objectGraph);

                    // Generating resource linkage for to-many relationships
                    if (linkMapping.InclusionRule == ResourceInclusionRules.ForceInclude && relatedInstance == null)
                        rel.Data = new MultipleResourceIdentifiers();
                    if (linkMapping.InclusionRule != ResourceInclusionRules.ForceOmit && relatedInstance != null)
                    {
                        var idGetter = linkMapping.ResourceMapping.IdGetter;
                        var identifiers = relatedInstance
                            .Cast<object>()
                            .Select(o => new SingleResourceIdentifier
                            {
                                Id = idGetter(o).ToString(),
                                Type = configuration.GetMapping(o.GetType()).ResourceType // This allows polymorphic (subtyped) resources to be fully represented
                            });
                        rel.Data = new MultipleResourceIdentifiers(identifiers);
                    }

                    // If data is present, count meta attribute is added for convenience
                    if (rel.Data != null)
                        rel.Meta = new Dictionary<string, string> { { MetaCountAttribute, ((MultipleResourceIdentifiers)rel.Data).Count.ToString() } };
                }

                if (relLinks.Self != null || relLinks.Related != null)
                    rel.Links = relLinks;

                if (rel.Data != null || rel.Links != null)
                    relationships.Add(relationshipName, rel);
            }
            return relationships.Any() ? relationships : null;
        }
        private void BatchInsert(string tableName, IEnumerable<JObject> items, List<ColumnDefinition> columns)
        {
            if (columns.Count == 0) // we need to have some columns to insert the item
            {
                return;
            }

            // Generate the prepared insert statement
            string sqlBase = String.Format(
                "INSERT OR IGNORE INTO {0} ({1}) VALUES ",
                SqlHelpers.FormatTableName(tableName),
                String.Join(", ", columns.Select(c => c.Name).Select(SqlHelpers.FormatMember))
            );

            // Use int division to calculate how many times this record will fit into our parameter quota
            int batchSize = ValidateParameterCount(columns.Count);

            foreach (var batch in items.Split(maxLength: batchSize))
            {
                var sql = new StringBuilder(sqlBase);
                var parameters = new Dictionary<string, object>();

                foreach (JObject item in batch)
                {
                    AppendInsertValuesSql(sql, parameters, columns, item);
                    sql.Append(",");
                }

                if (parameters.Any())
                {
                    sql.Remove(sql.Length - 1, 1); // remove the trailing comma
                    this.ExecuteNonQuery(sql.ToString(), parameters);
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Aligns selected elements, or if none, all elements to the closest mark.
        /// alignMethod = Start to align the start of the elements, End to align the end of the effects and Both to align Start and End of elements.
        /// </summary>
        /// <param name="alignMethod"></param>
        private void AlignEffectsToNearestMarks(string alignMethod)
        {
            if (!TimelineControl.grid.SelectedElements.Any())
            {
                //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form.
                var messageBox = new MessageBoxForm("This action will apply to your entire sequence, are you sure ?",
                    @"Align effects to marks", true, false);
                messageBox.ShowDialog();
                if (messageBox.DialogResult == DialogResult.No) return;
            }

            Dictionary<Element, Tuple<TimeSpan, TimeSpan>> moveElements = new Dictionary<Element, Tuple<TimeSpan, TimeSpan>>();

            foreach (Row row in TimelineControl.Rows)
            {
                List<Element> elements = new List<Element>();

                elements = TimelineControl.SelectedElements.Any() ? row.SelectedElements.ToList() : row.ToList();

                if (!elements.Any()) continue;

                foreach (Element element in elements)
                {
                    var nearestStartMark = element.StartTime;
                    var nearestEndMark = element.EndTime;

                    switch (alignMethod)
                    {
                        case "Start":
                            nearestStartMark = FindNearestMark(element.StartTime);
                            break;
                        case "End":
                            nearestEndMark = FindNearestMark(element.EndTime);
                            break;
                        case "Both":
                            nearestStartMark = FindNearestMark(element.StartTime);
                            nearestEndMark = FindNearestMark(element.EndTime);
                            break;
                    }
                    if (nearestStartMark != TimeSpan.Zero && !moveElements.ContainsKey(element) && nearestEndMark != TimeSpan.Zero && !moveElements.ContainsKey(element))
                    {
                        moveElements.Add(element, new Tuple<TimeSpan, TimeSpan>(nearestStartMark, nearestEndMark));
                    }
                }
            }

            //Make sure we have elements in the list to move.
            if (moveElements.Any()) TimelineControl.grid.MoveResizeElements(moveElements);
        }
Exemplo n.º 20
0
        private IDictionary<string, string> ProcessRunbookParameters(string automationAccountName, string runbookName, IDictionary parameters)
        {
            parameters = parameters ?? new Dictionary<string, string>();
            IEnumerable<KeyValuePair<string, RunbookParameter>> runbookParameters = this.ListRunbookParameters(automationAccountName, runbookName);
            var filteredParameters = new Dictionary<string, string>();

            foreach (var runbookParameter in runbookParameters)
            {
                if (parameters.Contains(runbookParameter.Key))
                {
                    object paramValue = parameters[runbookParameter.Key];
                    try
                    {
                        filteredParameters.Add(runbookParameter.Key, PowerShellJsonConverter.Serialize(paramValue));
                    }
                    catch (JsonSerializationException)
                    {
                        throw new ArgumentException(
                        string.Format(
                            CultureInfo.CurrentCulture, Resources.RunbookParameterCannotBeSerializedToJson, runbookParameter.Key));
                    }
                }
                else if (runbookParameter.Value.IsMandatory)
                {
                    throw new ArgumentException(
                        string.Format(
                            CultureInfo.CurrentCulture, Resources.RunbookParameterValueRequired, runbookParameter.Key));
                }
            }

            if (filteredParameters.Count != parameters.Count)
            {
                throw new ArgumentException(
                    string.Format(CultureInfo.CurrentCulture, Resources.InvalidRunbookParameters));
            }

            var hasJobStartedBy = filteredParameters.Any(filteredParameter => filteredParameter.Key == Constants.JobStartedByParameterName);

            if (!hasJobStartedBy)
            {
                filteredParameters.Add(Constants.JobStartedByParameterName, PowerShellJsonConverter.Serialize(Constants.ClientIdentity));
            }

            return filteredParameters;
        }
Exemplo n.º 21
0
 private void CompleteDrop(Dictionary<Element, Tuple<object, PropertyDescriptor>> elementValues, Element element, string type)
 {
     if (elementValues.Any())
     {
         var undo = new EffectsPropertyModifiedUndoAction(elementValues);
         AddEffectsModifiedToUndo(undo);
         TimelineControl.grid.ClearSelectedElements();
         TimelineControl.SelectElement(element);
         UpdateToolStrip4(
             string.Format("{2} applied to {0} {1} effect(s).", elementValues.Count(), element.EffectNode.Effect.EffectName, type), 30);
     }
 }
Exemplo n.º 22
0
        private void DistributeSelectedEffectsEqually()
        {
            if (!TimelineControl.grid.OkToUseAlignmentHelper(TimelineControl.SelectedElements))
            {
                MessageBox.Show(TimelineControl.grid.alignmentHelperWarning);
                return;
            }

            //Before we do anything lets make sure there is time to work with
            //I don't remember why I put this here, for now its commented out until its verified that its not needed, then it will be removed
            //if (TimelineControl.SelectedElements.First().EndTime == TimelineControl.SelectedElements.Last().EndTime)
            //{
            //	MessageBox.Show("The first and last effect cannot have the same end time.", "Warning", MessageBoxButtons.OK);
            //	return;
            //}
            bool startAtLastElement = false;
            var totalElements = TimelineControl.SelectedElements.Count();
            var startTime = TimelineControl.SelectedElements.First().StartTime;
            var endTime = TimelineControl.SelectedElements.Last().EndTime;
            if (TimelineControl.SelectedElements.First().StartTime > TimelineControl.SelectedElements.Last().StartTime)
            {
                startAtLastElement = true;
                startTime = TimelineControl.SelectedElements.Last().StartTime;
                endTime = TimelineControl.SelectedElements.First().EndTime;
            }
            var totalDuration = endTime - startTime;
            var effectDuration = totalDuration.TotalSeconds/totalElements;
            TimeSpan effectTS = TimeSpan.FromSeconds(effectDuration);
            //var msgString = string.Format("Total Elements: {0}\n Start Time: {1}\n End Time: {2}\n Total Duration: {3}\n Effect Duration: {4}\n TimeSpan Duration: {5}\n Start at last element: {6}", totalElements,startTime,endTime,totalDuration,effectDuration, effectTS.TotalSeconds, startAtLastElement);
            //MessageBox.Show(msgString);
            //Sanity Check - Keep effects from becoming less than minimum.
            if (effectDuration < .001)
            {
                MessageBox.Show(
                    string.Format(
                        "Unable to complete request. The resulting duration would fall below 1 millisecond.\nCalculated duration: {0}",
                        effectDuration), "Warning", MessageBoxButtons.OK);
                return;
            }

            var elementsToDistribute = new Dictionary<Element, Tuple<TimeSpan, TimeSpan>>();
            if (!startAtLastElement)
            {
                //Lets move the first one
                elementsToDistribute.Add(TimelineControl.SelectedElements.ElementAt(0),
                            new Tuple<TimeSpan, TimeSpan>(startTime, startTime + effectTS));
                for (int i = 1; i <= totalElements - 1; i++)
                {
                    var thisStartTime = elementsToDistribute.Last().Value.Item2;
                    elementsToDistribute.Add(TimelineControl.SelectedElements.ElementAt(i), new Tuple<TimeSpan, TimeSpan>(thisStartTime, thisStartTime + effectTS));
                }
            }
            else
            {
                //Lets move the first(last) one
                elementsToDistribute.Add(TimelineControl.SelectedElements.Last(), new Tuple<TimeSpan, TimeSpan>(startTime, startTime + effectTS));
                for (int i = totalElements - 2; i >= 0; i--)
                {
                    var thisStartTime = elementsToDistribute.Last().Value.Item2;
                    elementsToDistribute.Add(TimelineControl.SelectedElements.ElementAt(i), new Tuple<TimeSpan, TimeSpan>(thisStartTime, thisStartTime + effectTS));
                }
            }

            if (elementsToDistribute.Any())
            {
                TimelineControl.grid.MoveResizeElements(elementsToDistribute, ElementMoveType.Distribute);
            }
        }
Exemplo n.º 23
0
		public ActorInfo GetInfoByCommonName(Dictionary<string, HashSet<string>> names, string commonName, Player owner)
		{
			if (!names.Any() || !names.ContainsKey(commonName))
				throw new InvalidOperationException("Can't find {0} in the HackyAI UnitsCommonNames definition.".F(commonName));

			return Map.Rules.Actors.Where(k => names[commonName].Contains(k.Key)).Random(Random).Value;
		}
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            {
                C[] tableC = new C[10];
                Array.ForEach(tableC, c => { c = new C(); });

                Console.WriteLine("Objects Created ");
                Console.WriteLine("Press enter to Destroy it");
                Console.ReadLine();
                //Array.ForEach(tableC, c => { c = null; });
                tableC = null;

                Console.WriteLine("Call GC.Collect");
                GC.Collect();
            }
            
            //Test codes
            int spaceX = 0, spaceY = 0;
            Dictionary<int, int> mts = new Dictionary<int, int>();
            //mts.Any(k => { return k.Key == iTest && Math.Abs(k.Value - iTest) == 1; });
            bool isApproach = mts.Any(
                p => 
                { 
                    bool isApproachNow = ((p.Key == spaceX));
                    if (isApproachNow == true)
                    {
                        var nextL = mts.FirstOrDefault(p_ => { return (spaceY - p_.Value) <= 1; });

                        if (nextL.Equals(default(KeyValuePair<int, int>)) == true)
                        {
                            return true;
                        }
                        else 
                        {
                            return nextL.Key == spaceX;
                        }
                    }
                    else
                    {
                        return false;
                    }
                });

            //Any routines for call Object destructors.
            Console.Read();
            //Console.ReadLine();


            int n = int.Parse(Console.ReadLine()); // the number of temperatures to analyse
            string temps = Console.ReadLine(); // the n temperatures expressed as integers ranging from -273 to 5526

            // Write an action using Console.WriteLine()
            // To debug: Console.Error.WriteLine("Debug messages...");
            string[] tempsStr = temps.Split(' ');
            int[] tempsNum = new int[tempsStr.Count()];
            string.IsNullOrEmpty(temps);
            

            int tempNearst = tempsNum[0];
            foreach (int temp in tempsNum)
            {
                int tnAbs = Math.Abs(tempNearst), tAbs = Math.Abs(temp);
                if (tnAbs == tAbs)
                {
                    tempNearst = (temp > 0) ? temp : tempNearst;
                }
                else if (tnAbs > tAbs)
                {
                    tempNearst = temp;
                }
            }



            //string outputDebug = "";
            //for (int i = 0; i < 10; ++i)
            //{
            //    outputDebug = outputDebug + "\nNumber:" + i;
            //}

            //System.Diagnostics.Trace.WriteLine(outputDebug);
        }
Exemplo n.º 25
0
        private void DistributeSelectedEffects()
        {
            if (!TimelineControl.grid.OkToUseAlignmentHelper(TimelineControl.SelectedElements))
            {
                MessageBox.Show(TimelineControl.grid.alignmentHelperWarning);
                return;
            }

            var startTime = TimelineControl.SelectedElements.First().StartTime;
            var endTime = TimelineControl.SelectedElements.Last().EndTime;
            if (startTime > endTime)
            {
                startTime = TimelineControl.SelectedElements.Last().StartTime;
                endTime = TimelineControl.SelectedElements.First().EndTime;
            }
            var dDialog = new EffectDistributionDialog();
            var elementCount = TimelineControl.SelectedElements.Count();

            dDialog.ElementCount = elementCount.ToString();
            dDialog.StartTime = startTime;
            dDialog.EndTime = endTime;
            dDialog.RadioEqualDuration = true;
            dDialog.RadioStairStep = true;
            dDialog.StartWithFirst = true;
            dDialog.ShowDialog();
            if (dDialog.DialogResult == DialogResult.OK)
            {
                startTime = dDialog.StartTime;
                endTime = dDialog.EndTime;
                TimeSpan duration = endTime - startTime;
                double offset = duration.TotalSeconds/elementCount;

                var elementsToDistribute = new Dictionary<Element, Tuple<TimeSpan, TimeSpan>>();
                if (dDialog.StartWithFirst)
                {
                    //We start with the first effect
                    for (int i = 0; i <= elementCount - 1; i++)
                    {
                        double thisStartTime = startTime.TotalSeconds;
                        double thisEndTime = thisStartTime + offset;
                        //Generic placement of starttime eq to prev end time
                        if (i > 0)
                            thisStartTime = elementsToDistribute.Last().Value.Item2.TotalSeconds;
                        //Determine Start time
                        if (i > 0 && dDialog.RadioEffectPlacementOverlap)
                            thisStartTime = thisStartTime - Convert.ToDouble(dDialog.EffectPlacementOverlap.TotalSeconds);
                        if (i > 0 && dDialog.RadioPlacementSpacedDuration)
                            thisStartTime = thisStartTime + Convert.ToDouble(dDialog.SpacedPlacementDuration.TotalSeconds);
                        if (dDialog.RadioDoNotChangeDuration && !dDialog.RadioEffectPlacementOverlap &&
                            !dDialog.RadioPlacementSpacedDuration)
                            thisStartTime = startTime.TotalSeconds + (offset*i);
                        //Determine End time
                        if (dDialog.RadioEqualDuration)
                            thisEndTime = thisStartTime + offset;
                        if (dDialog.RadioDoNotChangeDuration)
                            thisEndTime = thisStartTime + TimelineControl.SelectedElements.ElementAt(i).Duration.TotalSeconds;
                        if (dDialog.RadioSpecifiedDuration)
                            thisEndTime = thisStartTime + Convert.ToDouble(dDialog.SpecifiedEffectDuration.TotalSeconds);
                        elementsToDistribute.Add(TimelineControl.SelectedElements.ElementAt(i),
                            new Tuple<TimeSpan, TimeSpan>(TimeSpan.FromSeconds(thisStartTime), TimeSpan.FromSeconds(thisEndTime)));
                    }
                }
                if (dDialog.StartWithLast)
                {
                    //We start with the last effect
                    int placeCount = 0;
                    for (int i = elementCount - 1; i >= 0; i--)
                    {
                        var thisStartTime = startTime.TotalSeconds;
                        var thisEndTime = thisStartTime + offset;
                        //Generic placement of starttime eq to prev end time
                        if (i < elementCount - 1)
                            thisStartTime = elementsToDistribute.Last().Value.Item2.TotalSeconds;
                        //Determine Start time
                        if (i < elementCount - 1 && dDialog.RadioEffectPlacementOverlap)
                            thisStartTime = thisStartTime - Convert.ToDouble(dDialog.EffectPlacementOverlap.TotalSeconds);
                        if (i < elementCount - 1 && dDialog.RadioPlacementSpacedDuration)
                            thisStartTime = thisStartTime + Convert.ToDouble(dDialog.SpacedPlacementDuration.TotalSeconds);
                        if (dDialog.RadioDoNotChangeDuration && !dDialog.RadioEffectPlacementOverlap &&
                            !dDialog.RadioPlacementSpacedDuration)
                            thisStartTime = startTime.TotalSeconds + (offset*placeCount);
                        //Determine End time
                        if (dDialog.RadioEqualDuration)
                            thisEndTime = thisStartTime + offset;
                        if (dDialog.RadioDoNotChangeDuration)
                            thisEndTime = thisStartTime + TimelineControl.SelectedElements.ElementAt(i).Duration.TotalSeconds;
                        if (dDialog.RadioSpecifiedDuration)
                            thisEndTime = thisStartTime + Convert.ToDouble(dDialog.SpecifiedEffectDuration.TotalSeconds);
                        elementsToDistribute.Add(TimelineControl.SelectedElements.ElementAt(i),
                            new Tuple<TimeSpan, TimeSpan>(TimeSpan.FromSeconds(thisStartTime), TimeSpan.FromSeconds(thisEndTime)));
                        placeCount++;
                    }
                }
                if (elementsToDistribute.Any())
                {
                    TimelineControl.grid.MoveResizeElements(elementsToDistribute, ElementMoveType.Distribute);
                }
            }
        }
        /// <summary>
        /// If paths is referenced in the MATCH clause, checks the SELECT elements to decide whether the 
        /// paths informaion is needed to be displayed. If PathAlias.* occurs in the SELECT elements,
        /// sets the corresponding bool value in MatchPath, and replaces this element with 
        /// an scalar function to display readable path information
        /// </summary>
        /// <param name="query">Select query</param>
        /// <param name="pathDictionary">A collection of path alias and match path instance</param>
        private void TransformPathInfoDisplaySelectElement(WSelectQueryBlock query,
            Dictionary<string, MatchPath> pathDictionary)
        {
            if (pathDictionary!=null && pathDictionary.Any())
            {
                List<WSelectElement> newSelectElements = new List<WSelectElement>();
                foreach (var selectElement in query.SelectElements)
                {
                    var starElement = selectElement as WSelectStarExpression;
                    if (starElement != null && starElement.Qulifier != null)
                    {
                        var colName = starElement.Qulifier.Identifiers[starElement.Qulifier.Count - 1].Value;
                        MatchPath path;
                        if (pathDictionary.TryGetValue(colName, out path))
                        {
                            path.ReferencePathInfo = true;
                            string schema = path.BindNodeTableObjName.SchemaIdentifier.Value;
                            string tableName = path.BindNodeTableObjName.BaseIdentifier.Value;
                            string pathName = path.EdgeColumn.MultiPartIdentifier.Identifiers.Last().Value;
                            var parameters = new List<WScalarExpression>
                            {
                                new WColumnReferenceExpression
                                {
                                    MultiPartIdentifier =
                                        new WMultiPartIdentifier(new Identifier() {Value = path.EdgeAlias},
                                            new Identifier() {Value = "PathMessage"})
                                },
                            };
                            if (
                                _graphMetaData.NodeViewMapping.ContainsKey(
                                    WNamedTableReference.SchemaNameToTuple(path.SinkNode.NodeTableObjectName)))
                            {
                                parameters.Add(new WColumnReferenceExpression
                                {
                                    MultiPartIdentifier =
                                        new WMultiPartIdentifier(new Identifier() { Value = path.SinkNode.RefAlias },
                                            new Identifier() { Value = "_NodeType" })
                                });
                                parameters.Add(new WColumnReferenceExpression
                                {
                                    MultiPartIdentifier =
                                        new WMultiPartIdentifier(new Identifier() { Value = path.SinkNode.RefAlias },
                                            new Identifier() { Value = "_NodeId" })
                                });
                            }
                            else
                            {
                                parameters.Add(new WValueExpression
                                {
                                    Value = path.SinkNode.NodeTableObjectName.BaseIdentifier.Value,
                                    SingleQuoted = true
                                });
                                string sinkNodeIdName =
                                    _graphMetaData.ColumnsOfNodeTables[
                                        WNamedTableReference.SchemaNameToTuple(path.SinkNode.NodeTableObjectName)]
                                        .FirstOrDefault(e => e.Value.Role == WNodeTableColumnRole.NodeId).Key;
                                if (string.IsNullOrEmpty(sinkNodeIdName))
                                    parameters.Add(new WValueExpression { Value = "null" });
                                else
                                {
                                    parameters.Add(new WColumnReferenceExpression
                                    {
                                        MultiPartIdentifier =
                                            new WMultiPartIdentifier(new Identifier() { Value = path.SinkNode.RefAlias },
                                                new Identifier() { Value = sinkNodeIdName })
                                    });
                                }

                            }
                            newSelectElements.Add(new WSelectScalarExpression
                            {
                                ColumnName = path.EdgeAlias + "_PathInfo",
                                SelectExpr = new WFunctionCall
                                {
                                    CallTarget = new WMultiPartIdentifierCallTarget
                                    {
                                        Identifiers = new WMultiPartIdentifier(new Identifier { Value = "dbo" })
                                    },
                                    FunctionName = new Identifier { Value = string.Format("{0}_{1}_{2}_PathMessageDecoder", schema, tableName, pathName) },
                                    Parameters = parameters
                                }
                            });
                            continue;
                        }
                    }
                    newSelectElements.Add(selectElement);

                }
                query.SelectElements = newSelectElements;
            }
        }
 protected override int ExecuteInsert(IDictionary values) {
     IDictionary<string, Exception> errors = new Dictionary<string, Exception>(StringComparer.OrdinalIgnoreCase);
     QueryableDataSourceEditData editData = BuildInsertObject(values, errors);
     if (errors.Any()) {
         HandleValidationErrors(errors, DataSourceOperation.Insert);
     }
     else {
         return InsertObject(editData.NewDataObject);
     }
     return -1;
 }
        public void SetDelNodes(Maid maid, Dictionary<string, bool> dDelNodes, bool bApply) 
        {
            if (!dDelNodes.Any()) return;

            foreach (TBodySkin slot in maid.body0.goSlot) {
                slot.boVisible = true;
                foreach (KeyValuePair<string, bool> entry in dDelNodes) {
                    if (slot.m_dicDelNodeBody.ContainsKey(entry.Key)) {
                        slot.m_dicDelNodeBody[entry.Key] = entry.Value;
                    }
                }
            }
            if (bApply) FixFlag();
        }
Exemplo n.º 29
0
        /// <summary>
        /// Liquidizes the child properties of an object for displaying debug information about fields available for lava templates
        /// </summary>
        /// <param name="myObject">an object.</param>
        /// <param name="levelsDeep">The levels deep.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="entityHistory">The entity history.</param>
        /// <param name="parentElement">The parent element.</param>
        /// <returns></returns>
        private static object LiquidizeChildren( this object myObject, int levelsDeep = 0, RockContext rockContext = null, Dictionary<int, List<int>> entityHistory = null, string parentElement = "" )
        {
            // Add protection for stack-overflow if property attributes are not set correctly resulting in child/parent objects being evaluated in loop
            levelsDeep++;
            if ( levelsDeep > 6)
            {
                return string.Empty;
            }

            // If the object is liquidable, get the object return by its ToLiquid() method.
            if ( myObject is DotLiquid.ILiquidizable )
            {
                myObject = ( (DotLiquid.ILiquidizable)myObject ).ToLiquid();
            }

            // If the object is null, return an empty string
            if ( myObject == null )
            {
                return string.Empty;
            }

            // If the object is a string, return its value converted to HTML and truncated
            if ( myObject is string )
            {
                return myObject.ToString().Truncate( 50 ).EncodeHtml();
            }

            // If the object is a guid, return its string representation
            if ( myObject is Guid )
            {
                return myObject.ToString();
            }

            // Get the object's type ( checking for a proxy object )
            Type entityType = myObject.GetType();
            if ( entityType.IsDynamicProxyType() )
            {
                entityType = entityType.BaseType;
            }

            // If this is an IEntity, check to see if it's already been liquidized in prev heirarchy. If so, just return string indicating "--See Previous Entry--"
            if ( myObject is IEntity )
            {
                var entity = myObject as IEntity;
                var entityTypeCache = EntityTypeCache.Read( entityType, false, rockContext );
                if ( entity != null && entityTypeCache != null )
                {
                    if ( entityHistory == null )
                    {
                        entityHistory = new Dictionary<int, List<int>>();
                    }
                    entityHistory.AddOrIgnore( entityTypeCache.Id, new List<int>() );
                    if ( entityHistory[entityTypeCache.Id].Contains( entity.Id ) )
                    {
                        return "--See Previous Entry--";
                    }
                    else
                    {
                        entityHistory[entityTypeCache.Id].Add( entity.Id );
                    }
                }
            }

            // If the object is a Liquid Drop object, return a list of all of the object's properties
            if ( myObject is Drop )
            {
                var result = new Dictionary<string, object>();

                foreach ( var propInfo in entityType.GetProperties(
                          BindingFlags.Public |
                          BindingFlags.Instance |
                          BindingFlags.DeclaredOnly ) )
                {
                    if ( propInfo != null )
                    {
                        try
                        {
                            result.Add( propInfo.Name, propInfo.GetValue( myObject, null ).LiquidizeChildren( levelsDeep, rockContext, entityHistory ) );
                        }
                        catch ( Exception ex )
                        {
                            result.Add( propInfo.Name, ex.ToString() );
                        }
                    }
                }

                return result;
            }

            // If the object has the [LiquidType] attribute, enumerate the allowed properties and return a list of those properties
            if ( entityType.GetCustomAttributes( typeof( LiquidTypeAttribute ), false ).Any() )
            {
                var result = new Dictionary<string, object>();

                var attr = (LiquidTypeAttribute)entityType.GetCustomAttributes( typeof( LiquidTypeAttribute ), false ).First();
                foreach ( string propName in attr.AllowedMembers )
                {
                    var propInfo = entityType.GetProperty( propName );
                    {
                        if ( propInfo != null )
                        {
                            try
                            {
                                result.Add( propInfo.Name, propInfo.GetValue( myObject, null ).LiquidizeChildren( levelsDeep, rockContext, entityHistory, parentElement + "." + propName ) );
                            }
                            catch ( Exception ex )
                            {
                                result.Add( propInfo.Name, ex.ToString() );
                            }
                        }
                    }
                }

                return result;
            }

            // If the object is a Rock Liquidizable object, call the object's AvailableKeys method to determine the properties available.
            if ( myObject is Lava.ILiquidizable )
            {
                var liquidObject = (Lava.ILiquidizable)myObject;

                var result = new Dictionary<string, object>();

                foreach ( var key in liquidObject.AvailableKeys )
                {
                    // Ignore the person property of the person's primary alias (prevent unnecessary recursion)
                    if ( key == "Person" && parentElement.Contains( ".PrimaryAlias" ) )
                    {
                        result.AddOrIgnore( key, string.Empty );
                    }
                    else
                    {
                        try
                        {
                            object propValue = liquidObject[key];
                            if ( propValue != null )
                            {
                                result.Add( key, propValue.LiquidizeChildren( levelsDeep, rockContext, entityHistory, parentElement + "." + key ) );
                            }
                            else
                            {
                                result.AddOrIgnore( key, string.Empty );
                            }
                        }
                        catch ( Exception ex )
                        {
                            result.AddOrIgnore( key, ex.ToString() );
                        }
                    }
                }

                // Add the attributes if this object has attributes
                if ( liquidObject is Rock.Attribute.IHasAttributes )
                {
                    var objWithAttrs = (Rock.Attribute.IHasAttributes)liquidObject;
                    if ( objWithAttrs.Attributes == null )
                    {
                        rockContext = rockContext ?? new RockContext();
                        objWithAttrs.LoadAttributes( rockContext );
                    }

                    var objAttrs = new Dictionary<string, object>();
                    foreach ( var objAttr in objWithAttrs.Attributes )
                    {
                        var attributeCache = objAttr.Value;
                        string value = attributeCache.FieldType.Field.FormatValue( null, objWithAttrs.GetAttributeValue( attributeCache.Key ), attributeCache.QualifierValues, false );
                        objAttrs.Add( attributeCache.Key, value.Truncate( 50 ).EncodeHtml() );
                    }

                    if ( objAttrs.Any() )
                    {
                        result.Add( string.Format( "Attributes <p class='attributes'>Below is a list of attributes that can be retrieved using <code>{{{{ {0} | Attribute:'[AttributeKey]' }}}}</code>.</p>", parentElement ), objAttrs );
                    }
                }

                return result;
            }

            if ( myObject is IDictionary<string, object> )
            {
                var result = new Dictionary<string, object>();

                foreach ( var keyValue in ( (IDictionary<string, object>)myObject ) )
                {
                    try
                    {
                        result.Add( keyValue.Key, keyValue.Value.LiquidizeChildren( levelsDeep, rockContext, entityHistory, keyValue.Key ) );
                    }
                    catch ( Exception ex )
                    {
                        result.Add( keyValue.Key, ex.ToString() );
                    }
                }

                return result;
            }

            if ( myObject is Newtonsoft.Json.Linq.JObject )
            {
                var result = new Dictionary<string, object>();
                var jObject = myObject as Newtonsoft.Json.Linq.JObject;

                foreach ( var keyValue in jObject )
                {
                    try
                    {
                        result.Add( keyValue.Key, keyValue.Value.LiquidizeChildren( levelsDeep, rockContext, entityHistory, keyValue.Key ) );
                    }
                    catch ( Exception ex )
                    {
                        result.Add( keyValue.Key, ex.ToString() );
                    }
                }

                return result;
            }

            if ( myObject is Newtonsoft.Json.Linq.JValue )
            {
                var jValue = ( myObject as Newtonsoft.Json.Linq.JValue );
                if ( jValue != null && jValue.Value != null )
                {
                    return jValue.Value.ToString();
                }
                else
                {
                    return string.Empty;
                }
            }

            if ( myObject is IEnumerable )
            {
                var result = new List<object>();

                // Only show first two items in an enumerable list
                int iEnumCount = 1;
                foreach ( var value in ( (IEnumerable)myObject ) )
                {
                    if ( iEnumCount > 2 )
                    {
                        result.Add( "..." );
                        break;
                    }
                    iEnumCount++;
                    try
                    {
                        result.Add( value.LiquidizeChildren( levelsDeep, rockContext, entityHistory, parentElement ) );
                    }
                    catch { }

                }

                return result;
            }

            return myObject.ToStringSafe();
        }
Exemplo n.º 30
0
        private static int VerifyForwardedTypes(
            Dictionary<INamedTypeSymbol, INamedTypeSymbol> equivalentTypesWithDifferingAssemblies,
            Compilation compilation,
            HashSet<INamedTypeSymbol> verifiedKeys,
            bool isSearchSymbolCompilation)
        {
            Contract.ThrowIfNull(compilation);
            Contract.ThrowIfNull(equivalentTypesWithDifferingAssemblies);
            Contract.ThrowIfTrue(!equivalentTypesWithDifferingAssemblies.Any());

            // Must contain equivalents named types residing in different assemblies.
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => !SymbolEquivalenceComparer.Instance.Equals(kvp.Key.ContainingAssembly, kvp.Value.ContainingAssembly)));

            // Must contain non-nested named types.
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Key.ContainingType == null));
            Contract.ThrowIfFalse(equivalentTypesWithDifferingAssemblies.All(kvp => kvp.Value.ContainingType == null));

            var referencedAssemblies = new MultiDictionary<string, IAssemblySymbol>();
            foreach (var assembly in compilation.GetReferencedAssemblySymbols())
            {
                referencedAssemblies.Add(assembly.Name, assembly);
            }

            int verifiedCount = 0;
            foreach (var kvp in equivalentTypesWithDifferingAssemblies)
            {
                if (!verifiedKeys.Contains(kvp.Key))
                {
                    INamedTypeSymbol originalType, expectedForwardedType;
                    if (isSearchSymbolCompilation)
                    {
                        originalType = kvp.Value.OriginalDefinition;
                        expectedForwardedType = kvp.Key.OriginalDefinition;
                    }
                    else
                    {
                        originalType = kvp.Key.OriginalDefinition;
                        expectedForwardedType = kvp.Value.OriginalDefinition;
                    }

                    foreach (var referencedAssembly in referencedAssemblies[originalType.ContainingAssembly.Name])
                    {
                        var fullyQualifiedTypeName = originalType.MetadataName;
                        if (originalType.ContainingNamespace != null)
                        {
                            fullyQualifiedTypeName = originalType.ContainingNamespace.ToDisplayString(SymbolDisplayFormats.SignatureFormat) +
                                "." + fullyQualifiedTypeName;
                        }

                        // Resolve forwarded type and verify that the types from different assembly are indeed equivalent.
                        var forwardedType = referencedAssembly.ResolveForwardedType(fullyQualifiedTypeName);
                        if (forwardedType == expectedForwardedType)
                        {
                            verifiedKeys.Add(kvp.Key);
                            verifiedCount++;
                        }
                    }
                }
            }

            return verifiedCount;
        }