/// <summary>
        /// A helper method for creating an object that represents a total count
        /// of objects that the cmdlet would return without paging
        /// (this can be more than the size of the page specified in the <see cref="First"/> cmdlet parameter).
        /// </summary>
        /// <param name="totalCount">A total count of objects that the cmdlet would return without paging.</param>
        /// <param name="accuracy">
        /// accuracy of the <paramref name="totalCount"/> parameter.
        /// <c>1.0</c> means 100% accurate;
        /// <c>0.0</c> means that total count is unknown;
        /// anything in-between means that total count is estimated
        /// </param>
        /// <returns>An object that represents a total count of objects that the cmdlet would return without paging.</returns>
        public PSObject NewTotalCount(UInt64 totalCount, double accuracy)
        {
            PSObject result = new PSObject(totalCount);

            string toStringMethodBody = string.Format(
                CultureInfo.CurrentCulture,
                @"
                    $totalCount = $this.PSObject.BaseObject
                    switch ($this.Accuracy) {{
                        {{ $_ -ge 1.0 }} {{ '{0}' -f $totalCount }}
                        {{ $_ -le 0.0 }} {{ '{1}' -f $totalCount }}
                        default          {{ '{2}' -f $totalCount }}
                    }}
                ",
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportAccurateTotalCountTemplate),
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportUnknownTotalCountTemplate),
                CodeGeneration.EscapeSingleQuotedStringContent(CommandBaseStrings.PagingSupportEstimatedTotalCountTemplate));
            PSScriptMethod toStringMethod = new PSScriptMethod("ToString", ScriptBlock.Create(toStringMethodBody));

            result.Members.Add(toStringMethod);

            accuracy = Math.Max(0.0, Math.Min(1.0, accuracy));
            PSNoteProperty statusProperty = new PSNoteProperty("Accuracy", accuracy);

            result.Members.Add(statusProperty);

            return(result);
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> CreateShortcodes([FromBody] CodeGenerationViewModel codeParameters)
        {
            if (ModelState.IsValid)
            {
                Survey survey = await this._unitOfWork.Surveys.GetAsync(codeParameters.SurveyId);

                //Survey survey = codeParameters.NumberOfCodes > 1? await this._unitOfWork.Surveys.GetSurveyWithAllCodesAsync(codeParameters.SurveyId) : await this._unitOfWork.Surveys.GetAsync(codeParameters.SurveyId);
                CodeGeneration codeGenerationParameters = Mapper.Map <CodeGeneration> (codeParameters);
                if (survey.Owner == this.User.Identity.Name || await HasExecuteSurveyPermissions(codeParameters.SurveyId))
                {
                    if (codeGenerationParameters.NumberOfCodes > 1)
                    {
                        this._codeGeneration.GenerateShortCodesBatch(codeGenerationParameters, survey);
                    }
                    else
                    {
                        await this._codeGeneration.GenerateShortCode(codeGenerationParameters, survey);
                    }
                    await this._unitOfWork.SaveChangesAsync();

                    return(new OkResult());
                }
                return(BadRequest("User does not have permissions to execute this survey."));
            }
            return(BadRequest(ModelState));
        }
