Example #1
0
 public void NewInit <K, V>(string type, IEnumerable <KeyValuePair <K, V> > args, string seperator)
 {
     WriteIndent("new " + type + " ");
     OpenBracket();
     Write(args.ToString(writer.Indent, ",\n"));
     WriteLine();
     CloseBracket(seperator);
 }
        public ContentResult SelectStation()
        {
            var Content = new ContentResult();
            IEnumerable <Station> stations = STATION_MANAGER.selectStation();

            Content.Content = stations.ToString();
            return(Content);
        }
Example #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Criterion"/> class.
 /// </summary>
 public Criterion(string propertyName, FilterFunction function, IEnumerable <int> ids)
     : this(propertyName, function, "(" + ids.ToString(", ") + ")")
 {
     if (function != FilterFunction.In)
     {
         throw new ArgumentException("List of IDs is only supported with 'FilterFunction.In'.");
     }
 }
Example #4
0
        private Card DeserializeObject(CardType cardType, IEnumerable jsonObject)
        {
            switch (cardType)
            {
            case CardType.Attachment:
                return(JsonConvert.DeserializeObject <IEnumerable <AttachmentCard> >(jsonObject.ToString(), SpecifiedSubclassConversion).First());

            case CardType.Character:
                return(JsonConvert.DeserializeObject <IEnumerable <CharacterCard> >(jsonObject.ToString(), SpecifiedSubclassConversion).First());

            case CardType.Event:
                return(JsonConvert.DeserializeObject <IEnumerable <EventCard> >(jsonObject.ToString(), SpecifiedSubclassConversion).First());

            case CardType.Holding:
                return(JsonConvert.DeserializeObject <IEnumerable <HoldingCard> >(jsonObject.ToString(), SpecifiedSubclassConversion).First());

            case CardType.Province:
                return(JsonConvert.DeserializeObject <IEnumerable <ProvinceCard> >(jsonObject.ToString(), SpecifiedSubclassConversion).First());

            case CardType.Role:
                return(JsonConvert.DeserializeObject <IEnumerable <RoleCard> >(jsonObject.ToString(), SpecifiedSubclassConversion).First());

            case CardType.Stronghold:
                return(JsonConvert.DeserializeObject <IEnumerable <StrongholdCard> >(jsonObject.ToString(), SpecifiedSubclassConversion).First());

            default:
                throw new CardTypeNotImplementedException();
            }
        }
 private void PrintArray <T>(IEnumerable <T> words)
 {
     Console.WriteLine(words.ToString());
     foreach (var item in words)
     {
         Console.Write($"{item}|");
     }
     Console.WriteLine("");
 }
        private double getNutrientsValue(JObject responsJFoodDetails, string wantedNutrient)
        {
            IEnumerable <JToken> responsJk = responsJFoodDetails["foods"][0]["food"]["nutrients"].Where(temp => temp["name"].ToString().Contains(wantedNutrient)).Select(temp => temp["value"]).First <JToken>();
            //responsJk = responsJk.Where(temp => temp["eunit"].ToString().Contains("g")).Select(temp => temp["value"]).First<JToken>();//=מידה measure
            string value = responsJk.ToString();
            string s     = value.Replace(".", ",");

            return(double.Parse(s));
        }
 public IsEqualCompressingWhiteSpace(IEnumerable <char> value)
 {
     if (value == null)
     {
         throw new ArgumentNullException(nameof(value), "Cannot be null");
     }
     _originalValue = value.ToString();
     _value         = RemoveRepeatedSpaces(value);
 }
Example #8
0
        /// <summary>
        /// Отпарвка push-уведомления
        /// </summary>
        /// <param name="settings">Настройки сервиса</param>
        /// <param name="pushNotifications">список уведомлений</param>
        /// <returns></returns>
        private async Task <bool> SendPushNotifications(NotificationsSettingsEntity settings,
                                                        IEnumerable <PushNotificationModel> pushNotifications)
        {
            var content  = new StringContent(pushNotifications.ToString(), Encoding.UTF8, Resources.JsonMIMEType);
            var response = await _httpClient.PostAsync(settings.PushUrl, content);

            return(response.StatusCode == System.Net.HttpStatusCode.NoContent ||
                   response.StatusCode == System.Net.HttpStatusCode.OK);
        }
Example #9
0
        private void ValidateArgs(string method, IEnumerable <MethodData> items, object[] args)
        {
            var argsOk = items.All(i => (i.Args == null && args == null) || i.Args.All(a => args.Contains(a)));

            if (!argsOk)
            {
                Assert.Fail($"Method {method} received args:\n {items.ToString(" - ")} but expected:\n {args?.ToString(" - ")}");
            }
        }
Example #10
0
        public override string ToString()
        {
            if (_expression is ConstantExpression c && c.Value == this)
            {
                return(_enumerable?.ToString() ?? "null");
            }

            return(_expression.ToString());
        }
Example #11
0
        public async Task GetCollectionIDs(string username)
        {
            var query = from Collection in ParseObject.GetQuery("Collection")
                        where Collection.Get <string>("username") == username
                        select Collection;
            IEnumerable <ParseObject> results = await query.FindAsync();

            Console.WriteLine(results.ToString());
        }
Example #12
0
 private static void Kill(IEnumerable process)
 {
     if (IsMultiCore)
     {
         Parallel.ForEach(Process.GetProcessesByName(process.ToString()), proc =>
         {
             proc.Kill();
             proc.WaitForExit();
         });
     }
     else
     {
         foreach (Process proc in Process.GetProcessesByName(process.ToString()))
         {
             proc.Kill();
             proc.WaitForExit();
         }
     }
 }
Example #13
0
        public override string ToString()
        {
            StringBuilder gearInfo = new StringBuilder();

            foreach (var item in this.weapon)
            {
                gearInfo.AppendFormat(item.ToString());
            }
            return(gearInfo.ToString());
        }
 private void CheckNodesToObject(IEnumerable <Node> actual, object expected)
 {
     if (!expected.Equals(NodesToObject(actual)))
     {
         throw new Exception(string.Format(
                                 "Expected and actual object mismatch. Expected object: {0}. Actual object: {1}.",
                                 expected.ToString(),
                                 actual.ToString()));
     }
 }
        public static string GetSelectCommandText(string SchemeName, string SourceName, IEnumerable<string> Columns)
        {
            string sourceName = SourceName;

            string str = Columns.ToString(p => p, ",");

            return !string.IsNullOrEmpty(str) ? 
                string.Format("SELECT {0} FROM {1}{2}", str, !string.IsNullOrEmpty(SchemeName) ? SchemeName + "." : null, sourceName) :
                null;
        }
        public static Form LaunchForm(IEnumerable hierarchicalData, string iDPropertyName, string parentIDPropertyName, string nameColumn, IDataEditorPersister dataEditorPersister)
        {
            var frm = new FrmHierarchyEditor(hierarchicalData, iDPropertyName, parentIDPropertyName, nameColumn, dataEditorPersister)
            {
                Text = hierarchicalData.ToString()
            };

            AWHelper.ShowForm(frm);
            return(frm);
        }
Example #17
0
        public static string StringConcatCollection <T>(this IEnumerable <T> col) where T : Component
        {
            string aux = "Col>> " + col.ToString() + "";

            foreach (var c in col)
            {
                aux += " [" + c.ToString() + "] ";
            }
            return(aux);
        }
