Exemplo n.º 1
0
Arquivo: Tags.cs Projeto: yysun/Rabbit
    public static dynamic pages_page_detail_aside(dynamic data)
    {
        data.Add("~/Views/Tags/_Page_List_Related.cshtml");
        data.Add("~/Views/Tags/_Tag_Cloud.cshtml");

        return data;
    }
        /// <summary>
        /// Given an existing command and a set of parameters, add the entire set of parameters to the command in the format needed to send the
        /// command to the device or to store it in the command history. The parameters must be either a JArray of JObjects, or a Dictionary with
        /// string keys and object values.
        /// </summary>
        /// <param name="command"></param>
        /// <param name="parameters"></param>
        public static void AddParameterCollectionToCommandHistoryItem(dynamic command, dynamic parameters)
        {
            if (parameters == null)
            {
                return;
            }

            if (parameters.GetType() == typeof(Dictionary<string, object>))
            {
                JObject newParam = new JObject();
                //We have a strongly-typed Collection
                foreach (string key in ((Dictionary<string, object>)parameters).Keys)
                {
                    newParam.Add(key, new JValue(((Dictionary<string, object>)parameters)[key]));
                }
                command.Add(DeviceCommandConstants.PARAMETERS, newParam);
            }
            else if (parameters.GetType() == typeof(JArray))
            {
                //We have JSON
                command.Parameters = parameters;
            }
            else
            {
                throw new ArgumentException("The parameters argument must be either a Dictionary with string keys or a JArray");
            }
        }
Exemplo n.º 3
0
 public static void AddProperty(dynamic props, string propName, string value)
 {
     if (GetProperty(props, propName) != null)
     {
         props[propName].Delete();
     }
     props.Add(propName, false, MsoDocProperties.msoPropertyTypeString, value);
 }
Exemplo n.º 4
0
        /// <summary>
        /// Populates the local menu shapes.
        /// </summary>
        /// <param name="shapeFactory">The shape factory.</param>
        /// <param name="parentShape">The menu parent shape.</param>
        /// <param name="menu">The menu shape.</param>
        /// <param name="menuItems">The current level to populate.</param>
        public static void PopulateLocalMenu(dynamic shapeFactory, dynamic parentShape, dynamic menu, IEnumerable<MenuItem> menuItems) {
            foreach (MenuItem menuItem in menuItems) {
                dynamic menuItemShape = BuildLocalMenuItemShape(shapeFactory, parentShape, menu, menuItem);

                if (menuItem.Items != null && menuItem.Items.Any()) {
                    PopulateLocalMenu(shapeFactory, menuItemShape, menu, menuItem.Items);
                }

                parentShape.Add(menuItemShape, menuItem.Position);
            }
        }