Ejemplo n.º 3
0
        protected Configuration CreateConfigurationBlock(Config ConfigBlock, string AssemblyName, string OuputType)
        {
            Configuration  ConfObj      = new Configuration();
            CodeGeneration CodeGenObj   = new CodeGeneration();
            Execution      ExecutionObj = new Execution();
            Output         OutputObj    = new Output();

            ConfObj.runwithwarnings = "False";
            ConfObj.name            = ConfigBlock.Name;

            // CodeGenObj member population
            CodeGenObj.runtime                 = "MsNet";
            CodeGenObj.compiler                = "Csc";
            CodeGenObj.warninglevel            = ConfigBlock.WarningLevel;
            CodeGenObj.nowarn                  = "";
            CodeGenObj.includedebuginformation = (ConfigBlock.DebugSymbols == true) ?
                                                 CodeGenerationIncludedebuginformation.True :
                                                 CodeGenerationIncludedebuginformation.False;

            CodeGenObj.optimize = (ConfigBlock.Optimize == true) ? "True" : "False";

            if (ConfigBlock.AllowUnsafeBlocks == true)
            {
                CodeGenObj.unsafecodeallowed = CodeGenerationUnsafecodeallowed.True;
            }
            else
            {
                CodeGenObj.unsafecodeallowed = CodeGenerationUnsafecodeallowed.False;
            }
            if (ConfigBlock.CheckForOverflowUnderflow == true)
            {
                CodeGenObj.generateoverflowchecks = "True";
            }
            else
            {
                CodeGenObj.generateoverflowchecks = "False";
            }

            CodeGenObj.mainclass = "";
            CodeGenObj.target    = OuputType;
            CodeGenObj.generatexmldocumentation = "False";
            CodeGenObj.win32Icon = "";

            // ExecutionObj member population
            ExecutionObj.commandlineparameters = "";
            ExecutionObj.consolepause          = "True";

            // OutputObj member population
            OutputObj.directory          = ConfigBlock.OutputPath;
            OutputObj.assembly           = AssemblyName;
            OutputObj.executeScript      = "";
            OutputObj.executeBeforeBuild = "";
            OutputObj.executeAfterBuild  = "";

            ConfObj.CodeGeneration = CodeGenObj;
            ConfObj.Execution      = ExecutionObj;
            ConfObj.Output         = OutputObj;

            return(ConfObj);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Helper function to generate a list of unique codes for a survey (both short and group)
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="survey"></param>
        /// <returns></returns>
        private List <string> GenerateUniqueCodes(CodeGeneration parameters, Survey survey)
        {
            //Choose method of generation based on parameter
            Func <CodeGeneration, string> codeGenFunction;

            if (parameters.UsePattern)
            {
                codeGenFunction = delegate(CodeGeneration cParams) { return(CodePatternFunction(cParams.Pattern)); };
            }
            else
            {
                codeGenFunction = delegate(CodeGeneration cParams) { return(CodePatternFunction(cParams.Pattern)); };
            }

            List <string> newCodes  = new List <string>();
            bool          allUnique = false;
            int           remainingCodes;

            /// in a loop, generate codes without checking for uniqueness
            /// compare against short code and group codes repo en mass
            /// keep unique codes and continue until number required is generated
            do
            {
                remainingCodes = parameters.NumberOfCodes - newCodes.Count;
                List <string> partialCodes = new List <string>();
                for (int i = 0; i < remainingCodes; i++)
                {
                    string codeString = codeGenFunction(parameters);
                    partialCodes.Add(codeString);
                }
                newCodes  = newCodes.Union(this._unitOfWork.GroupCodes.GetUniqueCodes(survey.Id, this._unitOfWork.Shortcodes.GetUniqueCodes(survey.Id, partialCodes))).ToList();
                allUnique = newCodes.Count == parameters.NumberOfCodes;
            } while (!allUnique);
            return(newCodes);
        }
Ejemplo n.º 5
0
        public void GenerateSourceCode()
        {
            var nameSpace = ResolveNameSpace();

            UnsubscribeTablePresenters();
            Task.Factory.StartNew(() =>
            {
                var selectedTables = GetSelectedTables().ToArray();

                var csharp = CodeGeneration.generateCsharp(selectedTables, nameSpace);

                dispatcher.InvokeAsync(() =>
                {
                    SourceCode = csharp;
                });

                SubscribeTablePresenters();
                if (Tables.Any())
                {
                    Document.Tables = Tables
                                      .Select(t => new TableDocument(t.Table.Name, t.Fields.Where(f => f.Selected).Select(f => f.Field.Name).ToArray()))
                                      .ToArray();

                    Document.SelectedTables = selectedTables.Select(t => t.Name).ToArray();
                    documentStorage.Save(Document, Filename);
                }

                SaveGeneratedCode();
            });
        }
Ejemplo n.º 6
0
        protected override void ProcessRecord()
        {
            if (!MyInvocation.BoundParameters.ContainsKey(nameof(ListItemText)))
            {
                ListItemText = CompletionText;
            }
            if (!MyInvocation.BoundParameters.ContainsKey(nameof(ToolTip)))
            {
                ToolTip = CompletionText;
            }
            string completionText;

            if (DoNotEscape)
            {
                completionText = CompletionText;
            }
            else
            {
                var temp = CodeGeneration.EscapeSingleQuotedStringContent(CompletionText);
                if (temp.Contains(" ") || temp.Contains("'"))
                {
                    completionText = "'" + temp + "'";
                }
                else
                {
                    completionText = temp;
                }
            }
            WriteObject(new CompletionResult(completionText, ListItemText, ResultType, ToolTip));
        }
        public void CodeGeneration_PerformanceTest() {
            var sw = new Stopwatch();
            sw.Start();
            var func = CodeGeneration.GetVectorMultiplyFunction<int>();
            sw.Stop();

            Console.WriteLine("Generating & Compiling method time : {0} ms ({1} ticks)", sw.ElapsedMilliseconds, sw.ElapsedTicks);

            const int TrialCount = 10000;
            var first = Enumerable.Range(0, 100).ToArray();
            var second = Enumerable.Range(0, 100).ToArray();

            // Cold start for JIT-compiling 
            func(first, second);
            CodeGeneration.MultuplyVectors(first, second);

            sw.Reset();
            sw.Start();
            for (int i = 0; i < TrialCount; i++)
                func(first, second);
            sw.Stop();
            Console.WriteLine("Generated code : {0} ms ({1} ticks)", sw.ElapsedMilliseconds, sw.ElapsedTicks);


            sw.Reset();
            sw.Start();
            for (int i = 0; i < TrialCount; i++)
                CodeGeneration.MultuplyVectors(first, second);
            sw.Stop();
            Console.WriteLine("Static code   : {0} ms ({1} ticks)", sw.ElapsedMilliseconds, sw.ElapsedTicks);
        }
Ejemplo n.º 8
0
        public void WhenAddUsedTypesInvokedAfterEndInit_ThenThrowsInvalidOperationOperation()
        {
            var codegen = new CodeGeneration();

            codegen.EndInit();

            Assert.Throws <InvalidOperationException>(() => codegen.AddUsedTypes(typeof(Foo)));
        }
Ejemplo n.º 9
0
        public void WhenInvokingBeginInitAfterEndInit_ThenThrowsInvalidOperationOperation()
        {
            var codegen = new CodeGeneration();

            codegen.EndInit();

            Assert.Throws <InvalidOperationException>(() => codegen.BeginInit());
        }
Ejemplo n.º 10
0
 /// <summary>Ctor - sets up defaults.</summary>
 public ExecutionConfig()
 {
     ThreadingProfile            = ThreadingProfile.NORMAL;
     FilterServiceProfile        = FilterServiceProfile.READMOSTLY;
     FilterServiceMaxFilterWidth = 16;
     DeclaredExprValueCacheSize  = 1;
     IsPrioritized  = false;
     CodeGeneration = new CodeGeneration();
 }
Ejemplo n.º 11
0
 public override CodeGeneration.CodeBuilder.ICodeBlock GenerateActivity(CodeGeneration.CodeBuilder.ICodeBlock codeBlock, SaveClasses.IElement element)
 {
     // We used to call TimedEmit here
     // but we only want to call it if the
     // NOS is non-null. That means we are going
     // to call the TimedEmit generating code from
     // within the NamedObjectSaveCodeGenerator's GenerateActivity
     return codeBlock;
 }
        public void GetVectorMultiplyFunction_Returns_Function_For_Long() {
            var first = new long[] { 1L, 2L, 3L };
            var second = new long[] { 2L, 2L, 2L };
            var expected = 1L * 2L + 2L * 2L + 3L * 2L;

            var func = CodeGeneration.GetVectorMultiplyFunction<long>();
            var actual = func(first, second);
            Assert.AreEqual(expected, actual);
        }
        public void GetVectorMultiplyFunction_Returns_Function_For_Double() {
            var first = new double[] { 1D, 2D, 3D };
            var second = new double[] { 2D, 2D, 2D };
            var expected = 1D * 2D + 2D * 2D + 3D * 2D;

            var func = CodeGeneration.GetVectorMultiplyFunction<double>();
            var actual = func(first, second);
            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 14
0
    public static string getDALFunction_SelectAll(ProjectClass pClass, string readConnection, cg.Language lang)
    {
        StringBuilder strB = new StringBuilder();

        strB.Append(CodeGeneration.getMetaDataText("Gets a list of all " + pClass.NameSpaceVariable.NameBasedOnID + "." + pClass.Name.Capitalized()
                                                   + " objects from the database.", false, (int)tab.XX, lang,
                                                   cg.GetByLanguage(lang, "List(Of ", "List<")
                                                   + pClass.NameSpaceVariable.NameBasedOnID + "." + pClass.Name.Capitalized()
                                                   + cg.GetByLanguage(lang, ")", ">")));
        string sprocName = "sproc" + pClass.Name.PluralAndCapitalized + "GetAll";

        if (lang == CodeGeneration.Language.VisualBasic)
        {
            strB.AppendLine(Strings.Space((int)tab.XX) + "Public Shared Function Get" + pClass.Name.PluralAndCapitalized
                            + "() As List(Of " + pClass.Name.Capitalized() + ")");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Dim comm As New SqlCommand(\"" + sprocName + "\")");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Dim retList As New List(Of " + pClass.Name.Capitalized() + ")");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Try");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.CommandType = Microsoft.Data.CommandType.StoredProcedure");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "Dim dr As SqlDataReader = GetDataReader(comm)");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "While dr.Read()");
            strB.AppendLine(Strings.Space((int)tab.XXXXX) + "retList.Add(New " + pClass.Name.Capitalized() + "(dr))");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "End While");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.Connection.Close()");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Catch ex As Exception");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.Connection.Close()");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "End Try");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Return retList");
            strB.AppendLine(Strings.Space((int)tab.XX) + "End Function");
        }
        else
        {
            strB.AppendLine(Strings.Space((int)tab.XX) + "public static List<" + pClass.Name.Capitalized() + "> Get" + pClass.Name.PluralAndCapitalized + "()");
            strB.AppendLine(Strings.Space((int)tab.XX) + "{");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "SqlCommand comm = new SqlCommand(\"" + sprocName + "\");");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "List<" + pClass.Name.Capitalized() + "> retList = new List<" + pClass.Name.Capitalized() + ">();");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "try");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "{");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.CommandType = Microsoft.Data.CommandType.StoredProcedure;");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "SqlDataReader dr = GetDataReader(comm);");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "while (dr.Read())");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "{");
            strB.AppendLine(Strings.Space((int)tab.XXXXX) + "retList.Add(new " + pClass.Name.Capitalized() + "(dr));");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "}");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.Connection.Close();");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "}");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "catch (Exception ex)");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "{");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.Connection.Close();");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "}");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "return retList;");
            strB.AppendLine(Strings.Space((int)tab.XX) + "}");
        }
        strB.AppendLine();
        return(strB.ToString());
    }