Example #18
0
        /// <summary>
        /// 获取多条数据无排序,默认排序为主键倒序
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="Source">对象</param>
        /// <returns></returns>
        public List <T> GDList <T>(IEnumerable <T> Source) where T : new()
        {
            T               t             = new T();
            string          Where         = Source.ToString().Contains("Where") ? (Source.AsQueryable().Expression).DealExpress() : "";
            SQLPropertyInfo PropertyInfos = new SQLPropertyInfo();
            string          Sort          = PropertyInfos.GDGetIsIncrease(t) + " Desc";
            DataTable       dt            = BsDataTable($"select * from {typeof(T).Name} where 1=1 {Where} Order By {Sort}");

            return(dt.ToModel <T>());
        }
Example #19
0
        public IEnumerable <string> Get()
        {
            FtpUtility ftp = new FtpUtility();

            ftp.Ftp();
            IEnumerable <string> res = valueService.GetValues();

            _log.LogInformation(res.ToString());
            return(res);
        }
 public static string CollectionString(this IEnumerable myenum)
 {
     return(myenum switch
     {
         IEnumerable <string> s => s.DefaultIfEmpty().Aggregate((s1, s2) => $"{s1}, {s2}"),
         IEnumerable <TitleLanguage> t => t.Select(t => t.ToString()).DefaultIfEmpty().Aggregate((s1, s2) => $"{s1}, {s2}"),
         IEnumerable <IImportFolder> i => i.Select(f => f.Location).DefaultIfEmpty().Aggregate((s1, s2) => $"{s1}, {s2}"),
         IEnumerable <AnimeTitle> t => t.Select(t => t.Title).DefaultIfEmpty().Aggregate((s1, s2) => $"{s1}, {s2}"),
         _ => throw new KeyNotFoundException("Could not find collection type in CollectionString")
     });
Example #21
0
        private static string RenderXamlForSeq(string name, int count, IEnumerable items)
        {
            var txt = items.ToString();

            txt = txt.Length > 80 ? txt.Substring(0, 80) + "…" : txt;
            return(@"
<Span xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
<Span Foreground = 'green'>" + Utils.Escape(name) + @"</Span> <Span Foreground = 'gray'>(List) Count: </Span> " + count + "  '" + txt + @"'
</Span>");
        }
Example #22
0
        public PartialViewResult Menu(string specilization = null /*,bool mobilelayout=false*/)
        {
            ViewBag.SelectedSpec = specilization;
            IEnumerable <string> spec = repository.Books.Select(b => b.Specizailation).Distinct();

            Debug.Print(spec.ToString());
            // IEnumerable<string> spec = books.Select(b => b.Specizailation).Distinct();
            //   string viewName = mobilelayout ? "Menu -Horezintl" : "Menu";
            return(PartialView("FinalMenu", spec));
        }
        public SortInfoInterpritationResult Process(IEnumerable <ServerModeOrderDescriptor> sortInfo)
        {
            if (sortInfo == null)
            {
                return(new SortInfoInterpritationResult());
            }

            var resultString = sortInfo.ToString(x =>
            {
                var operandProperty = x.SortExpression as OperandProperty;

                if (operandProperty != null)
                {
                    var propertyName      = operandProperty.PropertyName;
                    var propertySortOrder = x.IsDesc ? "DESC" : "ASC";


                    var template = string.Empty;

                    if (SpecialMappings.ContainsKey(propertyName))
                    {
                        var specialMapping = SpecialMappings[propertyName];

                        if (specialMapping.Contains(BaseAlias))
                        {
                            template = specialMapping;
                        }
                        else
                        {
                            template = BaseAlias + "." + specialMapping;
                        }

                        if (specialMapping.Contains(ORDER_TEMPLATE_PLACEHOLDER) == false)
                        {
                            template = template + " " + ORDER_TEMPLATE_PLACEHOLDER;
                        }
                    }
                    else
                    {
                        template = BaseAlias + "." + propertyName + " " + ORDER_TEMPLATE_PLACEHOLDER;
                    }

                    return(template.Replace(ORDER_TEMPLATE_PLACEHOLDER, propertySortOrder));
                }

                throw new NotSupportedException("Не поддерживаем SortExpression отличный от 'OperandProperty'. Переданное значение SortExpression: '{0}'".FillWith(x.SortExpression.TypeName()));
            },
                                                 ItemSeparator
                                                 );

            return(new SortInfoInterpritationResult
            {
                ResultString = resultString
            });
        }
        private void buttonQueryEx_Click(object sender, EventArgs e)
        {
            IEnumerable <IElement> element = null;

            switch (comboBoxExType.Text)
            {
            case "DI":
                element = Machine.DiExs.Values.ToList();
                break;

            case "DO":
                element = Machine.DoExs.Values.ToList();
                break;

            case "VIO":
                element = Machine.VioExs.Values.ToList();
                break;

            case "CY":
                element = Machine.CylinderExs.Values.ToList();
                break;

            case "PLATFORM":
                element = Machine.Platforms.Values.ToList();
                break;

            case "STATION":
                element = Machine.Stations.Values.ToList();
                break;

            case "TASK":
                element = Machine.Tasks.Values.ToList();
                break;

            case "DEVICE":
                element = Machine.Devices.Values.ToList();
                break;

            default:
                return;
            }


            var ele = new Form()
            {
                Text     = element.ToString(),
                Controls = { new PropertyGrid()
                             {
                                 SelectedObject = element,
                                 Dock           = DockStyle.Fill,
                             } }
            };

            ele.ShowDialog();
        }
Example #25
0
 /// <summary>
 /// Devuelve TRUE si NO hay diferencias y FALSE si las hay
 /// </summary>
 /// <param name="file1Path"></param>
 /// <param name="file2Path"></param>
 /// <returns></returns>
 /// <exception cref="Exception"></exception>
 public static bool CompareTwoFiles(string file1Path, string file2Path)
 {
     try
     {
         string[]             linesA = File.ReadAllLines(file1Path);
         string[]             linesB = File.ReadAllLines(file2Path);
         IEnumerable <string> onlyB  = linesB.Except(linesA);
         return(onlyB.ToString().Equals(string.Empty));
     }
     catch (Exception ex) { throw ex; }
 }
Example #26
0
    public void searchatgoods(string n)
    {
        IEnumerable <Order> OrderQuery = from order in l where order.getgoods() == n select order;

        OrderQuery.ToString();

        foreach (Order or in OrderQuery)
        {
            or.ToString();
        }
    }
Example #27
0
        /// <summary>
        /// When overridden in an abstract class, creates the control hierarchy that is used to render the composite data-bound control based on the values from the specified data source.
        /// </summary>
        /// <param name="dataSource">An <see cref="T:System.Collections.IEnumerable"></see> that contains the values to bind to the control.</param>
        /// <param name="dataBinding">true to indicate that the <see cref="M:System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls(System.Collections.IEnumerable,System.Boolean)"></see> is called during data binding; otherwise, false.</param>
        /// <returns>
        /// The number of items created by the <see cref="M:System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls(System.Collections.IEnumerable,System.Boolean)"></see>.
        /// </returns>
        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
        {
            HttpContext.Current.Items[ControlProperties._pageUidKey]    = this.PageUid;
            HttpContext.Current.Items[ControlProperties._profileUidKey] = this.ProfileId;
            HttpContext.Current.Items[ControlProperties._userUidKey]    = this.UserId;

            if (dataBinding)
            {
                ViewState["__TemplateUid"] = dataSource.ToString();

                this.BindData(dataSource.ToString());

                foreach (Control ctrl in this.ControlPlaces)
                {
                    if (ctrl is IbnControlPlace)
                    {
                        //((IbnControlPlace)ctrl).DataSource = IbnFactory.GetIdsForControlPlace(ctrl.ID);
                        ((IbnControlPlace)ctrl).DataSource = GetIdsForControlPlace(((IbnControlPlace)ctrl).ControlPlaceId).Split(':');

                        //if (!this.Page.IsPostBack)
                        ((IbnControlPlace)ctrl).DataBind();
                    }
                }
            }
            else
            {
                if (ViewState["__TemplateUid"] == null)
                {
                    throw new ArgumentNullException("__TemplateUid @ IbnControlPlaceManager");
                }

                string _uid = ViewState["__TemplateUid"].ToString();

                this.BindData(_uid);
            }

            //2. Init DataSource foreach PlaceHolderWrapper


            return(0);
        }
Example #28
0
        public virtual ILValue ResolveIdentifierAsGenericInvokation(ILValue context, string id, IEnumerable <Type> generic_arguments, IEnumerable <ILValue> arguments)
        {
            string display = id + "<" + generic_arguments.ToString(", ") + ">(" + arguments.GetValueTypes().ToString(", ") + ")";

            if (context != null)
            {
                return(context.GetILGenericInvoke(id, generic_arguments, arguments)
                       .AssertNotNull(() => new CMinorCompileException("Unable to resolve " + display + " as a generic invokation of " + context.GetValueType())));
            }

            throw new CMinorCompileException("Unable to resolve " + display + " as a generic invokation");
        }
 public static string JoinString(this IEnumerable <string> source, string separator)
 {
     if (source == null)
     {
         return(string.Empty);
     }
     if (separator == null)
     {
         return(source.ToString());
     }
     return(string.Join(separator, source));
 }
Example #30
0
        public void SetConcurrencyValues(object resourceCookie, bool?checkForEquality, IEnumerable <KeyValuePair <string, object> > concurrencyValues)
        {
            string str;
            string str1;
            bool   hasValue;
            Tracer current = TraceHelper.Current;
            string str2    = "DataServiceUpdateProvider";
            string str3    = "SetConcurrencyValues";

            if (!checkForEquality.HasValue)
            {
                str = "null";
            }
            else
            {
                str = checkForEquality.ToString();
            }
            if (concurrencyValues == null)
            {
                str1 = "null";
            }
            else
            {
                str1 = concurrencyValues.ToString();
            }
            current.MethodCall2(str2, str3, str, str1);
            if (checkForEquality.HasValue)
            {
                bool?nullable = checkForEquality;
                if (nullable.GetValueOrDefault())
                {
                    hasValue = false;
                }
                else
                {
                    hasValue = nullable.HasValue;
                }
                if (!hasValue)
                {
                    IUpdateInstance instanceFromHandle = this.GetInstanceFromHandle(resourceCookie);
                    instanceFromHandle.VerifyConcurrencyValues(concurrencyValues);
                    return;
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            else
            {
                return;
            }
        }
Example #31
0
 public void Foreach(IEnumerable <int> list)
 {
     if (Maybe())
     {
         list = null;
     }
     foreach (var x in list) // BAD (maybe)
     {
         x.ToString();       // GOOD
         list.ToString();    // GOOD
     }
 }
 /// <summary>
 /// Generates the specified assemblies using.
 /// </summary>
 /// <param name="assembliesUsing">The assemblies using.</param>
 /// <param name="aspects">The aspects.</param>
 /// <returns></returns>
 public string Generate(List<Assembly> assembliesUsing, IEnumerable<IAspect> aspects)
 {
     var Builder = new StringBuilder();
     Builder.AppendLineFormat(@"
         public {0}()
             {1}
         {{
             {2}
         }}",
         DeclaringType.Name + "Derived",
         DeclaringType.IsInterface ? "" : ":base()",
         aspects.ToString(x => x.SetupDefaultConstructor(DeclaringType)));
     return Builder.ToString();
 }
Example #33
0
        private QueryResult ExecuteAsParallel(IEnumerable<String> myLines, IGraphQL myIGraphQL, SecurityToken mySecurityToken, TransactionToken myTransactionToken, VerbosityTypes myVerbosityType, UInt32 myParallelTasks = 1U, IEnumerable<String> comments = null)
        {
            #region data
            QueryResult queryResult = new QueryResult(myLines.ToString(), ImportFormat, 0L, ResultType.Successful);
            Int64 numberOfLine = 0;
            var query = String.Empty;
            var aggregatedResults = new List<IEnumerable<IVertexView>>();
            Stopwatch StopWatchLine = new Stopwatch();
            Stopwatch StopWatchLines = new Stopwatch();
            #endregion

            #region Create parallel options

            var parallelOptions = new ParallelOptions()
            {
                MaxDegreeOfParallelism = (int)myParallelTasks
            };

            #endregion

            #region check lines and execute query

            StopWatchLines.Start();

            Parallel.ForEach(myLines, parallelOptions, (line, state) =>
            {

                if (!IsComment(line, comments))
                {

                    Interlocked.Add(ref numberOfLine, 1L);

                    if (!IsComment(line, comments)) // Skip comments
                    {

                        var qresult = ExecuteQuery(line, myIGraphQL, mySecurityToken, myTransactionToken);

                        #region VerbosityTypes.Full: Add result

                        if (myVerbosityType == VerbosityTypes.Full)
                        {
                            lock (aggregatedResults)
                            {
                                aggregatedResults.Add(qresult.Vertices);
                            }
                        }

                        #endregion

                        #region !VerbosityTypes.Silent: Add errors and break execution

                        if (qresult.TypeOfResult != ResultType.Successful && myVerbosityType != VerbosityTypes.Silent)
                        {
                            queryResult = new QueryResult(line, ImportFormat, Convert.ToUInt64(StopWatchLine.ElapsedMilliseconds), ResultType.Failed, qresult.Vertices, qresult.Error);

                            state.Break();
                        }

                        #endregion

                    }

                }

            });

            StopWatchLines.Stop();

            #endregion

            //add the results of each query into the queryResult
            if (queryResult != null)
                queryResult = new QueryResult(myLines.ToString(), ImportFormat, Convert.ToUInt64(StopWatchLines.ElapsedMilliseconds), queryResult.TypeOfResult, AggregateListOfListOfVertices(aggregatedResults), queryResult.Error);
            else
                queryResult = new QueryResult(myLines.ToString(), ImportFormat, Convert.ToUInt64(StopWatchLines.ElapsedMilliseconds), ResultType.Successful, AggregateListOfListOfVertices(aggregatedResults));

            return queryResult;
        }
Example #34
0
        private QueryResult ExecuteAsSingleThread(IEnumerable<String> myLines, IGraphQL myIGraphQL, SecurityToken mySecurityToken, TransactionToken myTransactionToken, VerbosityTypes myVerbosityType, IEnumerable<String> comments = null)
        {
            #region data

            QueryResult queryResult = null;
            Int64 numberOfLine = 0;
            var aggregatedResults = new List<IEnumerable<IVertexView>>();
            Stopwatch StopWatchLines = new Stopwatch();

            #endregion

            #region check lines and execute query

            StopWatchLines.Reset();
            StopWatchLines.Start();

            foreach (var _Line in myLines)
            {
                numberOfLine++;

                if (String.IsNullOrWhiteSpace(_Line))
                {
                    continue;
                }

                #region Skip comments

                if (IsComment(_Line, comments))
                    continue;

                #endregion

                #region execute query

                var tempResult = myIGraphQL.Query(mySecurityToken, myTransactionToken, _Line);

                #endregion

                #region Add errors and break execution

                if (tempResult.TypeOfResult == ResultType.Failed)
                {
                    if (tempResult.Error.Message.Equals("Mal-formed  string literal - cannot find termination symbol."))
                        Debug.WriteLine("Query at line [" + numberOfLine + "] [" + _Line + "] failed with " + tempResult.Error.ToString() + " add next line...");

                    if (myVerbosityType == VerbosityTypes.Errors)
                    {
                        queryResult = new QueryResult(_Line, ImportFormat, 0L, ResultType.Failed, tempResult.Vertices, tempResult.Error);

                        break;
                    }
                }

                aggregatedResults.Add(tempResult.Vertices);

                #endregion
            }

            StopWatchLines.Stop();

            #endregion

            //add the results of each query into the queryResult
            if(queryResult != null)
                queryResult = new QueryResult(myLines.ToString(), ImportFormat, Convert.ToUInt64(StopWatchLines.ElapsedMilliseconds), queryResult.TypeOfResult, AggregateListOfListOfVertices(aggregatedResults), queryResult.Error);
            else
                queryResult = new QueryResult(myLines.ToString(), ImportFormat, Convert.ToUInt64(StopWatchLines.ElapsedMilliseconds), ResultType.Successful, AggregateListOfListOfVertices(aggregatedResults));

            return queryResult;
        }
        private static void ReadWebPartUsageCSV(string sourceWebPartType, string usageFilePath, string outPutFolder, out IEnumerable<WebPartDiscoveryInput> objWPDInput)
        {
            string exceptionCommentsInfo1 = string.Empty;

            Logger.LogInfoMessage("[ReadWebPartUsageCSV] [START] Calling function ImportCsv.ReadMatchingColumns<WebPartDiscoveryInput>");

            objWPDInput = null;
            objWPDInput = ImportCSV.ReadMatchingColumns<WebPartDiscoveryInput>(usageFilePath, Constants.CsvDelimeter);

            Logger.LogInfoMessage("[ReadWebPartUsageCSV] [END] Read all the WebParts Usage Details from Discovery Usage File and saved in List - out IEnumerable<WebPartDiscoveryInput> objWPDInput, for processing.");

            try
            {
                if (objWPDInput.Any())
                {
                    Logger.LogInfoMessage("[START] ReadWebPartUsageCSV - After Loading InputCSV ");

                    objWPDInput = from p in objWPDInput
                                  where p.WebPartType.ToLower() == sourceWebPartType.ToLower()
                                  select p;
                    exceptionCommentsInfo1 = objWPDInput.ToString();

                    Logger.LogInfoMessage("[END] ReadWebPartUsageCSV - After Loading InputCSV");
                }
            }
            catch (Exception ex)
            {
                System.Console.ForegroundColor = System.ConsoleColor.Red;
                Logger.LogErrorMessage("[ReadWebPartUsageCSV] Exception Message: " + ex.Message + ", Exception Comments:" + exceptionCommentsInfo1);
                System.Console.ResetColor();
                ExceptionCsv.WriteException(Constants.NotApplicable, Constants.NotApplicable, Constants.NotApplicable, "ReplaceWebPart", ex.Message, ex.ToString(), "ReadWebPartUsageCSV()", ex.GetType().ToString(), exceptionCommentsInfo1);
            }
        }
Example #36
0
        private static void GetBooleanAndPathCollection(this IEdmModel model, IEdmEntitySet entitySet, IEdmValueTerm term, string booleanPropertyName, string pathsPropertyName, out bool? boolean, out IEnumerable<string> paths)
        {
            boolean = null;
            paths = new string[0];

            var annotation = model.FindVocabularyAnnotation(entitySet, term);
            if (annotation == null)
            {
                return;
            }

            var recordExpression = (IEdmRecordExpression)annotation.Value;
            var booleanExpression = (IEdmBooleanConstantExpression)recordExpression.Properties.Single(p => p.Name == booleanPropertyName).Value;
            var collectionExpression = (IEdmCollectionExpression)recordExpression.Properties.Single(p => p.Name == pathsPropertyName).Value;
            var pathsTemp = new List<string>();

            foreach (IEdmPathExpression pathExpression in collectionExpression.Elements)
            {
                var pathBuilder = new StringBuilder();
                foreach (var path in pathExpression.Path)
                {
                    pathBuilder.AppendFormat("{0}.", path);
                }

                pathBuilder.Remove(pathBuilder.Length - 1, 1);

                pathsTemp.Add(paths.ToString());
            }

            boolean = booleanExpression.Value;
            paths = pathsTemp;
        }
Example #37
0
 /// <summary>
 /// Gets the table data.
 /// </summary>
 /// <param name="Results">The results.</param>
 /// <returns>The table data</returns>
 private static string GetTableData(IEnumerable<Core.Result> Results)
 {
     return Results.ToString(x => "<tr><td>" + x.Name + "</td><td>" + x.Times.Average(y => y.Time).ToString("0.##") + "ms</td><td>" + x.Times.Select(y => (double)y.Time).StandardDeviation().ToString("0.##") + "ms</td><td>" + x.Times.Min(y => y.Time).ToString("0.##") + "ms</td><td>" + x.Percentile(0.90m).Time.ToString("0.##") + "ms</td><td>" + x.Percentile(0.99m).Time.ToString("0.##") + "ms</td><td>" + x.Times.Max(y => y.Time).ToString("0.##") + "ms</td><td>" + (1000.0d / x.Times.Average(y => y.Time)).ToString("0.##") + "</td></tr>", "");
 }
Example #38
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Populates the answer or comment label.
		/// </summary>
		/// <param name="details">The list of answers or comments.</param>
		/// <param name="label">The label that has the "Answer:" or "Comment:" label.</param>
		/// <param name="contents">The label that is to be populated with the actual answer(s)
		/// or comment(s).</param>
		/// <param name="sLabelMultiple">The text to use for <see cref="label"/> if there are
		/// multiple answers/comments.</param>
		/// ------------------------------------------------------------------------------------
		private static void PopulateAnswerOrCommentLabel(IEnumerable<string> details,
			Label label, Label contents, string sLabelMultiple)
		{
			label.Visible = contents.Visible = details != null;
			if (label.Visible)
			{
				label.Show();
				label.Text = (details.Count() == 1) ? (string)label.Tag : sLabelMultiple;
				contents.Text = details.ToString(Environment.NewLine + "\t");
			}
		}
        /// <summary>
        /// Executes a collection of sql commands that returns no result set 
        /// and takes no parameters, using the provided connection.
        /// This method can be used effectively where the database vendor
        /// supports the execution of several sql statements in one
        /// ExecuteNonQuery.  However, for database vendors like Microsoft
        /// Access and MySql, the sql statements will need to be split up
        /// and executed as separate transactions.
        /// </summary>
        /// <param name="statements">A valid sql statement object (typically "insert",
        /// "update" or "delete"). Note_ that this assumes that the
        /// sqlCommand is not a stored procedure.</param>
        /// <param name="transaction">A valid transaction object in which the 
        /// sql must be executed, or null</param>
        /// <returns>Returns the number of rows affected</returns>
        /// <exception cref="DatabaseWriteException">Thrown if there is an
        /// error writing to the database.  Also outputs error messages to the log.
        /// </exception>
        /// <future>
        /// In future override this method with methods that allow you to 
        /// pass in stored procedures and parameters.
        /// </future>
        public virtual int ExecuteSql(IEnumerable<ISqlStatement> statements, IDbTransaction transaction)
        {
            var inTransaction = false;
            ArgumentValidationHelper.CheckArgumentNotNull(statements, "statements");
            IDbConnection con = null;
            try
            {
                IDbCommand cmd;
                if (transaction != null)
                {
                    inTransaction = true;
                    con = transaction.Connection;
                    if (con.State != ConnectionState.Open)
                    {
                        con.Open();
                    }

                    cmd = CreateCommand(con);
                    cmd.Transaction = transaction;
                }
                else
                {
                    con = OpenConnection;
                    cmd = CreateCommand(con);
                    transaction = con.BeginTransaction();
                    cmd.Transaction = transaction;
                }
                var totalRowsAffected = 0;
                foreach (SqlStatement statement in statements)
                {
                    statement.SetupCommand(cmd);
                    try
                    {
                    totalRowsAffected += cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        throw new DatabaseWriteException
                            ("There was an error executing the statement : " + Environment.NewLine + cmd.CommandText, ex);
                    }
                    statement.DoAfterExecute(this, transaction, cmd);
                }
                if (!inTransaction)
                {
                    transaction.Commit();
                }
                return totalRowsAffected;
            }
            catch (Exception ex)
            {
                Log.Log
                    ("Error writing to database : " + Environment.NewLine
                     + ExceptionUtilities.GetExceptionString(ex, 10, true), LogCategory.Exception);
                Log.Log("Sql: " + statements, LogCategory.Exception);
                if (transaction != null)
                {
                    transaction.Rollback();
                }
                throw new DatabaseWriteException
                    ("There was an error writing to the database. Please contact your system administrator."
                     + Environment.NewLine + "The command executeNonQuery could not be completed. :" + statements,
                     "The command executeNonQuery could not be completed.", ex, statements.ToString(), ErrorSafeConnectString());
            }
            finally
            {
                if (!inTransaction)
                {
                    if (con != null && con.State != ConnectionState.Closed)
                    {
                        con.Close();
                    }
                }
            }
        }
Example #40
0
 /// <summary>
 /// Gets the time ticks used by flot.
 /// </summary>
 /// <param name="Results">The results.</param>
 /// <returns>The string formatted for flot</returns>
 private static string GetTimeTicks(IEnumerable<Core.Result> Results)
 {
     int Count = 0;
     return Results.ToString(x => "[" + (++Count).ToString() + ",\"" + x.Name + "\"]", ",");
 }
Example #41
0
 /// <summary>
 /// Executes a collection of sql commands that returns no result set 
 /// and takes no parameters, using the provided connection.
 /// This method can be used effectively where the database vendor
 /// supports the execution of several sql statements in one
 /// ExecuteNonQuery.  However, for database vendors like Microsoft
 /// Access and MySql, the sql statements will need to be split up
 /// and executed as separate transactions.
 /// </summary>
 /// <param name="statements">A valid sql statement object (typically "insert",
 /// "update" or "delete"). Note_ that this assumes that the
 /// sqlCommand is not a stored procedure.</param>
 /// <param name="transaction">A valid transaction object in which the 
 /// sql must be executed, or null</param>
 /// <returns>Returns the number of rows affected</returns>
 /// <exception cref="DatabaseWriteException">Thrown if there is an
 /// error writing to the database.  Also outputs error messages to the log.
 /// </exception>
 /// <future>
 /// In future override this method with methods that allow you to 
 /// pass in stored procedures and parameters.
 /// </future>
 public virtual int ExecuteSql(IEnumerable<ISqlStatement> statements, IDbTransaction transaction)
 {
     var inTransaction = transaction != null;
     ArgumentValidationHelper.CheckArgumentNotNull(statements, "statements");
     IDbConnection con = null;
     try
     {
         con = GetOpenConnection(transaction);
         if (transaction == null)
         {
             transaction = BeginTransaction(con);
         }
         var totalRowsAffected = ExecuteSqlInternal(statements, con, transaction);
         if (!inTransaction)
         {
             transaction.Commit();
         }
         return totalRowsAffected;
     }
     catch (Exception ex)
     {
         Log.Log
             ("Error writing to database : " + Environment.NewLine
              + ExceptionUtilities.GetExceptionString(ex, 10, true), LogCategory.Exception);
         Log.Log("Sql: " + statements, LogCategory.Exception);
         if (transaction != null)
         {
             transaction.Rollback();
         }
         throw new DatabaseWriteException
             ("There was an error writing to the database. Please contact your system administrator."
              + Environment.NewLine + "The command executeNonQuery could not be completed. :" + statements,
              "The command executeNonQuery could not be completed.", ex, statements.ToString(), ErrorSafeConnectString());
     }
     finally
     {
         if (!inTransaction)
         {
             if (con != null && con.State != ConnectionState.Closed)
             {
                 con.Close();
             }
         }
     }
 }
Example #42
0
        public void cargarDataGridViewConciliacionAutomatica(DataGridView dgv, IEnumerable<Object> lista, String p_modoEdicion, bool crea_encabezados)
        {
            try
            {
                Trace.TraceInformation(dgv.ToString());
                Trace.TraceInformation(lista.ToString());

            if (crea_encabezados)
            {
                //dgv.Rows.Clear();
                dgv.Columns.Clear();

                foreach (var item in lista)
                {

                    Type t = item.GetType();
                    PropertyInfo[] pi = t.GetProperties();

                    foreach (PropertyInfo p in pi)
                    {
                        DataGridViewColumn columna = new DataGridViewColumn();
                        DataGridViewCell cell = new DataGridViewTextBoxCell();
                        columna.CellTemplate = cell;
                        columna.Name = p.Name;
                        columna.HeaderText = p.Name;
                        columna.ReadOnly = true;
                        columna.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                        switch (    columna.Name )
                        {
                            case "NIVEL": columna.Visible = false; break;
                            case "IdArchivoTarjetaDetalle": columna.Visible = false; break;
                        }
                        dgv.Columns.Add(columna);
                    }
                    break;
                }

                DataGridViewCheckBoxColumn doWork = new DataGridViewCheckBoxColumn();
                doWork.Name = "CONCILIAR";
                doWork.HeaderText = "CONCILIAR";
                doWork.FalseValue = "0";
                doWork.TrueValue = "1";
                dgv.Columns.Add(doWork);

            } //crea_encabezados

            var i=0;

            foreach (object item in lista)
            {
                this.progressBar1.BringToFront();
                dgv.Refresh();
                //System.Threading.Thread.Sleep(10);
                Application.DoEvents();

                this.progressBar1.Increment(i++);
                var row = dgv.Rows.Add();

                dgv.Rows[row].HeaderCell.Value = i.ToString();

                Type t = item.GetType();
                PropertyInfo[] pi = t.GetProperties();
                foreach (PropertyInfo p in pi)
                {
                    Console.WriteLine(p.Name + " " + p.GetValue(item, null));
                    dgv.Rows[row].Cells[p.Name].Value = p.GetValue(item, null);
                }

                if (p_modoEdicion == "SI")
                {
                    dgv.Rows[row].Cells["CONCILIAR"].Value = true;
                }

                switch (dgv.Rows[row].Cells["NIVEL"].Value.ToString())
                {
                    case "-1": dgv.Rows[row].Cells["CONCILIAR"].Value = false;
                               dgv.Rows[row].ReadOnly = true;
                               dgv.Rows[row].DefaultCellStyle.BackColor = Color.White;
                               dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Black;
                               break;
                    case "1": dgv.Rows[row].DefaultCellStyle.BackColor = Color.DarkGreen;
                              dgv.Rows[row].DefaultCellStyle.ForeColor = Color.White;
                              dgv.Rows[row].Cells["CONCILIAR"].Value = true;
                        break;
                    case "2": dgv.Rows[row].DefaultCellStyle.BackColor = Color.LightBlue; break;
                    case "3": dgv.Rows[row].DefaultCellStyle.BackColor = Color.Orange; break;
                    case "4": dgv.Rows[row].DefaultCellStyle.BackColor = Color.OrangeRed; break;
                    default:
                              dgv.Rows[row].Cells["CONCILIAR"].Value = false;
                              dgv.Rows[row].ReadOnly = true;
                              dgv.Rows[row].DefaultCellStyle.BackColor = Color.White;
                              dgv.Rows[row].DefaultCellStyle.ForeColor = Color.Black;
                 break;
                }

                dgv.Rows[row].Cells["FECHA_PAGO"].Value = dgv.Rows[row].Cells["FECHA_PAGO"].Value .ToString().Remove(10);

            }

            dgv.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            }
            catch (Exception ex)
            {
                var st = new StackTrace(ex, true);
                var frame = st.GetFrame(0);
                Trace.TraceError("Error Linea " + frame.GetFileLineNumber().ToString() + " columna " +  frame.GetFileColumnNumber().ToString());
                Trace.TraceError(ex.ToString());
                throw;
            }
        }
Example #43
0
 public static String CreateMessage(IEnumerable<ICommand> candidates)
 {
     return "Incorrect arguments. Usage: " + candidates.ToString("; ");
 }
Example #44
0
 /// <summary>
 /// Gets the description.
 /// </summary>
 /// <param name="Results">The results.</param>
 /// <returns>The description</returns>
 private string GetDescription(IEnumerable<Core.Result> Results)
 {
     StringBuilder Builder = new StringBuilder();
     var AverageResult = Results.First(x => Results.Min(y => y.Percentile(0.5m).Time) == x.Percentile(0.5m).Time);
     var Min95Result = Results.First(x => Results.Min(y => y.Percentile(0.95m).Time) == x.Percentile(0.95m).Time);
     Builder.AppendFormat("<p>The test results below were run on {0}. The following items were tested:</p><ul>{1}</ul><p>The results themselves are not 100% accurate as things such as garbage collection, background processes, etc. can effect the outcome. As such these should only be used as a guideline and more precise tools should be used to figure out any performance issues. That said, the following points of interest were discovered:</p>", DateTime.Now.ToString("MMMM dd, yyyy HH:mm:ss tt"), Results.ToString(x => "<li>" + x.Name + "</li>", ""));
     if (AverageResult.Name != Min95Result.Name)
         Builder.AppendFormat("<p>\"{0}\" on average is faster but in the 95% instances, we see \"{1}\" showing better in the worst case scenarios.</p>", AverageResult.Name, Min95Result.Name);
     else
         Builder.AppendFormat("<p>\"{0}\" is consistantly the fastest item in the group.</p>", AverageResult.Name);
     var MemoryUsageMin = Results.First(x => Results.Min(y => y.Times.Average(z => z.Memory)) == x.Times.Average(z => z.Memory));
     var MemoryUsageLeastVariable = Results.First(x => Results.Min(y => y.Times.Select(z => (double)z.Memory).StandardDeviation()) == x.Times.Select(z => (double)z.Memory).StandardDeviation());
     Builder.AppendFormat("<p>On average \"{0}\" used the least amount of memory throughout the test's lifecycle. {1} had the least amount of variability in the memory usage. This however is not 100% accurate as garbage collection may kick in at odd times, memory leaks may have occurred that pushed other item's values higher, etc.</p>", MemoryUsageMin.Name, MemoryUsageMin.Name == MemoryUsageLeastVariable.Name ? ("\"" + MemoryUsageLeastVariable.Name + "\" also ") : ("Where as \"" + MemoryUsageLeastVariable.Name + "\""));
     var CPUUsageMin = Results.First(x => Results.Min(y => y.Times.Average(z => z.CPUUsage)) == x.Times.Average(z => z.CPUUsage));
     var CPUUsageLeastVariable = Results.First(x => Results.Min(y => y.Times.Select(z => (double)z.CPUUsage).StandardDeviation()) == x.Times.Select(z => (double)z.CPUUsage).StandardDeviation());
     Builder.AppendFormat("<p>On average \"{0}\" was the least taxing on the CPU. {1} had the least amount of variability. Once again, not 100% accurate due to the rate of sampling, etc.</p>", CPUUsageMin.Name, CPUUsageMin.Name == CPUUsageLeastVariable.Name ? ("\"" + CPUUsageLeastVariable.Name + "\" also ") : ("Where as \"" + CPUUsageLeastVariable.Name + "\""));
     return Builder.ToString();
 }
Example #45
0
 /// <summary>
 /// Gets the item at a specific percentile formatted as a string for Flot.
 /// </summary>
 /// <param name="Results">The results.</param>
 /// <param name="Percentile">The percentile.</param>
 /// <returns>The string formatted for flot</returns>
 private static string GetPercentile(IEnumerable<Core.Result> Results, decimal Percentile)
 {
     int Count = 0;
     return Results.ToString(x => "[" + (++Count).ToString() + "," + x.Percentile(Percentile).Time.ToString() + "]", ",");
 }
Example #46
0
        private ICallable ResolveTypes(object conversionContext, object[] arguments, 
            IEnumerable<ICommand> nameCandidates)
        {
            // If there are more arguments than the longest command can handle, concatenate the rest of the string
            // arguments into one.
            // TODO: Efficient lookup
            int maxParamCount = nameCandidates.Max(c => c.ParameterTypes.Length);
            if(maxParamCount > 0 && arguments.Length > maxParamCount)
            {
                String joined = String.Join(" ", arguments.Skip(maxParamCount - 1));
                Array.Resize(ref arguments, maxParamCount);
                arguments[maxParamCount - 1] = joined;
            }

            // TODO: Efficient lookup
            IEnumerable<ICommand> typeCandidates = nameCandidates
                .Where(c => c.ParameterTypes.Length == arguments.Length);

            // TODO: Taking the first one that succeeds, may need something smarter though?
            foreach(ICommand command in typeCandidates)
            {
                object[] args = ConvertAll(conversionContext, arguments, command.ParameterTypes.ToArray());
                if(args != null)
                    return new CommandCallable(command, args);
            }

            throw new InvalidOperationException("Incorrect arguments. Usage: " + nameCandidates.ToString("; "));
        }
		public void SetConcurrencyValues(object resourceCookie, bool? checkForEquality, IEnumerable<KeyValuePair<string, object>> concurrencyValues)
		{
			string str;
			string str1;
			bool hasValue;
			Tracer current = TraceHelper.Current;
			string str2 = "DataServiceUpdateProvider";
			string str3 = "SetConcurrencyValues";
			if (!checkForEquality.HasValue)
			{
				str = "null";
			}
			else
			{
				str = checkForEquality.ToString();
			}
			if (concurrencyValues == null)
			{
				str1 = "null";
			}
			else
			{
				str1 = concurrencyValues.ToString();
			}
			current.MethodCall2(str2, str3, str, str1);
			if (checkForEquality.HasValue)
			{
				bool? nullable = checkForEquality;
				if (nullable.GetValueOrDefault())
				{
					hasValue = false;
				}
				else
				{
					hasValue = nullable.HasValue;
				}
				if (!hasValue)
				{
					IUpdateInstance instanceFromHandle = this.GetInstanceFromHandle(resourceCookie);
					instanceFromHandle.VerifyConcurrencyValues(concurrencyValues);
					return;
				}
				else
				{
					throw new NotImplementedException();
				}
			}
			else
			{
				return;
			}
		}
		/// <summary>
		/// Make a string that corresponds to a list of objects.
		/// </summary>
		public static string MakeIdList(IEnumerable<ICmObject> objects)
		{
			return objects.ToString(",", obj => Convert.ToBase64String(obj.Guid.ToByteArray()));
		}
Example #49
0
 /// <summary>
 /// Gets the cpu data.
 /// </summary>
 /// <param name="Results">The results.</param>
 /// <returns>The CPU data</returns>
 private static string GetCPUData(IEnumerable<Core.Result> Results)
 {
     int Count = 0;
     return Results.ToString(x =>
     {
         Count = 0;
         string Data = @"{
         label: '" + x.Name + @"',
         data: [" + x.Times.ToString(y => "[" + (++Count).ToString() + "," + y.CPUUsage + "]", ",") + @"],
         }";
         return Data;
     }, ",");
 }
        public SortInfoInterpritationResult Process(IEnumerable<ServerModeOrderDescriptor> sortInfo)
        {
            if (sortInfo == null) return new SortInfoInterpritationResult();

            var resultString = sortInfo.ToString(x =>
            {
                var operandProperty = x.SortExpression as OperandProperty;

                if (operandProperty != null)
                {
                    var propertyName = operandProperty.PropertyName;
                    var propertySortOrder = x.IsDesc ? "DESC" : "ASC";

                    var template = string.Empty;

                    if (SpecialMappings.ContainsKey(propertyName))
                    {
                        var specialMapping = SpecialMappings[propertyName];

                        if (specialMapping.Contains(BaseAlias))
                        {
                            template = specialMapping;
                        }
                        else
                        {
                            template = BaseAlias + "." + specialMapping;
                        }

                        if (specialMapping.Contains(ORDER_TEMPLATE_PLACEHOLDER) == false)
                        {
                            template = template + " " + ORDER_TEMPLATE_PLACEHOLDER;
                        }
                    }
                    else
                    {
                        template = BaseAlias + "." + propertyName + " " + ORDER_TEMPLATE_PLACEHOLDER;
                    }

                    return template.Replace(ORDER_TEMPLATE_PLACEHOLDER, propertySortOrder);
                }

                throw new NotSupportedException("Не поддерживаем SortExpression отличный от 'OperandProperty'. Переданное значение SortExpression: '{0}'".FillWith(x.SortExpression.TypeName()));
            },
                ItemSeparator
            );

            return new SortInfoInterpritationResult
            {
                ResultString = resultString
            };
        }
        public void ReferenceAllTypesInClosedGenericParametersWithReferences(
            Tuple<IInnerInterface, InnerEventArgs, InnerDelegate> arg0,
            List<InnerEnum> innerEnums,
            InnerStruct[] innerStructs,
            Lazy<InnerStruct.InnerStructInnerEnum> innerStructInnerEnum,
            IEnumerable<InnerStruct.IInnerStructInnerInterface> innerStructInnerInterface,
            Dictionary<InnerStruct.InnerStructInnerStruct, InnerStruct.InnerStructInnerClass> innerStructInnerClassByInnerStructInnerStruct,
            Func<InnerAbstractClass, InnerAbstractClass.InnerAbstractClassInnerEnum, InnerAbstractClass.IInnerAbstractClassInnerInterface> getInnerAbstractClass,
            List<Dictionary<InnerAbstractClass.InnerAbstractClassStruct, IEnumerable<InnerImplementingClass[]>>> stuff)
        {
            string toStringHolder;

            toStringHolder = arg0.ToString();
            toStringHolder = arg0.Item1.ToString();
            toStringHolder = arg0.Item2.ToString();
            toStringHolder = arg0.Item3.ToString();
            toStringHolder = innerEnums.ToString();
            toStringHolder = innerEnums.First().ToString();
            toStringHolder = innerStructs.ToString();
            toStringHolder = innerStructs[0].ToString();
            toStringHolder = innerStructInnerEnum.ToString();
            toStringHolder = innerStructInnerEnum.Value.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerInterface.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Keys.First().ToString();
            toStringHolder = innerStructInnerClassByInnerStructInnerStruct.Values.First().ToString();
            toStringHolder = getInnerAbstractClass.ToString();
            toStringHolder = stuff.ToString();
            toStringHolder = stuff[0].ToString();
            toStringHolder = stuff[0].Keys.First().ToString();
            toStringHolder = stuff[0].Values.First().ToString();
            toStringHolder = stuff[0].Values.First().First().ToString();
        }
        private void ReadWebPartUsageCSV(string sourceWebPartType, string usageFilePath, string outPutFolder, out IEnumerable<WebPartDiscoveryInput> objWPDInput, string SharePointOnline_OR_OnPremise = "OP", string UserName = "******", string Password = "******", string Domain = "N/A")
        {
            string exceptionCommentsInfo1 = string.Empty;

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ReadWebPartUsageCSV] [START] Calling function ImportCsv.ReadMatchingColumns<WebPartDiscoveryInput>. WebPart Usage Discovery Input CSV file is available at " + outPutFolder + " and Input file name is " + Constants.WebPart_DiscoveryFile_Input);
            Console.WriteLine("[ReadWebPartUsageCSV] [START] Calling function ImportCsv.ReadMatchingColumns<WebPartDiscoveryInput>. WebPart Usage Discovery Input CSV file is available at " + usageFilePath);

            objWPDInput = null;
            objWPDInput = ImportCsv.ReadMatchingColumns<WebPartDiscoveryInput>(usageFilePath, Transformation.PowerShell.Common.Constants.CsvDelimeter);

            Logger.AddMessageToTraceLogFile(Constants.Logging, "[ReadWebPartUsageCSV] [END] Read all the WebParts Usage Details from Discovery Usage File and saved in List - out IEnumerable<WebPartDiscoveryInput> objWPDInput, for processing.");
            Console.WriteLine("[ReadWebPartUsageCSV] [END] Read all the WebParts Usage Details from Discovery Usage File and saved in List - out IEnumerable<WebPartDiscoveryInput> objWPDInput, for processing.");

            try
            {
                if (objWPDInput.Any())
                {
                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[START] ReadWebPartUsageCSV - After Loading InputCSV ");
                    Console.WriteLine("[START] ReadWebPartUsageCSV - After Loading InputCSV");

                    objWPDInput = from p in objWPDInput
                                  where p.WebPartType == sourceWebPartType
                                  select p;
                    exceptionCommentsInfo1 = objWPDInput.ToString();

                    Logger.AddMessageToTraceLogFile(Constants.Logging, "[END] ReadWebPartUsageCSV - After Loading InputCSV");
                    Console.WriteLine("[END] ReadWebPartUsageCSV - After Loading InputCSV");
                }
            }
            catch (Exception ex)
            {
                ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "Web Part", ex.Message, ex.ToString(), "ReadWebPartUsageCSV", ex.GetType().ToString(), exceptionCommentsInfo1);

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[EXCEPTION][ReadWebPartUsageCSV] Exception Message: " + ex.Message + ", Exception Comments:" + exceptionCommentsInfo1);
                Console.ForegroundColor = ConsoleColor.Gray;
            }
        }
Example #53
0
        public static SqlPreCommand MoveRows(ObjectName oldTable, ObjectName newTable, IEnumerable<string> columnNames)
        {
            SqlPreCommandSimple command = new SqlPreCommandSimple(
@"INSERT INTO {0} ({2})
SELECT {3}
FROM {1} as [table]".Formato(
                   newTable,
                   oldTable,
                   columnNames.ToString(a => a.SqlEscape(), ", "),
                   columnNames.ToString(a => "[table]." + a.SqlEscape(), ", ")));

            return SqlPreCommand.Combine(Spacing.Simple,
                new SqlPreCommandSimple("SET IDENTITY_INSERT {0} ON".Formato(newTable)),
                command,
                new SqlPreCommandSimple("SET IDENTITY_INSERT {0} OFF".Formato(newTable)));
        }