Exemplo n.º 5
0
 private void ChangeValue(dynamic calculator, Operations operation)
 {
     dynamic addvalue = null;
     if (CurrentVal.Text != "Write your Value:")
     {
         if (state.CalcEnum == CalcEnum.IntCalc)
         {
             addvalue = new Real<int>(int.Parse(CurrentVal.Text));
         }
         if (state.CalcEnum == CalcEnum.FloatCalc)
         {
             addvalue = new Real<double>(double.Parse(CurrentVal.Text));
         }
         if (state.CalcEnum == CalcEnum.ComCalc)
         {
             addvalue = new Complecs(CurrentVal.Text);
         }
         switch (operation)
         {
             case Operations.Add:
                 calculator.Add(addvalue);
                 break;
             case Operations.Remove:
                 calculator.Remove(addvalue);
                 break;
             case Operations.Divide:
                 calculator.Divide(addvalue);
                 break;
             case Operations.Multiply:
                 calculator.Multiply(addvalue);
                 break;
             case Operations.Clear:
                 calculator.Clear(addvalue);
                 break;
             case Operations.Sqrt:
                 try
                 {
                     calculator.Sqrt(addvalue);
                 }
                 catch (Exception)
                 {
                     MessageBox.Show("Eror: Divide at 0");
                 }
                 break;
             case Operations.Modul:
                 calculator.Modul(addvalue);
                 break;
         }
     }
     else
     {
         MessageBox.Show("Write Value!!!!");
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Will append an element to the given list
        /// </summary>
        public override void Execute()
        {
            dynamic val = GetInputValue("array");

            System.Type valType = val.GetType();

            Input input = GetInput("element");

            System.Type copyType = null;

            if (valType.GenericTypeArguments.Length > 0)
            {
                copyType = valType.GenericTypeArguments[0];
            }

            dynamic item = input.Definition.Type.GetDeepCopyOf(input.Value, copyType);

            val?.Add(item);
            SetOutputValue("count", val?.Count);
        }
Exemplo n.º 7
0
 private static void MergeItems(INamedEnumerable<object> args, dynamic shape) {
     foreach (var arg in args) {
         // look for string first, because the "string" type is also an IEnumerable of char
         if (arg is string) {
             shape.Add(arg as string);
         }
         else if (arg is IEnumerable) {
             foreach (var item in arg as IEnumerable) {
                 shape.Add(item);
             }
         }
         else {
             shape.Add(System.Convert.ToString(arg));
         }
     }
 }
Exemplo n.º 8
0
        private dynamic makeRequest(String page, dynamic data = null, WebHeaderCollection headers = null)
        {
            string url = dict[page.ToUpper()];

            if (headers == null)
                headers = new WebHeaderCollection();

            dynamic result;

            WebResponse response = null;
            StreamReader reader = null;
            String dataString = "";

            if (page.ToUpper() != "LOGIN")
            {
                url += "?auth=" + authToken;
                result = "";
            }
            else
            {
                result = new List<string>();
            }

            try
            {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "sharpVoice / 0.1";
                if (data != null)
                {
                    if (data is Dictionary<string, string>)
                    {
                        //Dictionary<string, string> temp = new Dictionary<string, string>();
                        data.Add("_rnr_se", rnrSEE);

                        foreach (KeyValuePair<string, string> h in data)
                        {
                            dataString += h.Key + "=" + HttpUtility.UrlEncode(h.Value, Encoding.UTF8);
                            dataString += "&";
                        }
                        dataString.TrimEnd(new char[] { '&' });
                    }
                    else
                    {
                        //dataString += data +
                    }
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                }
                else
                {
                    request.Method = "GET";
                }
                //request.Headers.Add(headers);

                request.ContentLength = dataString.Length;
                if (dataString.Length > 0)
                {
                    using (Stream writeStream = request.GetRequestStream())
                    {
                        UTF8Encoding encoding = new UTF8Encoding();
                        byte[] bytes = encoding.GetBytes(dataString);
                        writeStream.Write(bytes, 0, bytes.Length);
                    }
                }
                response = request.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                if (page.ToUpper() != "LOGIN")
                {
                    result = reader.ReadToEnd();
                }
                else
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        result.Add(line);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
                Debug.WriteLine(ex.Data);
                throw new IOException(ex.Message);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                if (response != null)
                    response.Close();
            }

            if (result.Equals(""))
            {
                throw new IOException("No Response Data Received.");
            }

            return result;
        }
        public string StartCartridge(string action, Manifest cartridge, dynamic options)
        {
            options = (Dictionary<string, object>)options;
            if (!options.ContainsKey("user_initiated"))
            {
                options.Add("user_initiated", true);
            }

            if (!options.ContainsKey("hot_deploy"))
            {
                options.Add("hot_deploy", false);
            }

            if (!options["user_initiated"] && StopLockExists)
            {
                return string.Format("Not starting cartridge {0} because the application was explicitly stopped by the user", cartridge.Name);
            }

            Manifest primaryCartridge = GetPrimaryCartridge();            

            if (primaryCartridge != null)
            {
                if (primaryCartridge.Name == cartridge.Name)
                {
                    if (options["user_initiated"])
                    {
                        File.Delete(StopLock);
                    }
                    state.Value(State.STARTED);

                //TODO : Unidle the application
                }
            }

            if (options["hot_deploy"])
            {
                return string.Format("Not starting cartridge {0} because hot deploy is enabled", cartridge.Name);
            }

            return DoControl(action, cartridge, options);
        }
        public string StopCartridge(string cartridgeName, bool userInitiated, dynamic options)
        {

            Manifest manifest = GetCartridge(cartridgeName);
            if (!options.ContainsKey("user_initiated"))
            {
                options.Add("user_initiated", userInitiated);
            }
            else
            {
                options["user_initiated"] = userInitiated;
            }
            return StopCartridge(manifest, options);

        }
Exemplo n.º 11
0
        public void Discover(ShapeTableBuilder builder)
        {
            builder.Describe("Content")
            .OnDisplaying(displaying =>
            {
                dynamic shape           = displaying.Shape;
                ContentItem contentItem = shape.ContentItem;

                if (contentItem != null)
                {
                    // Alternates in order of specificity.
                    // Display type > content type > specific content > display type for a content type > display type for specific content
                    // BasicShapeTemplateHarvester.Adjust will then adjust the template name

                    // Content__[DisplayType] e.g. Content-Summary
                    displaying.Shape.Metadata.Alternates.Add("Content_" + EncodeAlternateElement(displaying.Shape.Metadata.DisplayType));

                    // Content__[ContentType] e.g. Content-BlogPost,
                    displaying.Shape.Metadata.Alternates.Add("Content__" + EncodeAlternateElement(contentItem.ContentType));

                    // Content__[Id] e.g. Content-42,
                    displaying.Shape.Metadata.Alternates.Add("Content__" + contentItem.Id);

                    // Content_[DisplayType]__[ContentType] e.g. Content-BlogPost.Summary
                    displaying.Shape.Metadata.Alternates.Add("Content_" + displaying.Shape.Metadata.DisplayType + "__" + EncodeAlternateElement(contentItem.ContentType));

                    // Content_[DisplayType]__[Id] e.g. Content-42.Summary
                    displaying.Shape.Metadata.Alternates.Add("Content_" + displaying.Shape.Metadata.DisplayType + "__" + contentItem.Id);
                }
            });

            // This shapes provides a way to lazily load a content item render it in any display type.
            builder.Describe("ContentItem")
            .OnProcessing(async context =>
            {
                dynamic content    = context.Shape;
                string handle      = content.Handle;
                string displayType = content.DisplayType;
                string alternate   = content.Alternate;

                if (String.IsNullOrEmpty(handle))
                {
                    // This code is provided for backwards compatability and can be removed in a future version.
                    handle = content.Alias;
                    if (String.IsNullOrEmpty(handle))
                    {
                        return;
                    }
                }

                var contentManager      = context.ServiceProvider.GetRequiredService <IContentManager>();
                var handleManager       = context.ServiceProvider.GetRequiredService <IContentHandleManager>();
                var displayManager      = context.ServiceProvider.GetRequiredService <IContentItemDisplayManager>();
                var updateModelAccessor = context.ServiceProvider.GetRequiredService <IUpdateModelAccessor>();

                var contentItemId = await handleManager.GetContentItemIdAsync(handle);

                if (string.IsNullOrEmpty(contentItemId))
                {
                    return;
                }

                var contentItem = await contentManager.GetAsync(contentItemId);

                if (contentItem == null)
                {
                    return;
                }

                content.ContentItem = contentItem;

                var displayShape = await displayManager.BuildDisplayAsync(contentItem, updateModelAccessor.ModelUpdater, displayType);

                if (!String.IsNullOrEmpty(alternate))
                {
                    displayShape.Metadata.Alternates.Add(alternate);
                }

                content.Add(displayShape);
            });
        }
Exemplo n.º 12
0
Arquivo: Tags.cs Projeto: yysun/Rabbit
 public static dynamic pages_page_detail_home_aside(dynamic data)
 {
     data.Add("~/Views/Tags/_Page_List_Home_Aside.cshtml");
     return data;
 }
Exemplo n.º 13
0
        public IHtmlString Pager_Links(dynamic Shape, dynamic Display,
            HtmlHelper Html,
            int Page,
            int PageSize,
            double TotalItemCount,
            int? Quantity,
            object FirstText,
            object PreviousText,
            object NextText,
            object LastText,
            object GapText,
            string PagerId
            // parameter omitted to workaround an issue where a NullRef is thrown
            // when an anonymous object is bound to an object shape parameter
            /*object RouteValues*/) {

            var currentPage = Page;
            if (currentPage < 1)
                currentPage = 1;

            var pageSize = PageSize;
            if (pageSize < 1)
                pageSize = _workContext.Value.CurrentSite.PageSize;

            var numberOfPagesToShow = Quantity ?? 0;
            if (Quantity == null || Quantity < 0)
                numberOfPagesToShow = 7;
    
            var totalPageCount = (int)Math.Ceiling(TotalItemCount / pageSize);

            var firstText = FirstText ?? T("<<");
            var previousText = PreviousText ?? T("<");
            var nextText = NextText ?? T(">");
            var lastText = LastText ?? T(">>");
            var gapText = GapText ?? T("...");

            var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values);
            var queryString = _workContext.Value.HttpContext.Request.QueryString;
            if (queryString != null) {
                foreach (var key in from string key in queryString.Keys where key != null && !routeData.ContainsKey(key) let value = queryString[key] select key) {
                    routeData[key] = queryString[key];
                }
            }

            // specific cross-requests route data can be passed to the shape directly (e.g., Orchard.Users)
            var shapeRoute = (object)Shape.RouteData;

            if (shapeRoute != null) {
                var shapeRouteData = shapeRoute as RouteValueDictionary;
                if (shapeRouteData == null) {
                    var route = shapeRoute as RouteData;
                    if (route != null) {
                        shapeRouteData = (route).Values;    
                    }
                }

                if (shapeRouteData != null) {
                    foreach (var rd in shapeRouteData) {
                        routeData[rd.Key] = rd.Value;
                    }
                }
            }

            // HACK: MVC 3 is adding a specific value in System.Web.Mvc.Html.ChildActionExtensions.ActionHelper
            // when a content item is set as home page, it is rendered by using Html.RenderAction, and the routeData is altered
            // This code removes this extra route value
            var removedKeys = routeData.Keys.Where(key => routeData[key] is DictionaryValueProvider<object>).ToList();
            foreach (var key in removedKeys) {
                routeData.Remove(key);
            }

            int firstPage = Math.Max(1, Page - (numberOfPagesToShow / 2));
            int lastPage = Math.Min(totalPageCount, Page + (int)(numberOfPagesToShow / 2));

            var pageKey = String.IsNullOrEmpty(PagerId) ? "page" : PagerId;

            Shape.Classes.Add("pager");
            Shape.Metadata.Alternates.Clear();
            Shape.Metadata.Type = "List";

            // first and previous pages
            if (Page > 1) {
                if (routeData.ContainsKey(pageKey)) {
                    routeData.Remove(pageKey); // to keep from having "page=1" in the query string
                }
                // first
                Shape.Add(Display.Pager_First(Value: firstText, RouteValues: routeData, Pager: Shape));

                // previous
                if (currentPage > 2) { // also to keep from having "page=1" in the query string
                    routeData[pageKey] = currentPage - 1;
                }
                Shape.Add(Display.Pager_Previous(Value: previousText, RouteValues: routeData, Pager: Shape));
            }

            // gap at the beginning of the pager
            if (firstPage > 1 && numberOfPagesToShow > 0) {
                Shape.Add(Display.Pager_Gap(Value: gapText, Pager: Shape));
            }

            // page numbers
            if (numberOfPagesToShow > 0 && firstPage != lastPage) {
                for (var p = firstPage; p <= lastPage; p++) {
                    if (p == currentPage) {
                        Shape.Add(Display.Pager_CurrentPage(Value: p, RouteValues: routeData, Pager: Shape));
                    }
                    else {
                        if (p == 1)
                            routeData.Remove(pageKey);
                        else
                            routeData[pageKey] = p;
                        Shape.Add(Display.Pager_Link(Value: p, RouteValues: routeData, Pager: Shape));
                    }
                }
            }

            // gap at the end of the pager
            if (lastPage < totalPageCount && numberOfPagesToShow > 0) {
                Shape.Add(Display.Pager_Gap(Value: gapText, Pager: Shape));
            }
    
            // next and last pages
            if (Page < totalPageCount) {
                // next
                routeData[pageKey] = Page + 1;
                Shape.Add(Display.Pager_Next(Value: nextText, RouteValues: routeData, Pager: Shape));
                // last
                routeData[pageKey] = totalPageCount;
                Shape.Add(Display.Pager_Last(Value: lastText, RouteValues: routeData, Pager: Shape));
            }

            return Display(Shape);
        }
Exemplo n.º 14
0
        private void AnalyzeContent(ref dynamic results, string resultPath, string[] ignoreList, string filterFile)
        {
            WebClient webClient = new WebClient();

            DirectoryInfo dir = new DirectoryInfo(resultPath);

            if (String.IsNullOrEmpty(filterFile))
            {
                filterFile = "*";
            }

            // Get all files in directory with matched prefix name
            FileInfo[] files = dir.GetFiles($"{filterFile}.html");

            if (files.Count() == 0)
            {
                throw new Exception($"There is no file with name \"{filterFile}.html\" in folder \"{resultPath}\"");
            }

            // Loop all files and get data base on defined keywords
            foreach (FileInfo file in files)
            {
                var    filePath = "file:///" + resultPath.Replace("\\", "/") + "/" + file.Name;
                string page     = webClient.DownloadString(filePath);
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(page);

                var tables = doc.DocumentNode.SelectNodes("//ul[@id='test-collection']/li").ToList();
                for (int i = 1; i <= tables.Count; i++)
                {
                    var    testNode  = doc.DocumentNode.SelectNodes($"(//ul[@id='test-collection']/li)[{i}]").Single();
                    string testID    = testNode.SelectNodes(".//span[@class='test-name']").Single().InnerText.Trim();
                    string startTime = testNode.SelectNodes(".//span[@class='label start-time']").Single().InnerText.Trim();
                    string endTime   = testNode.SelectNodes(".//span[@class='label end-time']").Single().InnerText.Trim();
                    string status    = Helper.UpperFirstCharacter(testNode.SelectNodes(".//div[@class='test-heading']/span[contains(@class,'test-status')]").Single().InnerText.Trim()) + "ed";
                    string message   = "";

                    // Get error/warning message if test case is not pass
                    if (status != "Passed")
                    {
                        var lastNode = testNode.SelectNodes("(.//li[contains(@class,'node')])[last()]").Single();
                        if (lastNode.Attributes["status"].Value != "pass")
                        {
                            var lastLog = lastNode.SelectNodes("(.//tr[@class='log'])[last()]").Single();
                            if (lastLog.Attributes["status"].Value != "info" && lastLog.Attributes["status"].Value != "pass")
                            {
                                message = lastLog.SelectNodes(".//td[@class='step-details']").Single().InnerText.Trim();
                            }
                        }
                    }

                    // Ignore all test cases in ignore list
                    if (!Array.Exists(ignoreList, E => E == testID))
                    {
                        // If get only one data for each test case, compare and get data has latest end time
                        // Else get all raw data for each test case (one test case id can be run many times with different test result)
                        if (results.GetType() == typeof(Dictionary <string, string[]>))
                        {
                            if (results.ContainsKey(testID))
                            {
                                DateTime storedDate  = DateTime.ParseExact(results[testID][Constant.TEST_END_TIME_INDEX].ToString(), REPORT_DATE_FORMAT, null);
                                DateTime currentDate = DateTime.ParseExact(endTime, REPORT_DATE_FORMAT, null);
                                if (storedDate < currentDate)
                                {
                                    results[testID] = new string[] { startTime, endTime, status, message };
                                }
                            }
                            else
                            {
                                results[testID] = new string[] { startTime, endTime, status, message };
                            }
                        }
                        else
                        {
                            results.Add(new KeyValuePair <string, string[]>(testID, new string[] { startTime, endTime, status, message }));
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
        public IHtmlString Pager_Links(dynamic Shape, dynamic Display,
                                       HtmlHelper Html,
                                       int Page,
                                       int PageSize,
                                       double TotalItemCount,
                                       int?Quantity,
                                       object FirstText,
                                       object PreviousText,
                                       object NextText,
                                       object LastText,
                                       object GapText,
                                       string PagerId
                                       // parameter omitted to workaround an issue where a NullRef is thrown
                                       // when an anonymous object is bound to an object shape parameter
                                       /*object RouteValues*/)
        {
            var currentPage = Page;

            if (currentPage < 1)
            {
                currentPage = 1;
            }

            var pageSize = PageSize;

            if (pageSize < 1)
            {
                pageSize = _workContext.Value.CurrentSite.PageSize;
            }

            var numberOfPagesToShow = Quantity ?? 0;

            if (Quantity == null || Quantity < 0)
            {
                numberOfPagesToShow = 7;
            }

            var totalPageCount = (int)Math.Ceiling(TotalItemCount / pageSize);

            var firstText    = FirstText ?? T("<<");
            var previousText = PreviousText ?? T("<");
            var nextText     = NextText ?? T(">");
            var lastText     = LastText ?? T(">>");
            var gapText      = GapText ?? T("...");

            var routeData   = new RouteValueDictionary(Html.ViewContext.RouteData.Values);
            var queryString = _workContext.Value.HttpContext.Request.QueryString;

            if (queryString != null)
            {
                foreach (var key in from string key in queryString.Keys where key != null && !routeData.ContainsKey(key) let value = queryString[key] select key)
                {
                    routeData[key] = queryString[key];
                }
            }

            // specific cross-requests route data can be passed to the shape directly (e.g., Orchard.Users)
            var shapeRoute = (object)Shape.RouteData;

            if (shapeRoute != null)
            {
                var shapeRouteData = shapeRoute as RouteValueDictionary;
                if (shapeRouteData == null)
                {
                    var route = shapeRoute as RouteData;
                    if (route != null)
                    {
                        shapeRouteData = (route).Values;
                    }
                }

                if (shapeRouteData != null)
                {
                    foreach (var rd in shapeRouteData)
                    {
                        routeData[rd.Key] = rd.Value;
                    }
                }
            }

            // HACK: MVC 3 is adding a specific value in System.Web.Mvc.Html.ChildActionExtensions.ActionHelper
            // when a content item is set as home page, it is rendered by using Html.RenderAction, and the routeData is altered
            // This code removes this extra route value
            var removedKeys = routeData.Keys.Where(key => routeData[key] is DictionaryValueProvider <object>).ToList();

            foreach (var key in removedKeys)
            {
                routeData.Remove(key);
            }

            int firstPage = Math.Max(1, Page - (numberOfPagesToShow / 2));
            int lastPage  = Math.Min(totalPageCount, Page + (int)(numberOfPagesToShow / 2));

            var pageKey = String.IsNullOrEmpty(PagerId) ? "page" : PagerId;

            Shape.Classes.Add("pager");
            Shape.Metadata.Alternates.Clear();
            Shape.Metadata.Type = "List";

            // first and previous pages
            if (Page > 1)
            {
                if (routeData.ContainsKey(pageKey))
                {
                    routeData.Remove(pageKey); // to keep from having "page=1" in the query string
                }
                // first
                Shape.Add(New.Pager_First(Value: firstText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));

                // previous
                if (currentPage > 2)   // also to keep from having "page=1" in the query string
                {
                    routeData[pageKey] = currentPage - 1;
                }
                Shape.Add(New.Pager_Previous(Value: previousText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
            }

            // gap at the beginning of the pager
            if (firstPage > 1 && numberOfPagesToShow > 0)
            {
                Shape.Add(New.Pager_Gap(Value: gapText, Pager: Shape));
            }

            // page numbers
            if (numberOfPagesToShow > 0)
            {
                for (var p = firstPage; p <= lastPage; p++)
                {
                    if (p == currentPage)
                    {
                        Shape.Add(New.Pager_CurrentPage(Value: p, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
                    }
                    else
                    {
                        if (p == 1)
                        {
                            routeData.Remove(pageKey);
                        }
                        else
                        {
                            routeData[pageKey] = p;
                        }
                        Shape.Add(New.Pager_Link(Value: p, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
                    }
                }
            }

            // gap at the end of the pager
            if (lastPage < totalPageCount && numberOfPagesToShow > 0)
            {
                Shape.Add(New.Pager_Gap(Value: gapText, Pager: Shape));
            }

            // next and last pages
            if (Page < totalPageCount)
            {
                // next
                routeData[pageKey] = Page + 1;
                Shape.Add(New.Pager_Next(Value: nextText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
                // last
                routeData[pageKey] = totalPageCount;
                Shape.Add(New.Pager_Last(Value: lastText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
            }

            return(Display(Shape));
        }
Exemplo n.º 16
0
        /// <summary>
        /// extra custom functinos go in here.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="args"></param>
        private void NCalcPulsarFunctions(string name, FunctionArgs args)
        {
            if (name == "Ability")
            {
                int index = 0;
                try
                {
                    index = (int)args.Parameters[0].Evaluate();

                    ChainedExpression result = _design.ComponentDesignAttributes[index].Formula;
                    if (result.Result == null)
                    {
                        result.Evaluate();
                    }
                    MakeThisDependant(result);
                    args.Result = result.Result;
                }
                catch (InvalidCastException e) { throw new Exception("Parameter must be an intiger. " + e); }
                catch (IndexOutOfRangeException e) { throw new Exception("This component does not have an ComponentAbilitySD at index " + index + ". " + e); }
            }
            if (name == "SetAbilityValue") //I might remove this..
            {
                int index = 0;
                try
                {
                    index = (int)args.Parameters[0].Evaluate();

                    ChainedExpression expression = _design.ComponentDesignAttributes[index].Formula;
                    expression.SetResult = args.Parameters[1].Evaluate();
                }
                catch (InvalidCastException e) { throw new Exception("Parameter must be an intiger. " + e); }
                catch (IndexOutOfRangeException e) { throw new Exception("This component does not have an ComponentAbilitySD at index " + index + ". " + e); }
            }

            if (name == "EnumDict")
            {
                string  typeAsString = (string)args.Parameters[0].Evaluate();
                Type    type         = Type.GetType(typeAsString);
                Type    dictType     = typeof(Dictionary <,>).MakeGenericType(type, typeof(double));
                dynamic dict         = Activator.CreateInstance(dictType);

                Type    enumDictType  = typeof(Dictionary <,>).MakeGenericType(typeof(string), type);
                dynamic enumConstants = Activator.CreateInstance(enumDictType);
                foreach (dynamic value in Enum.GetValues(type))
                {
                    enumConstants.Add(Enum.GetName(type, value), value);
                }

                foreach (var kvp in _designAttribute.GuidDictionary)
                {
                    dynamic key = enumConstants[(string)kvp.Key];
                    dict.Add(key, kvp.Value.DResult);
                }
                args.Result = dict;
            }

            if (name == "TechData")
            {
                Guid   techGuid = Guid.Parse((string)args.EvaluateParameters()[0]);
                TechSD techSD   = _staticDataStore.Techs[techGuid];
                args.Result = ResearchProcessor.DataFormula(_factionTechDB, techSD);
            }

            //Returns the tech level for the given guid
            if (name == "TechLevel")
            {
                Guid techGuid = Guid.Parse((string)args.EvaluateParameters()[0]);
                if (_factionTechDB.ResearchedTechs.ContainsKey(techGuid))
                {
                    args.Result = _factionTechDB.ResearchedTechs[techGuid];
                }
                else
                {
                    args.Result = 0;
                }
            }
            //currently not used, but an future experiment to pass the CargoTypeSD as a parameter
            if (name == "CargoType")
            {
                Guid        typeGuid = Guid.Parse((string)args.EvaluateParameters()[0]);
                CargoTypeSD typeSD   = _staticDataStore.CargoTypes[typeGuid];
                args.Result = typeSD;
            }
            //used for datablob args for when a guid is required as a parameter
            if (name == "GuidString")
            {
                Guid typeGuid = Guid.Parse((string)args.EvaluateParameters()[0]);
                args.Result = typeGuid;
            }

            //This sets the DatablobArgs. it's up to the user to ensure the right number of args for a specific datablob
            //The datablob will be the one defined in designAbility.DataBlobType
            //TODO document blobs and what args they take!!
            if (name == "DataBlobArgs")
            {
                if (_designAttribute.DataBlobType == null)
                {
                    throw new Exception("This Ability does not have a DataBlob defined! define a datablob for this ability!");
                }
                //_designAbility.DataBlobArgs = new List<double>();
                List <object> argList = new List <object>();
                foreach (var argParam in args.Parameters)
                {
                    ChainedExpression argExpression = new ChainedExpression(argParam, _designAttribute, _factionTechDB, _staticDataStore);
                    _isDependant = false;
                    argExpression.Evaluate();
                    argList.Add(argExpression.Result);
                }
                _designAttribute.DataBlobArgs = argList.ToArray();
                args.Result = argList;
            }
        }
Exemplo n.º 17
0
        public static T Parse <T>(List <Parameter> descriptor, string path = "") where T : new()
        {
            var properties  = ElementsHelper.SortedProperties <T>();
            var result      = new T();
            var currentType = typeof(T);

            var thisMethod = typeof(ParametersConverter).GetMethod(nameof(Parse));

            foreach (var parameter in descriptor)
            {
                var currentPath = string.IsNullOrEmpty(path)
                    ? parameter.Id.ToString()
                    : string.Concat(path, '.', parameter.Id.ToString());
                if (!properties.ContainsKey(parameter.Id))
                {
                    Logger.Error($"Parameter {parameter.Id} isn't supported for {currentType.Name}");
                    return(result);
                }
                //    throw new ArgumentException($"Parameter {parameter.Id} isn't supported for {currentType.Name}");

                var propertyInfo = properties[parameter.Id];
                var propertyType = propertyInfo.PropertyType;

                if (propertyType == typeof(long) ||
                    propertyType == typeof(TextAlignment) ||
                    propertyType == typeof(bool) ||
                    propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    Logger.Trace("{0} '{1}': {2}", currentPath, propertyInfo.Name, parameter.Value);
                    dynamic propertyValue = propertyInfo.GetValue(result, null);

                    if (propertyType.IsGenericType && propertyValue != null)
                    {
                        throw new ArgumentException($"Parameter {parameter.Id} is already set for {currentType.Name}");
                    }

                    if (!propertyType.IsGenericType && propertyType == typeof(long) && propertyValue != 0)
                    {
                        throw new ArgumentException($"Parameter {parameter.Id} is already set for {currentType.Name}");
                    }

                    if (propertyType == typeof(TextAlignment))
                    {
                        propertyInfo.SetValue(result, (TextAlignment)parameter.Value, null);
                    }
                    else if (propertyType == typeof(bool))
                    {
                        propertyInfo.SetValue(result, parameter.Value > 0, null);
                    }
                    else
                    {
                        propertyInfo.SetValue(result, parameter.Value, null);
                    }
                }
                else if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    Logger.Trace("{0} '{1}'", currentPath, propertyInfo.Name);
                    dynamic propertyValue = propertyInfo.GetValue(result, null);
                    if (propertyValue == null)
                    {
                        propertyValue = Activator.CreateInstance(propertyType);
                        propertyInfo.SetValue(result, propertyValue, null);
                    }

                    try
                    {
                        var     generic     = thisMethod.MakeGenericMethod(propertyType.GetGenericArguments()[0]);
                        dynamic parsedValue = generic.Invoke(null,
                                                             new dynamic[] { parameter.Children, currentPath });
                        propertyValue.Add(parsedValue);
                    }
                    catch (TargetInvocationException e)
                    {
                        throw e.InnerException;
                    }
                }
                else
                {
                    Logger.Trace("{0} '{1}'", currentPath, propertyInfo.Name);
                    dynamic propertyValue = propertyInfo.GetValue(result, null);
                    if (propertyValue != null)
                    {
                        throw new ArgumentException($"Parameter {parameter.Id} is already set for {currentType.Name}");
                    }

                    try
                    {
                        var     generic     = thisMethod.MakeGenericMethod(propertyType);
                        dynamic parsedValue = generic.Invoke(null, new object[] { parameter.Children, currentPath });
                        propertyInfo.SetValue(result, parsedValue, null);
                    }
                    catch (TargetInvocationException e)
                    {
                        throw e.InnerException;
                    }
                }
            }

            return(result);
        }
Exemplo n.º 18
0
 public void Add(T item)
 {
     c.Add(item);
 }
Exemplo n.º 19
0
 static XeedMod()
 {
     MainMod.LoadConfig();
     items = new List<CustomItem>();
     if (File.Exists(ItemFile))
     {
         CustomItem ci = null;
         foreach (string line in File.ReadAllLines(ItemFile))
             if (line.StartsWith("[") && line.EndsWith("]"))
             {
                 if (ci != null) items.Add(ci);
                 ci = new CustomItem(line.Remove(line.Length - 1, 1).Remove(0, 1));
             }
             else
             {
                 string[] data = line.Split(new char[] { '=' }, 2);
                 if (data[0].Equals("baseId")) ci.iId = int.Parse(data[1]);
                 else if (data[0].Equals("name")) ci.name = data[1];
                 else if (data[0].Equals("scope-effect")) ci.scope = bool.Parse(data[1]);
                 else if (data[0].Equals("texture-name") && !String.IsNullOrWhiteSpace(data[1]))
                     ci.ctex = ImageToByte2(System.Drawing.Image.FromFile(MainMod.Config.PluginDataDirectory + @"\Textures\" + data[1]));
                 else if (!data[0].StartsWith("#")) ci.AddField(data[0].Split(':'), data[1]);
             }
         if (ci != null) items.Add(ci);
     }
 }
Exemplo n.º 20
0
        private dynamic AddNewComponent(dynamic parentDirectory, bool? isPrimary = null)
        {
            var guid = Guid.NewGuid();

            var componentRef = wix.Product["Id=ProductFeature"].Add("ComponentRef");
            componentRef.Attributes.Id = guid.ComponentId();
            if (isPrimary.HasValue) {
                componentRef.Attributes.Primary = isPrimary == true ? "yes" : "no";
            }
            var component = parentDirectory.Add("Component");
            component.Attributes.Id = guid.ComponentId();
            component.Attributes.Guid = guid.ToString("B");

            return component;
        }
Exemplo n.º 21
0
        private static async Task <ResolveFieldResult <object> > ResolveFieldAsync(dynamic source, dynamic target, Fields fields, bool isRoot = false)
        {
            if (target == null)
            {
                target = new ExpandoObject();
            }

            var resolveResult = new ResolveFieldResult <object>
            {
                Skip = false
            };

            var subFields        = new Dictionary <string, Fields>();
            var visitedFragments = new List <string>();

            var f = fields.First();

            subFields = CollectFields(f.SelectionSet, subFields, visitedFragments);

            dynamic result;

            if (isRoot)
            {
                result = new List <object>();
                var collection = ((IDataStore)source).GetCollection(f.Name);

                foreach (var item in collection.AsQueryable())
                {
                    if (f.Arguments.Any(a => GetValue(item, a.Name) != ((dynamic)a.Value).Value))
                    {
                        continue;
                    }

                    dynamic rootObject = new ExpandoObject();

                    foreach (var i in subFields)
                    {
                        var r = await ResolveFieldAsync(item, rootObject, i.Value);

                        rootObject = r.Value;
                    }

                    if (rootObject != null)
                    {
                        result.Add(rootObject);
                    }
                }

                resolveResult.Value = result;
                return(resolveResult);
            }
            else
            {
                var newSource = ((IDictionary <string, object>)source).ContainsKey(f.Name) ? ((IDictionary <string, object>)source)[f.Name] : null;

                var newTarget = target;

                if (newSource is ExpandoObject && subFields.Count > 0)
                {
                    if (f.Arguments.Any(a => GetValue(newSource, a.Name) != ((dynamic)a.Value).Value))
                    {
                        return(resolveResult);
                    }

                    newTarget = new ExpandoObject();
                    ((IDictionary <string, object>)target)[f.Name] = newTarget;

                    foreach (var i in subFields)
                    {
                        var r = await ResolveFieldAsync(newSource, newTarget, i.Value);
                    }
                }
                else if (IsEnumerable(newSource?.GetType()) && subFields.Count > 0)
                {
                    dynamic newArray = Activator.CreateInstance(newSource.GetType());
                    ((IDictionary <string, object>)target)[f.Name] = newArray;

                    foreach (var item in newSource as IEnumerable <dynamic> )
                    {
                        if (f.Arguments.Any(a => GetValue(item, a.Name) != ((dynamic)a.Value).Value))
                        {
                            continue;
                        }

                        dynamic rootObject = new ExpandoObject();

                        foreach (var i in subFields)
                        {
                            var r = await ResolveFieldAsync(item, rootObject, i.Value);

                            rootObject = r.Value;
                        }

                        if (rootObject != null)
                        {
                            newArray.Add(rootObject);
                        }
                    }
                }
                else
                {
                    ((IDictionary <string, object>)target)[f.Name] = newSource;
                }

                resolveResult.Value = target;
                return(resolveResult);
            }
        }
Exemplo n.º 22
0
        private async void Install_Click(object sender, RoutedEventArgs e)
        {
            _installButton.IsEnabled = false;

            try {
                var     list             = _list.ItemsSource as List <UpdateItem>;
                dynamic updatesToInstall = Activator.CreateInstance(Type.GetTypeFromProgID("Microsoft.Update.UpdateColl"));
                foreach (var item in list)
                {
                    if (!item.IsChecked)
                    {
                        continue;
                    }
                    if (!item.EulaAccepted)
                    {
                        if (MessageBox.Show(this, item.Update.EulaText, "Do you accept this license agreement?", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                        {
                            continue;
                        }
                        item.Update.AcceptEula();
                    }
                    updatesToInstall.Add(item.Update);
                }
                if (updatesToInstall.Count == 0)
                {
                    _status.Text = "All applicable updates were skipped.";
                }
                else
                {
                    _status.Text = "Downloading updates...";
                    dynamic downloader = _updateSession.CreateUpdateDownloader();
                    downloader.Updates = updatesToInstall;
                    await Task.Run(() => { downloader.Download(); });

                    if (MessageBox.Show(this, "Installation ready. Continue?", "Notice", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        _status.Text = "Installing updates...";

                        dynamic installer = _updateSession.CreateUpdateInstaller();
                        installer.Updates = updatesToInstall;
                        dynamic installationResult = null;
                        await Task.Run(() => { installationResult = installer.Install(); });

                        var sb = new StringBuilder();
                        if (installationResult.RebootRequired == true)
                        {
                            sb.Append("[REBOOT REQUIRED] ");
                        }
                        sb.AppendFormat("Code: {0}\n", installationResult.ResultCode);
                        sb.Append("Listing of updates installed:\n");
                        for (int i = 0; i < updatesToInstall.Count; ++i)
                        {
                            sb.AppendFormat("{0} : {1}\n",
                                            installationResult.GetUpdateResult(i).ResultCode,
                                            updatesToInstall.Item(i).Title);
                        }
                        MessageBox.Show(this, sb.ToString(), "Installation Result");
                    }
                    await SearchForUpdates();
                }
            }
            catch (Exception ex) {
                MessageBox.Show(this, ex.ToString(), "Exception has occured!");
            }

            _installButton.IsEnabled = true;
        }
Exemplo n.º 23
0
        public void InitializeAsDictionary(JObject o)
        {
            underlyingObject = new Dictionary<string, object>();

            foreach (var value in o) underlyingObject.Add(value.Key, value.Value);
        }
Exemplo n.º 24
0
 public void Execute(object parameter)
 {
     _viewModel.Add();
 }
Exemplo n.º 25
0
        public IHtmlContent Pager_Links(dynamic Shape, dynamic Display, dynamic New,
            IHtmlHelper Html,
            int Page,
            int PageSize,
            double TotalItemCount,
            int? Quantity,
            object FirstText,
            object PreviousText,
            object NextText,
            object LastText,
            object GapText,
            string PagerId
            // parameter omitted to workaround an issue where a NullRef is thrown
            // when an anonymous object is bound to an object shape parameter
            /*object RouteValues*/)
        {

            var currentPage = Page;
            if (currentPage < 1)
                currentPage = 1;

            var pageSize = PageSize;

            var numberOfPagesToShow = Quantity ?? 0;
            if (Quantity == null || Quantity < 0)
                numberOfPagesToShow = 7;

            var totalPageCount = pageSize > 0 ? (int)Math.Ceiling(TotalItemCount / pageSize) : 1;

            var firstText = FirstText ?? T["<<"];
            var previousText = PreviousText ?? T["<"];
            var nextText = NextText ?? T[">"];
            var lastText = LastText ?? T[">>"];
            var gapText = GapText ?? T["..."];

            var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values);
            var queryString = _httpContextAccessor.HttpContext.Request.Query;
            if (queryString != null)
            {
                foreach (var key in from string key in queryString.Keys where key != null && !routeData.ContainsKey(key) let value = queryString[key] select key)
                {
                    routeData[key] = queryString[key];
                }
            }

            // specific cross-requests route data can be passed to the shape directly (e.g., Orchard.Users)
            var shapeRoute = (object)Shape.RouteData;

            if (shapeRoute != null)
            {
                var shapeRouteData = shapeRoute as RouteValueDictionary;
                if (shapeRouteData == null)
                {
                    var route = shapeRoute as RouteData;
                    if (route != null)
                    {
                        shapeRouteData = new RouteValueDictionary(route.Values);
                    }
                }

                if (shapeRouteData != null)
                {
                    foreach (var rd in shapeRouteData)
                    {
                        routeData[rd.Key] = rd.Value;
                    }
                }
            }

            int firstPage = Math.Max(1, Page - (numberOfPagesToShow / 2));
            int lastPage = Math.Min(totalPageCount, Page + (int)(numberOfPagesToShow / 2));

            var pageKey = String.IsNullOrEmpty(PagerId) ? "page" : PagerId;

            Shape.Classes.Add("pager");
            Shape.Metadata.Alternates.Clear();
            Shape.Metadata.Type = "List";

            // first and previous pages
            if (Page > 1)
            {
                if (routeData.ContainsKey(pageKey))
                {
                    routeData.Remove(pageKey); // to keep from having "page=1" in the query string
                }
                // first
                Shape.Add(New.Pager_First(Value: firstText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));

                // previous
                if (currentPage > 2)
                { // also to keep from having "page=1" in the query string
                    routeData[pageKey] = currentPage - 1;
                }
                Shape.Add(New.Pager_Previous(Value: previousText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
            }

            // gap at the beginning of the pager
            if (firstPage > 1 && numberOfPagesToShow > 0)
            {
                Shape.Add(New.Pager_Gap(Value: gapText, Pager: Shape));
            }

            // page numbers
            if (numberOfPagesToShow > 0 && lastPage > 1)
            {
                for (var p = firstPage; p <= lastPage; p++)
                {
                    if (p == currentPage)
                    {
                        Shape.Add(New.Pager_CurrentPage(Value: p, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
                    }
                    else {
                        if (p == 1)
                            routeData.Remove(pageKey);
                        else
                            routeData[pageKey] = p;
                        Shape.Add(New.Pager_Link(Value: p, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
                    }
                }
            }

            // gap at the end of the pager
            if (lastPage < totalPageCount && numberOfPagesToShow > 0)
            {
                Shape.Add(New.Pager_Gap(Value: gapText, Pager: Shape));
            }

            // next and last pages
            if (Page < totalPageCount)
            {
                // next
                routeData[pageKey] = Page + 1;
                Shape.Add(New.Pager_Next(Value: nextText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
                // last
                routeData[pageKey] = totalPageCount;
                Shape.Add(New.Pager_Last(Value: lastText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
            }

            return Display(Shape);
        }
Exemplo n.º 26
0
        public void BindMembers(dynamic bindingObj)
        {
            Type type = bindingObj.GetType();
            if (!type.IsSubclassOf(typeof(XCompileObject)))
            {
                throw new XCompileException("Invalid base class inheritance! Class does not derive from CrossCompileObject!");
            }

            var parser = Language.Parser;
            parser.BindingObject = bindingObj;
            parser.Parse(_sourceFile);

            if (parser.CompilationUnitSyntax == null)
            {
                if (TargetMainClass.Equals(string.Empty))
                    throw new XCompileException("Invalid TargetMainClass name!");
                parser.InitializeExecutableCompilationUnit(TargetNamespace, TargetMainClass);
            }

            // Creates a dll compilation from the syntax tree received from the parser and
            // adds references at runtime including metadata references of System library
            var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var compilation = CSharpCompilation.Create(
                $"{TargetMainClass}.dll",
                references: new[] { mscorlib },
                syntaxTrees: new[] { parser.CompilationUnitSyntax.SyntaxTree }
                );
            compilation.GetSemanticModel(parser.CompilationUnitSyntax.SyntaxTree, false);

            // The compiled code is emitted into memory stream which is used to create a assembly at runtime
            Assembly assembly;
            using (var stream = new MemoryStream())
            {
                compilation.Emit(stream);
                assembly = Assembly.Load(stream.GetBuffer());
            }

            // Adding the new assembly to the dynamic object instance
            bindingObj.Add(Language.AssemblyName, assembly);
            bindingObj.Add($"CreateInstanceOf{TargetMainClass}", new Func<object>(() => assembly.CreateInstance($"{TargetNamespace}.{TargetMainClass}")));
        }
Exemplo n.º 27
0
        private dynamic FindOrCreateDirectory(dynamic parentDirectory, string subFolderPath)
        {
            if (string.IsNullOrEmpty(subFolderPath)) {
                return parentDirectory;
            }

            var path = subFolderPath;
            string childPath = null;
            var i = subFolderPath.IndexOf('\\');
            if (i > -1) {
                path = subFolderPath.Substring(0, i);
                childPath = subFolderPath.Substring(i + 1);
            }

            var immediateSubdirectory = parentDirectory["Name=" + path];

            if (immediateSubdirectory == null) {
                immediateSubdirectory = parentDirectory.Add("Directory");
                // immediateSubdirectory.Attributes.Id = path.MakeSafeDirectoryId() + (subFolderPath.MD5Hash());
                string pid = parentDirectory.Attributes.Id.ToString();

                immediateSubdirectory.Attributes.Id = "dir_" + ((pid + subFolderPath).MD5Hash());

                immediateSubdirectory.Attributes.Name = path;
            }

            if (! string.IsNullOrEmpty(childPath)) {
                return FindOrCreateDirectory(immediateSubdirectory, childPath);
            }

            return immediateSubdirectory;
        }
Exemplo n.º 28
0
        private static object Clone(object model, string flavor, Dictionary <object, object> cloneDictionary)
        {
            if (model == null)
            {
                return(null);
            }

            if (model.GetType().IsValueType)
            {
                return(model);
            }

            if (model is string)
            {
                return(model);
            }

            if (cloneDictionary.ContainsKey(model))
            {
                return(cloneDictionary[model]);
            }

            object clone = FastActivator.Create(model.GetType());

            cloneDictionary[model] = clone;

            if (clone == null)
            {
                return(null);
            }

            object value = null;

            foreach (PropertyInfo prop in model.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.GetField | BindingFlags.SetField))
            {
                if (!prop.CanRead ||
                    !prop.CanWrite ||
                    ExcludeProperty(model, flavor, prop) ||
                    prop.GetIndexParameters().Length > 0
                    )
                {
                    continue;
                }

                if (prop.PropertyType.GetInterface(typeof(IDictionary <,>).Name) != null)
                {
                    var     origCollection  = prop.GetValue(model, null) as IEnumerable;
                    dynamic cloneCollection = null;
                    if (origCollection != null)
                    {
                        cloneCollection = FastActivator.Create(prop.PropertyType);
                        foreach (dynamic elem in origCollection)
                        {
                            var key = Clone(elem.Key, flavor, cloneDictionary);
                            var obj = Clone(elem.Value, flavor, cloneDictionary);
                            cloneCollection.Add(key, obj);
                        }
                    }
                    prop.SetValue(clone, cloneCollection, null);
                    continue;
                }
                if (prop.PropertyType.GetInterface(typeof(ICollection <>).Name) != null)
                {
                    var origCollection = prop.GetValue(model, null) as IEnumerable;
                    if (origCollection == null)
                    {
                        prop.SetValue(clone, null, null);
                        continue;
                    }
                    dynamic cloneCollection = null;
                    if (prop.PropertyType.IsArray)
                    {
                        //cloneCollection = (origCollection as Array).Clone();
                        Type    elemType = prop.PropertyType.GetElementType();
                        dynamic list     = FastActivator.Create(Type.GetType(string.Format("{0}[[{1},{2}]]", typeof(List <>).FullName, elemType.FullName, elemType.Assembly.GetName())));
                        foreach (var elem in origCollection)
                        {
                            dynamic obj = Clone(elem, flavor, cloneDictionary);
                            list.Add(obj);
                        }
                        cloneCollection = list.ToArray();
                    }
                    else
                    {
                        cloneCollection = FastActivator.Create(prop.PropertyType);
                        foreach (var elem in origCollection)
                        {
                            dynamic obj = Clone(elem, flavor, cloneDictionary);
                            cloneCollection.Add(obj);
                        }
                    }
                    prop.SetValue(clone, cloneCollection, null);
                    continue;
                }
                try
                {
                    value = prop.GetValue(model, null);
                }
                catch (Exception)
                {
                }

                if (prop.PropertyType.IsValueType)
                {
                    prop.SetValue(clone, value, null);
                }
                else
                {
                    var obj = Clone(value, flavor, cloneDictionary);
                    try
                    {
                        prop.SetValue(clone, obj, null);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }
            return(clone);
        }