Ejemplo n.º 15
0
    public static string getDALFunction_SelectSingle(ProjectClass pClass, string readConnection, cg.Language lang)
    {
        StringBuilder strB = new StringBuilder();

        strB.AppendLine(CodeGeneration.getMetaDataText("Gets the " + pClass.NameSpaceVariable.NameBasedOnID + "." + pClass.Name.Text()
                                                       + "corresponding with the given ID", false, (int)tab.XX, lang, pClass.Name.Capitalized()));

        string sprocName = "sproc" + pClass.Name.Capitalized() + "Get";

        if (lang == CodeGeneration.Language.VisualBasic)
        {
            strB.AppendLine(Strings.Space((int)tab.XX) + "Public Shared Function Get" + pClass.Name.Capitalized() + "(ByVal id As Integer) As " + pClass.Name.Capitalized());
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Dim comm As New SqlCommand(\"" + sprocName + "\")");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Dim retObj As " + pClass.Name.Capitalized() + " = Nothing ");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Try");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "With comm");
            strB.AppendLine(Strings.Space((int)tab.XXXXX) + getParaString(lang, pClass, "ID", "id"));
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "End With");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "Dim dr As SqlDataReader = GetDataReader(comm)");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "While dr.Read()");
            strB.AppendLine(Strings.Space((int)tab.XXXXX) + "retObj = New " + pClass.Name.Capitalized() + "(dr)");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "End While");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.Connection.Close()");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Catch ex As Exception");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.Connection.Close()");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "End Try");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "Return retObj");
            strB.AppendLine(Strings.Space((int)tab.XX) + "End Function");
        }
        else
        {
            strB.AppendLine(Strings.Space((int)tab.XX) + "public static " + pClass.Name.Capitalized() + " Get" + pClass.Name.Capitalized() + "(int id)");
            strB.AppendLine(Strings.Space((int)tab.XX) + "{");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "SqlCommand comm = new SqlCommand(\"" + sprocName + "\");");
            strB.AppendLine(Strings.Space((int)tab.XXX) + pClass.Name.Capitalized() + " retObj = null;");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "try");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "{");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + getParaString(lang, pClass, "ID", "id"));

            strB.AppendLine(Strings.Space((int)tab.XXXX) + "SqlDataReader dr = GetDataReader(comm);");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "while (dr.Read())");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "{");
            strB.AppendLine(Strings.Space((int)tab.XXXXX) + "retObj = new " + pClass.Name.Capitalized() + "(dr);");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "}");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.Connection.Close();");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "}");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "catch (Exception ex)");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "{");
            strB.AppendLine(Strings.Space((int)tab.XXXX) + "comm.Connection.Close();");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "}");
            strB.AppendLine(Strings.Space((int)tab.XXX) + "return retObj;");
            strB.AppendLine(Strings.Space((int)tab.XX) + "}");
        }
        strB.AppendLine();
        return(strB.ToString());
    }