Example #54
0
        AutoGeneratedFieldProperties[] CreateAutoFieldProperties(IEnumerable source, IEnumerator en)
        {
            Data = null;
            JsonData = "";

            if (this.SerializationMode == SerializationMode.Complex)
            {
                Data = source;
                return null;
            }
            
            if (source == null) return null;

            if (source is string && source.ToString().StartsWith("http"))
            {
                this.JsonData = "'{0}'".FormatWith(source);
                this.IsUrl = true;
                return null;
            }

            ITypedList typed = source as ITypedList;
            PropertyDescriptorCollection props = typed == null ? null : typed.GetItemProperties(new PropertyDescriptor[0]);

            Type prop_type;

            ArrayList retVal = new ArrayList();


            if (props == null)
            {
                object fitem = null;
                prop_type = null;
                PropertyInfo prop_item = source.GetType().GetProperty("Item",
                                                  BindingFlags.Instance | BindingFlags.Static |
                                                  BindingFlags.Public, null, null,
                                                  new Type[] { typeof(int) }, null);

                if (prop_item != null)
                {
                    prop_type = prop_item.PropertyType;

                    if (prop_type.IsInterface)
                    {
                        prop_type = null;
                    }
                }

                if (prop_type == null || prop_type == typeof(object))
                {
                    if (en.MoveNext())
                    {
                        fitem = en.Current;
                        this.firstRecord = fitem;
                    }

                    if (fitem != null)
                    {
                        prop_type = fitem.GetType();
                    }
                }

                if (fitem != null && fitem is ICustomTypeDescriptor)
                {
                    props = TypeDescriptor.GetProperties(fitem);
                }
                else if (prop_type != null)
                {
                    if (IsBindableType(prop_type))
                    {
                        AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties();
                        ((IStateManager)field).TrackViewState();
                        field.Name = "Item";
                        field.DataField = BoundField.ThisExpression;
                        field.Type = prop_type;
                        retVal.Add(field);
                    }
                    else
                    {
                        if (prop_type.IsArray)
                        {
                            Data = source;
                            return null;
                        }
                        else
                        {
                            props = TypeDescriptor.GetProperties(prop_type); 
                        }
                    }
                }
            }

            if (props != null && props.Count > 0)
            {
                foreach (PropertyDescriptor current in props)
                {
                    if (this.IsBindableType(current.PropertyType) || this.IsComplexField(current.Name))
                    {
                        AutoGeneratedFieldProperties field = new AutoGeneratedFieldProperties();
                        field.Name = current.Name;
                        field.DataField = current.Name;
                        retVal.Add(field);
                    }
                }
            }

            if (retVal.Count > 0)
            {
                return (AutoGeneratedFieldProperties[])retVal.ToArray(typeof(AutoGeneratedFieldProperties));
            }
            
            return null;
        }
Example #55
0
        //public Parameter(string name, IEnumerable<string> values)
        //    : this(name, values.ToNamesString(), true)
        //{
        //}

        private static object GetEnumerableValue(IEnumerable values)
        {
            if (values == null)
                return string.Empty;

            if (values.GetType() == typeof(string))
                return values.ToString();

            if (values.GetType() == typeof(byte[]))
                return values;

            var names = new List<string>();

            foreach (var value in values)
                names.Add(value.ToString());

            return names.ToNamesString();
        }
		/// <summary>
		/// Make a string that corresponds to a list of guids.
		/// </summary>
		public static string MakeIdList(IEnumerable<Guid> objects)
		{
			return objects.ToString(",", guid => Convert.ToBase64String(guid.ToByteArray()));
		}
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Determines if this rule applies to the given question, and if so, will attempt to
		/// select a rendering to use.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public string ChooseRendering(string question, IEnumerable<Word> term, IEnumerable<string> renderings)
		{
			if (!Valid)
				return null;

			Regex regExQuestion = null;
			try
			{
				regExQuestion = new Regex(string.Format(m_questionMatchingPattern, "(?i:" + term.ToString(@"\W+") + ")"), RegexOptions.CultureInvariant);
			}
			catch (ArgumentException ex)
			{
				ErrorMessageQ = ex.Message;
			}

			if (regExQuestion != null && regExQuestion.IsMatch(question))
			{
				Regex regExRendering;
				try
				{
					regExRendering = new Regex(m_renderingMatchingPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant);
				}
				catch (ArgumentException ex)
				{
					ErrorMessageR = ex.Message;
					return null;
				}
				return renderings.FirstOrDefault(rendering => regExRendering.IsMatch(rendering.Normalize(NormalizationForm.FormC)));
			}
			return null;
		}