Ejemplo n.º 16
0
        public void WhenAddingAssembly_ThenSafeUsingsDoNotContainGenerics()
        {
            var codegen = new CodeGeneration();

            codegen.AddType(typeof(IEnumerable <string>));
            codegen.AddType(typeof(IEnumerable));
            codegen.EndInit();

            Assert.False(codegen.SafeImports.Any(s => s.IndexOf('[') != -1));
        }
        public void GetVectorMultiplyFunction_Returns_Function_For_Int() {
            var first = new int[] { 1, 2, 3 };
            var second = new int[] { 2, 2, 2 };
            var expected = 1*2 + 2*2 + 3*2;

            var func = CodeGeneration.GetVectorMultiplyFunction<int>();
            var actual = func(first, second);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 18
0
    public void GenerateVBBusinessLogicClass()
    {
        string         strTemplate        = string.Empty;
        string         strDataAccessClass = string.Empty;
        CodeGeneration objTemplate        = new CodeGeneration();

        strTemplate        = objTemplate.ReadTemplate(PublicEnums.TemplateName.VBBusinessLogicClass);
        strDataAccessClass = GenerateVBBusinessLogicClass(strTemplate, strTableName, dtColumns);
        objTemplate.SaveClass(strDataAccessClass, strOutput + @"\CodeClasses\VBClasses\BusinessLogicClasses\" + strTableName + ".vb");
    }
Ejemplo n.º 19
0
        public void WhenSimplifyingAssemblyQualifiedName_ThenAddsUsingAndSimplifiesTypeName()
        {
            var codegen = new CodeGeneration();

            codegen.AddType("Foo.Bar, Foo");
            codegen.EndInit();

            Assert.Equal("Bar", codegen.GetTypeName("Foo.Bar, Foo"));
            Assert.True(codegen.SafeImports.Contains("Foo"));
        }
Ejemplo n.º 20
0
        public void WhenSimplifyingGenericType_ThenAddsUsingsAndSimplifiesGenericParameterType()
        {
            var codegen = new CodeGeneration();

            codegen.AddType(typeof(IEnumerable <NonNestedType>));
            codegen.EndInit();

            Assert.Equal("IEnumerable<NonNestedType>", codegen.GetTypeName(typeof(IEnumerable <NonNestedType>)));
            Assert.True(codegen.SafeImports.Contains(typeof(IEnumerable <>).Namespace));
            Assert.True(codegen.SafeImports.Contains(typeof(NonNestedType).Namespace));
        }
Ejemplo n.º 21
0
 private Compiler(Context context)
 {
     context.put(CONTEX_KEY, this);
     options             = CommandLineOptions.instance(context);
     parser              = ParserRunner.instance(context);
     declarationAnalysis = DeclarationAnalysis.instance(context);
     codeTypeAnalysis    = CodeTypeAnalysis.instance(context);
     flowAnalysis        = FlowAnalysis.instance(context);
     codeGeneration      = CodeGeneration.instance(context);
     log = Log.instance(context);
 }
Ejemplo n.º 22
0
 public string getVariableName()
 {
     if (!CodeGeneration.isRegularDataType(ParameterType.Name()))
     {
         return(Name + "ID");
     }
     else
     {
         return(Name);
     }
 }
Ejemplo n.º 23
0
        public void WhenSimplifyingTypeMap_ThenNoNamespaceTypesAreValid()
        {
            var codegen = new CodeGeneration();

            codegen.TypeNameMap["Foo"] = "Foo";
            codegen.TypeNameMap["Bar"] = "Foo";

            codegen.EndInit();

            Assert.Equal("Foo", codegen.TypeNameMap["Foo"], "Foo does not have a namespace but it still is valid.");
            Assert.Equal("Bar", codegen.TypeNameMap["Bar"], "Bar does not have a namespace but it still is valid.");
        }
Ejemplo n.º 24
0
        public void WhenSimplifyingGenericTypeWithCollidingParameter_ThenKeepsParameterFullName()
        {
            var codegen = new CodeGeneration();

            codegen.AddType(typeof(IEnumerable <StringConverter>));
            codegen.AddType(typeof(System.ComponentModel.StringConverter));
            codegen.EndInit();

            Assert.Equal("IEnumerable<NuPattern.Runtime.UnitTests.CodeGen.StringConverter>", codegen.GetTypeName(typeof(IEnumerable <StringConverter>)));
            Assert.True(codegen.SafeImports.Contains(typeof(IEnumerable <>).Namespace));
            Assert.False(codegen.SafeImports.Contains(typeof(StringConverter).Namespace));
        }
Ejemplo n.º 25
0
        protected override void ProcessRecord()
        {
            var jobNames = Name?
                           .Select(i => WildcardPattern.Get(i, WildcardOptions.IgnoreCase))
                           ?? new[] { WildcardPattern.Get("*", WildcardOptions.IgnoreCase) };
            var printerNames = PrinterName?
                               .Select(i => CodeGeneration.EscapeSingleQuotedStringContent(WildcardPattern.Get(i, WildcardOptions.IgnoreCase).ToWql()))
                               ?? new string[] { "%" };

            if (ParameterSetName == DefaultSet)
            {
                foreach (var sn in Session !)
                {
                    foreach (var printerName in printerNames)
                    {
                        try
                        {
                            var printers = sn.QueryInstances("root/standardcimv2", "WQL", $"select * from msft_printer where Name like '{printerName}'", _options);
                            foreach (var printer in printers)
                            {
                                var parameters = new CimMethodParametersCollection()
                                {
                                    CimMethodParameter.Create("PrinterObject", printer, CimType.Instance, CimFlags.In)
                                };
                                var methodResult = sn.InvokeMethod("root/standardcimv2", "msft_printjob", "GetByObject", parameters, _options);
                                var jobs         = (IEnumerable <CimInstance>)methodResult.OutParameters["cmdletOutput"].Value;
                                WriteObject(methodResult.OutParameters);
                                Console.WriteLine("checking jobs");
                                jobs.GetEnumerator();
                                Console.WriteLine("Got enumerator");
                                foreach (var job in jobs)
                                {
                                    Console.WriteLine("creating job");
                                    var psjob = new PSPrintJob(job);
                                    Console.WriteLine("job created");
                                    if (jobNames.Any(i => i.IsMatch(psjob.Name)))
                                    {
                                        WriteObject(psjob);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            WriteError(new ErrorRecord(e, "not good", ErrorCategory.NotSpecified, null));
                        }
                    }
                }
            }
            else if (ParameterSetName == PrinterSet)
            {
            }
        }
Ejemplo n.º 26
0
        private DebuggerCommandResults HandlePromptCommand(PSDataCollection <PSObject> output)
        {
            // Nested debugged runspace prompt should look like:
            // [DBG]: [JobName]: PS C:\>>
            string    promptScript  = "'[DBG]: '" + " + " + "'[" + CodeGeneration.EscapeSingleQuotedStringContent(_jobName) + "]: '" + " + " + @"""PS $($executionContext.SessionState.Path.CurrentLocation)>> """;
            PSCommand promptCommand = new PSCommand();

            promptCommand.AddScript(promptScript);
            _wrappedDebugger.ProcessCommand(promptCommand, output);

            return(new DebuggerCommandResults(null, true));
        }
Ejemplo n.º 27
0
        public void WhenSimplifyingAllCoreLib_ThenAddsUsingForGenericsAndNonGenericEnumerable()
        {
            var codegen = new CodeGeneration();

            codegen.AddTypes(typeof(string).Assembly);
            codegen.AddType(typeof(IComparable <string>));
            codegen.EndInit();

            Assert.Equal("IComparable<String>", codegen.GetTypeName(typeof(IComparable <string>)));
            Assert.Equal("IComparable", codegen.GetTypeName(typeof(IComparable)));
            Assert.True(codegen.SafeImports.Contains(typeof(IComparable <>).Namespace));
        }
Ejemplo n.º 28
0
        public void WhenSimplifyingTypeMap_ThenUniqueTypeNamesAreSimplified()
        {
            var codegen = new CodeGeneration();

            codegen.TypeNameMap["Foo.A"] = "Foo.A";
            codegen.TypeNameMap["Bar.B"] = "Foo.B";

            codegen.EndInit();

            Assert.Equal("A", codegen.TypeNameMap["Foo.A"], "A is unique in the dictionary, so it can be used as a simplified type name.");
            Assert.Equal("B", codegen.TypeNameMap["Bar.B"], "B is unique in the dictionary, so it can be used as a simplified type name.");
        }
Ejemplo n.º 29
0
        public void WhenSimplifyingGenericTypeWithNestedTypeParameter_ThenRemovesPlusFromNestedTypeName()
        {
            var codegen = new CodeGeneration();

            codegen.AddType(typeof(IEnumerable <NestedType>));
            codegen.EndInit();

            Assert.Equal("IEnumerable<CodeGenerationSpec.NestedType>", codegen.GetTypeName(typeof(IEnumerable <NestedType>)));
            Assert.True(codegen.SafeImports.Contains(typeof(IEnumerable <>).Namespace));
            Assert.True(codegen.SafeImports.Contains(typeof(NestedType).Namespace));
            Assert.False(codegen.SafeImports.Contains(typeof(CodeGenerationSpec).FullName), "The nested type parent should not be mistaken for a namespace.");
        }
Ejemplo n.º 30
0
    private string GenerateVariableDeclarationList(DataTable dtColumns)
    {
        string         strVariablesList = string.Empty;
        CodeGeneration objCodeGen       = new CodeGeneration();

        foreach (DataRow dr in dtColumns.Rows)
        {
            strVariablesList += "Dim " + objCodeGen.GetVariableName(dr["DATA_TYPE"].ToString(), dr["COLUMN_NAME"].ToString()) + " As " + GetVBDataType(dr["DATA_TYPE"].ToString()) + "\n";
        }

        return(strVariablesList);
    }
Ejemplo n.º 31
0
    }     //end function

    private string GenerateSPParametersList(DataTable dtColumns)
    {
        string         strParametersList = string.Empty;
        CodeGeneration objCodeGen        = new CodeGeneration();

        foreach (DataRow dr in dtColumns.Rows)
        {
            strParametersList += @"objCommand.Parameters.AddWithValue(""@" + dr["COLUMN_NAME"].ToString() + @""", " + objCodeGen.GetVariableName(dr["DATA_TYPE"].ToString(), dr["COLUMN_NAME"].ToString()) + ")\n";
        }

        return(strParametersList);
    }