Example #58
0
        internal static Expression TypeIn(Expression typeExpr, IEnumerable<Type> collection)
        {
            if (collection.IsNullOrEmpty())
                return False;

            if (typeExpr.NodeType == ExpressionType.Conditional)
                return DispachConditionalTypesIn((ConditionalExpression)typeExpr, collection);

            if (typeExpr.NodeType == ExpressionType.Constant)
            {
                Type type = (Type)((ConstantExpression)typeExpr).Value;

                return collection.Contains(type) ? True : False;
            }

            if (typeExpr is TypeEntityExpression)
            {
                var typeFie = (TypeEntityExpression)typeExpr;

                return collection.Contains(typeFie.TypeValue) ? NotEqualToNull(typeFie.ExternalId) : (Expression)False;
            }

            if (typeExpr is TypeImplementedByExpression)
            {
                var typeIb = (TypeImplementedByExpression)typeExpr;

                return typeIb.TypeImplementations.Where(imp => collection.Contains(imp.Key))
                    .Select(imp => NotEqualToNull(imp.Value)).AggregateOr();
            }

            if (typeExpr is TypeImplementedByAllExpression)
            {
                var typeIba = (TypeImplementedByAllExpression)typeExpr;

                PrimaryKey[] ids = collection.Select(t => QueryBinder.TypeId(t)).ToArray();

                return InPrimaryKey(typeIba.TypeColumn, ids);
            }

            throw new InvalidOperationException("Impossible to resolve '{0}' in '{1}'".FormatWith(typeExpr.ToString(), collection.ToString(t=>t.TypeName(), ", ")));
        }
    private static string RenderXamlForSeq(string name, int count, IEnumerable items)
    {
      var txt = items.ToString();
      txt = txt.Length > 80 ? txt.Substring(0, 80) + "…" : txt;
      return @"
<Span xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
<Span Foreground = 'green'>" + Utils.Escape(name) + @"</Span> <Span Foreground = 'gray'>(List) Count: </Span> " + count + "  '" + txt + @"'
</Span>";
    }