Пример #1
0
    public static Dictionary <string, string> GetLanguages()
    {
        Dictionary <string, string> langs = new Dictionary <string, string>();

        foreach (Code c in CodeTranslator.GetCodeType("LOC"))
        {
            string lang        = "";
            string description = "";
            char[] splitters   = { '_', '(' };

            if (c.Alternate_Type != null && c.Alternate_Type.Length > 0)
            {
                string[] langsplit = c.Alternate_Type.Split(splitters);
                string[] descs     = c.External_Description.Split(splitters);

                lang        = langsplit[0];
                description = descs[0].TrimEnd();

                if (c.Alternate_Type == "en_ZW")
                {
                    description = "English";
                }

                if (langs.ContainsKey(lang) == false)
                {
                    langs.Add(lang, description);
                }
            }
        }

        return(langs);
    }
Пример #2
0
    private static string BuildTitle(Task emailTask, IMTDService service)
    {
        string retVal = "";

        retVal = emailTask.Task_CID.GetExternalText() + "; ";

        Base.Attribute projectAttr = emailTask.Attributes.Find(CodeTranslator.Find("TASK_ATTR", "PROJECT"));
        if (projectAttr != null)
        {
            BaseExtendable project = new BaseExtendable(CodeTranslator.Find("ENTITY_TYPE", "PROJECT").Code_IID);
            project.Entity_IID = (int)projectAttr.Value;
            project            = (BaseExtendable)service.Load(project);
            service.LoadAttributes(project);

            Base.Attribute contactAttr = project.Attributes.Find(CodeTranslator.Find("PROJECT_ATTR", "CONTACT"));
            if (contactAttr != null)
            {
                Contact targetContact = new Contact((int)contactAttr.Value);
                targetContact = (Contact)service.Load(targetContact);
                retVal       += targetContact.Customer_Name + "; ";

                /*
                 * CustomerSite targetSite = new CustomerSite(targetContact.Site_IID);
                 * targetSite = (CustomerSite)service.Load(targetSite);
                 * Customer targetCustomer = new Customer(targetSite.Customer_IID);
                 * targetCustomer = (Customer)service.Load(targetCustomer);
                 * retVal += targetCustomer.Name + "; ";
                 */
            }

            retVal += project.Description + "; ";

            Base.Attribute projectNumAttr = project.Attributes.Find(CodeTranslator.Find("PROJECT_ATTR", "PROJECTNUM"));
            if (projectNumAttr != null)
            {
                retVal += "P#:" + (string)projectNumAttr.Value;
            }
            else
            {
                retVal += "Q#:" + project.OID;
            }
        }
        else
        {
            Base.Attribute prospectAttr = emailTask.Attributes.Find(CodeTranslator.Find("TASK_ATTR", "PROSPECT"));
            if (prospectAttr != null)
            {
                int          prospectIID = (int)prospectAttr.Value;
                Prospect     propect     = service.LoadProspect(prospectIID);
                CustomerSite site        = service.LoadCustomerSite(propect.Site_IID);
                Customer     cust        = service.LoadCustomer(site.Customer_IID);
                retVal += " " + propect.First_Name + " " + propect.Last_Name + " (" + cust.Name + ")";
            }
        }

        return(retVal);
    }
Пример #3
0
        public static void AutoExecuteCode(string code)
        {
            code = CodeTranslator.TranslateCode(code);
            CODE_READER.CheckLanguageRoutines(code, 0);
            var name = CODE_READER.GetCodeDeclaration(code);
            var args = CODE_READER.GetReads(code);

            args = CorrectArgs(name, args);
            ExecuteCode(name, args);
        }
Пример #4
0
        public void AnalyzeCode()
        {
            CODE_EXEC.Fields.Clear();
            var lines = CODE_READER.GetScriptLines(CurrentCode);

            foreach (var line in lines)
            {
                var lineCode = CodeTranslator.TranslateCode(line);
                CODE_READER.CheckLanguageRoutines(lineCode, 0);
            }
        }
Пример #5
0
        /// <summary>
        /// Gets the kernel code.
        /// </summary>
        /// <param name="kernalClass">The kernal class.</param>
        /// <returns></returns>
        private string GetKernelCode(Type kernalClass)
        {
            string           assemblyPath = kernalClass.Assembly.Location;
            CSharpDecompiler cSharpDecompiler
                = new CSharpDecompiler(assemblyPath, new Amplifier.Decompiler.DecompilerSettings()
            {
                ThrowOnAssemblyResolveErrors = false, ForEachStatement = false
            });
            StringBuilder   result   = new StringBuilder();
            ITypeDefinition typeInfo = cSharpDecompiler.TypeSystem.MainModule.Compilation.FindType(new FullTypeName(kernalClass.FullName)).GetDefinition();

            List <IMethod> kernelMethods    = new List <IMethod>();
            List <IMethod> nonKernelMethods = new List <IMethod>();

            foreach (var item in typeInfo.Methods)
            {
                if (item.IsConstructor)
                {
                    continue;
                }

                if (item.GetAttributes().FirstOrDefault(x => (x.AttributeType.Name == "OpenCLKernelAttribute")) == null)
                {
                    nonKernelMethods.Add(item);
                    continue;
                }

                kernelMethods.Add(item);

                var k = new KernelFunction()
                {
                    Name = item.Name
                };
                foreach (var p in item.Parameters)
                {
                    k.Parameters.Add(p.Name, p.Type.FullName);
                }

                KernelFunctions.Add(k);
            }

            var kernelHandles    = kernelMethods.ToList().Select(x => (x.MetadataToken)).ToList();
            var nonKernelHandles = nonKernelMethods.ToList().Select(x => (x.MetadataToken)).ToList();

            result.AppendLine(cSharpDecompiler.DecompileAsString(nonKernelHandles));
            result.AppendLine(cSharpDecompiler.DecompileAsString(kernelHandles));

            return(CodeTranslator.Translate(result.ToString()));
        }
Пример #6
0
        private string GetStructCode(Type structInstance)
        {
            string           assemblyPath = structInstance.Assembly.Location;
            CSharpDecompiler cSharpDecompiler
                = new CSharpDecompiler(assemblyPath, new Amplifier.Decompiler.DecompilerSettings()
            {
                ThrowOnAssemblyResolveErrors = false, ForEachStatement = false
            });

            var tree = cSharpDecompiler.DecompileType(new FullTypeName(structInstance.FullName));

            string code = cSharpDecompiler.DecompileTypeAsString(new FullTypeName(structInstance.FullName));

            return(CodeTranslator.Translate(code).Trim() + ";");
        }
Пример #7
0
        private CodeTranslator CodeGenStart(List <CodeTranslator.Tokens> tokens, SemanticsInitializer semantics)
        {
            CodeTranslator gen = null;

            try
            {
                gen = new CodeTranslator(tokens, semantics);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            return(gen);
        }
Пример #8
0
    public static SortedList <string, Code> GetLocales(string lang_mnemonic)
    {
        SortedList <string, Code> locales = new SortedList <string, Code>();

        foreach (Code c in CodeTranslator.GetCodeType("LOC"))
        {
            string lang      = "";
            char[] splitters = { '_', '(', ')' };

            if (c.Alternate_Type != null && c.Alternate_Type.Length > 0)
            {
                string[] langsplit = c.Alternate_Type.Split(splitters);
                string[] descs     = c.External_Description.Split(splitters);
                string   locale    = "";

                lang = langsplit[0];
                if (lang == lang_mnemonic)
                {
                    if (descs.Length > 1)
                    {
                        locale = descs[1];
                    }
                    else
                    {
                        locale = descs[0].TrimEnd();
                    }

                    if (locales.IndexOfKey(locale) >= 0)
                    {
                        locales.Add(c.External_Description + " [" + c.Code_Value + "]", c);
                    }
                    else
                    {
                        locales.Add(locale, c);
                    }
                }
            }
        }

        return(locales);
    }
Пример #9
0
        public string[] WriteProject(IIntermediateAssembly assembly, string rootFolder, string extension = ".cs")
        {
            List<string> fileTracker = new List<string>();
            Dictionary<IIntermediateAssembly, string> fileNameLookup = new Dictionary<IIntermediateAssembly, string>();
            this.nameProvider = new NameProvider(this, fileNameLookup);
            var information =
                (from part in new[] { assembly }.Concat(assembly.Parts)
                 let partFile = CSharpProjectTranslator.AssemblyFileVisitor.GetFileInfo(part, this, fileTracker)
                 where partFile.YieldsFile
                 let fnTrans = GetTranslatorAndFinalName(rootFolder, extension, partFile.FileName, part, fileNameLookup)
                 select new { Part = part, FileName = partFile.FileName, FinalName = fnTrans.Item2, Translator = fnTrans.Item1 }).ToArray();
#if !DO_NOT_WRITE_MULTITHREADED
            Parallel.ForEach(information, async assemblyFileInfo =>
#else
            foreach (var assemblyFileInfo in information)
#endif
            {
                CodeTranslator translator = assemblyFileInfo.Translator;
                var fileStream = new FileStream(assemblyFileInfo.FinalName, FileMode.Create, FileAccess.Write, FileShare.Read);
                var streamWriter = new StreamWriter(fileStream);
                IndentedTextWriter itw ;
                if (options.IndentationSpaceCount != null)
                    itw = new IndentedTextWriter(streamWriter, new string(' ', options.IndentationSpaceCount.Value));
                else
                    itw = new IndentedTextWriter(streamWriter);
                translator.Target = itw;
                translator.Translate(assemblyFileInfo.Part);
#if !DO_NOT_WRITE_MULTITHREADED
                await streamWriter.FlushAsync();
#else
                streamWriter.Flush();
#endif
                streamWriter.Dispose();
                fileStream.Close();
                fileStream.Dispose();
            }
Пример #10
0
    private static string BuildHeader(Task emailTask, IMTDService service)
    {
        string retVal = "<strong>Task Information</strong><br>";

        Base.Attribute projectAttr = emailTask.Attributes.Find(CodeTranslator.Find("TASK_ATTR", "PROJECT"));
        if (projectAttr != null)
        {
            BaseExtendable project = new BaseExtendable(CodeTranslator.Find("ENTITY_TYPE", "PROJECT").Code_IID);
            project.Entity_IID = (int)projectAttr.Value;
            project            = (BaseExtendable)service.Load(project);
            service.LoadAttributes(project);

            retVal += "Quote Number: " + project.OID + "<br>";

            Base.Attribute projectNumAttr = project.Attributes.Find(CodeTranslator.Find("PROJECT_ATTR", "PROJECTNUM"));
            if (projectNumAttr != null)
            {
                retVal += "Project Number: " + (string)projectNumAttr.Value + "<br>";
            }

            retVal += "Description: " + project.Description + "<br>";

            Base.Attribute contactAttr = project.Attributes.Find(CodeTranslator.Find("PROJECT_ATTR", "CONTACT"));
            if (contactAttr != null)
            {
                Contact targetContact = new Contact((int)contactAttr.Value);
                targetContact = (Contact)service.Load(targetContact);
                retVal       += "Company: " + targetContact.Customer_Name + "<br>";

                /*
                 * CustomerSite targetSite = new CustomerSite(targetContact.Site_IID);
                 * targetSite = (CustomerSite)service.Load(targetSite);
                 * Customer targetCustomer = new Customer(targetSite.Customer_IID);
                 * targetCustomer = (Customer)service.Load(targetCustomer);
                 * retVal += "Company: " + targetCustomer.Name + "<br>";
                 */
            }
        }

        retVal += "Task Status: " + emailTask.Task_Status_CID.GetExternalText() + "<br>";


        UserRole createRole = service.LoadUserRole(emailTask.Created_User_Role_IID);

        retVal += "Task Created By: " + createRole.User.DisplayName + "<br>";

        if (emailTask.Pending_User_Role_IID != -1)
        {
            UserRole pendingRole = service.LoadUserRole(emailTask.Pending_User_Role_IID);
            retVal += "Task Pending Acceptance: " + pendingRole.User.DisplayName + "<br>";
        }
        if (emailTask.Current_User_Role_IID != -1)
        {
            UserRole currentRole = service.LoadUserRole(emailTask.Current_User_Role_IID);
            retVal += "Task Owned By: " + currentRole.User.DisplayName + "<br>";
        }

        retVal += "<hr><br>";

        return(retVal);
    }
Пример #11
0
        // #lizard forgives
        public static void Main(string[] args)
        {
            if (!argsValid(args))
            {
                usage();
                return;
            }
            ProcessMode mode = args[0] == "-patch" ?  ProcessMode.Patch : ProcessMode.Inject;

            CodeTranslator     tranlater      = new CodeTranslator();
            AssemblyDefinition assembly       = null;
            AssemblyDefinition ilfixAassembly = null;
            AssemblyDefinition oldAssembly    = null;
            string             dllName        = null;

            try
            {
                var  assmeblyPath = args[2];
                bool readSymbols  = true;
                try
                {
                    //尝试读取符号
                    assembly = AssemblyDefinition.ReadAssembly(assmeblyPath,
                                                               new ReaderParameters {
                        ReadSymbols = true
                    });
                }
                catch
                {
                    //如果读取不到符号则不读
                    Debug.Log("Warning: read " + assmeblyPath + " with symbol fail");
                    //写入的时候用这个标志
                    readSymbols = false;
                    assembly    = AssemblyDefinition.ReadAssembly(assmeblyPath,
                                                                  new ReaderParameters {
                        ReadSymbols = false
                    });
                }

                var  resolver        = assembly.MainModule.AssemblyResolver as BaseAssemblyResolver;
                bool isInheritInject = args[0] == "-inherit_inject";
                int  searchPathStart = isInheritInject ? 7 : 6;

                //往resolver加入程序集搜索路径
                foreach (var path in args.Skip(searchPathStart))
                {
                    try
                    {
                        //Debug.Log("searchPath:" + path);
                        resolver.AddSearchDirectory(path);
                    } catch { }
                }

                ilfixAassembly = AssemblyDefinition.ReadAssembly(args[1]);
                dllName        = Path.GetFileName(args[2]);
                GenerateConfigure configure = null;

                if (mode == ProcessMode.Inject)
                {
                    //对测试用例特殊处理:测试用例默认全解析执行
                    configure = args[3] == "no_cfg" ?
                                GenerateConfigure.Empty() : GenerateConfigure.FromFile(args[3]);

                    if (isInheritInject)
                    {
                        throw new Exception("Do Not Support already!");
                    }

                    //注入逻辑
                    //TODO: tranlater的名字不太合适
                    if (tranlater.Process(assembly, ilfixAassembly, configure, mode)
                        == CodeTranslator.ProcessResult.Processed)
                    {
                        Debug.Log(dllName + " process yet!");
                        return;
                    }

                    tranlater.Serialize(args[4]);

                    assembly.Write(args[5], new WriterParameters {
                        WriteSymbols = readSymbols
                    });
                    //ilfixAassembly.Write(args[2], new WriterParameters { WriteSymbols = true });
                }
                else
                {
                    //补丁生成流程
                    configure = new PatchGenerateConfigure(assembly, args[4]);

                    if (tranlater.Process(assembly, ilfixAassembly, configure, mode)
                        == CodeTranslator.ProcessResult.Processed)
                    {
                        //发现程序集已经被注入,主要是防止已经注入的函数包含的注入逻辑会导致死循环
                        Debug.Log("Error: the new assembly must not be inject, please reimport the project!");
                        return;
                    }

                    tranlater.Serialize(args[5]);
                    Debug.Log("output: " + args[5]);
                }
            }
            catch (Exception e)
            {
                Debug.Log("Unhandled Exception:\r\n" + e);
                return;
            }
            finally
            {
                //清理符号读取器
                //如果不清理,在window下会锁定文件
                if (assembly != null && assembly.MainModule.SymbolReader != null)
                {
                    assembly.MainModule.SymbolReader.Dispose();
                }

                if (ilfixAassembly != null && ilfixAassembly.MainModule.SymbolReader != null)
                {
                    ilfixAassembly.MainModule.SymbolReader.Dispose();
                }

                if (oldAssembly != null && oldAssembly.MainModule.SymbolReader != null)
                {
                    oldAssembly.MainModule.SymbolReader.Dispose();
                }
            }
            Debug.Log(dllName + " process success");
        }
Пример #12
0
        private void LexButton_Click(object sender, EventArgs e)
        {
            LexGrid.Rows.Clear();
            DataLexicalError.Rows.Clear();
            DataSyntaxError.Rows.Clear();
            Grid_Syntax.Rows.Clear();
            Grid_Dec.Rows.Clear();
            Grid_Array.Rows.Clear();
            Output.Text = "";
            if (Code.Text != "")
            {
                //LEXICAL ANALYZER
                Output.Text = "[1] Starting Lexical Analyzer\n";
                LexicalAnalyzer    lex     = new LexicalAnalyzer();
                LexicalInitializer Lexical = new LexicalInitializer();
                string             txt     = Code.Text;
                lex = Lexical.Start(txt, lex);
                //DISPLAY TOKENS
                DisplayTokens(lex);

                if (syntax_mode.Checked)
                {
                    if (lex.invalid == 0 && lex.token.Count != 0)
                    {
                        //SYNTAX ANALYZER
                        SyntaxInitializer    Syntax_Analyzer = new SyntaxInitializer();
                        SemanticsInitializer semantics       = new SemanticsInitializer();
                        Output.Text += "\n[2] Starting Syntax Analyzer\n";

                        if (semantics_mode.Checked)
                        {
                            Output.Text += "[3] Starting Static Semantics Analyzer\n";
                        }
                        string syntax_result = Syntax_Analyzer.Start(tokenDump(lex.token)) + "\n";
                        int    c             = 0;
                        Grid_Syntax.Rows.Clear();
                        foreach (var item in Syntax_Analyzer.SET)
                        {
                            Grid_Syntax.Rows.Add((c + 1).ToString(), Syntax_Analyzer.PRODUCTION[c].ToString(), "->", Syntax_Analyzer.SET[c].ToString());
                            c++;
                        }


                        //MessageBox.Show(Syntax_Analyzer.production);
                        //MessageBox.Show(Syntax_Analyzer.recursiveprod);
                        if (syntax_result != "Syntax Analyzer Succeeded...\n")
                        {
                            int errornum = 1;
                            DataSyntaxError.Rows.Clear();
                            //if(Syntax_Analyzer.PRODUCTION[c-1] == "Prod_logop1")
                            //{
                            //    DataSyntaxError.Rows.Add(errornum, Syntax_Analyzer.errors.getLines(), Syntax_Analyzer.errors.getColumn(), "Expected: \"!\", \"id\", \"boollit\", \"intlit\", \"doublelit\", \"charlit\", \"stringlit\".");
                            //}
                            //else if (Syntax_Analyzer.PRODUCTION[c - 1] == "Prod_option" && Syntax_Analyzer.errors.getErrorMessage() == "Expected: Var, Clear, id, Int, Char, Boolean, Double, String, ++, --, Object, Until, Do, For, Array, If, Read, Say, Option, ., Stop, End.")
                            //{
                            //    DataSyntaxError.Rows.Add(errornum, Syntax_Analyzer.errors.getLines(), Syntax_Analyzer.errors.getColumn(), "Expected: \"intlit\", \"charlit\", \"stringlit\".");
                            //}
                            //else
                            if (Syntax_Analyzer.errors.getColumn() == 1)
                            {
                                Syntax_Analyzer.errors.setLines(Syntax_Analyzer.errors.getLines() - 1);
                            }
                            DataSyntaxError.Rows.Add(errornum, Syntax_Analyzer.errors.getLines(), Syntax_Analyzer.errors.getColumn(), Syntax_Analyzer.errors.getErrorMessage());
                            errornum++;
                        }
                        else
                        {
                            Output.Text += syntax_result;
                        }
                        if (semantics_mode.Checked)
                        {
                            semantics = SemanticsStart(tokenDumps(lex.token));
                            string semantics_result = semantics.Start();
                            foreach (var item in semantics.Identifiers)
                            {
                                Grid_Dec.Rows.Add(item.getLines(), item.getId(), item.getDtype(), item.getValue(), item.getScope());
                            }
                            foreach (var item in semantics.Indexes)
                            {
                                Grid_Array.Rows.Add(item.getId(), item.getDatatype(), item.getValue(), item.getIndex_1(), item.getIndex_2());
                            }
                            if (semantics.error != "" || syntax_result != "Syntax Analyzer Succeeded...\n")
                            {
                                Output.Text += semantics.error + semantics_result;
                            }
                            else
                            {
                                CodeTranslator generate = new CodeTranslator();
                                generate = CodeGenStart(TokenDump(lex.token), semantics);
                                generate.Start();
                                string code = generate.code;
                                code  = code.Remove(code.Length - 2, 2);
                                code += "}\n    public static Int64[] Random(Int64 start, Int64 end)\n{\nList<Int64> listNumbers = new List<Int64>();\nInt64 length = (end - start) + 1;\nif (length < 2)\n{\n    Console.WriteLine(\"Insufficient Length of Random Numbers...\");\n    return listNumbers.ToArray();\n}\n\nRandom rand = new Random();\nInt64 number;\nfor (Int64 i = 0; i < length; i++)\n{\n    do\n    {\n        number = Int64.Parse(rand.Next(Int32.Parse(start.ToString()), Int32.Parse(end.ToString()) + 1).ToString());\n    } while (listNumbers.Contains(number));\n    listNumbers.Add(number);\n}\nreturn listNumbers.ToArray();\n}";
                                code += "\nprivate static string Substr(string str, Int64 index)\n{\nreturn str.Substring(Int32.Parse(index.ToString()));\n}\nprivate static string Substr(string str, Int64 index, Int64 length)\n{\nreturn str.Substring(Int32.Parse(index.ToString()), Int32.Parse(length.ToString()));\n}\nprivate static Int64 StrLen(string str)\n{\nreturn Int64.Parse(str.Length.ToString());\n}\npublic static Int64 PInt(string s)\n{\n    Int64 num = -1;\n bool p = false;\n  p = Int64.TryParse(s,out num);\n    return num;\n}";
                                code += "\npublic static char[] ToCharArray (string str)\n{\nreturn str.ToCharArray();\n}\n";
                                code += "\npublic static string ToUpper(string str)\n{\n    return str.ToUpper();\n}\n\npublic static string ToLower(string str)\n{\n    return str.ToLower();\n}\n";
                                code += "\n   private static double Sqrt(Int64 intNum)\n   {\n           return Double.Parse(Math.Sqrt(Int32.Parse(intNum.ToString())).ToString(\"0.00##\"));\n   }\n";
                                code += " \npublic static Int64 CompareTo(string a, string b)\n{\n    return Int64.Parse(a.CompareTo(b).ToString());\n}";
                                code += "\npublic static double PDouble(string s)\n{\n    double num = -1;\n bool p = false;\n  p = Double.TryParse(s,out num);\n    return num;\n}\n}\n";
                                if (generatedCode.Checked)
                                {
                                    MessageBox.Show(code);
                                }
                                if (consoleOutput.Checked)
                                {
                                    //OUTPUT
                                    OutputInitializer output = new OutputInitializer();
                                    output.Start(code);
                                    if (output.error != "")
                                    {
                                        Output.Text += "Semantic Error/s: \n" + output.error;
                                        MessageBox.Show("Code compiled with error.", "FAILED!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    else
                                    {
                                        Output.Text += "Static Semantics Analyzer Succeeded...";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public BaseExtendable createMTDQuote(int contact_iid, string projDesc, TMAMessage msg, IMTDService svc, UserSession us, Guid mtdGUID, int srcLangCID, int[] targetLangCIDs)
        {
            BaseExtendable newQuote = new BaseExtendable(Code.Find(AppCodes.PROJECT_TARGET_TYPE).CID);

            if (msg.name != null)
            {
                newQuote.Description = msg.name;
            }
            else
            {
                newQuote.Description = projDesc;
            }
            newQuote.OID = svc.NextSequenceNumber(true);
            svc.Store(newQuote);
            ///// Add Attributes
            /////////////////////////////////////////////////////////////////////////////////////

            //           int contact_iid = Convert.ToInt32(ConfigurationSettings.AppSettings["CONTACT_IID"]);

            Contact      contact        = svc.LoadContact(contact_iid);
            CustomerSite site           = svc.LoadCustomerSite(contact.Site_IID);
            int          salesPersonIID = site.Sales_Employee_IID;

            if (salesPersonIID == -1)
            {
                salesPersonIID = us.Current_User.Employee.Employee_IID; // vilma
            }

            Base.Attribute salesAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "SALESPERSON"), salesPersonIID);
            salesAttr.SetParent(newQuote.Attributes);

            Base.Attribute contactAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "CONTACT"), contact_iid);
            contactAttr.SetParent(newQuote.Attributes);
            // msg.status ='approved"
            Base.Attribute statusAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "STATUS"), Code.Find(10033));
            statusAttr.SetParent(newQuote.Attributes);
            // Quoted
            int perCt = 10;

            Base.Attribute pmPercentAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "PM_PERCENT"), perCt);
            pmPercentAttr.SetParent(newQuote.Attributes);

            decimal internalRate = 35;

            Base.Attribute internalRateAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "BASE_INTERNAL_RATE"), internalRate);
            internalRateAttr.SetParent(newQuote.Attributes);

            Base.Attribute sourceAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "SOURCE_LANG"), Code.Find(srcLangCID));
            sourceAttr.SetParent(newQuote.Attributes);
            int targetCID;
            int numLangs = targetLangCIDs.Length;

            for (int i = 0; i < numLangs; i++)
            {
                targetCID = targetLangCIDs[i];
                if (targetCID > 0)
                {
                    Base.Attribute targetLang = newQuote.Attributes.Add(CodeTranslator.Find("CTYPE", "LOC"), Code.Find(targetCID), 0);
                    targetLang.SetParent(newQuote.Attributes);
                }
            }

            /*
             * Base.Attribute budgetAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "BUDGET"), this.BudgetCheckBox.Checked);
             * budgetAttr.SetParent(newQuote.Attributes);
             * Base.Attribute rushAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "RUSH_JOB"), this.RushCheckBox.Checked);
             * rushAttr.SetParent(newQuote.Attributes);
             * Base.Attribute reverseAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "LANGUAGES_REVERSED"), this.ReverseCheckBox.Checked);
             * reverseAttr.SetParent(newQuote.Attributes);
             * Base.Attribute cleanAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "PRE_TRANS_CLEANING"), this.CleanCheckBox.Checked);
             * cleanAttr.SetParent(newQuote.Attributes);
             */

            //DateTime dTime = new DateTime(2012, 09, 01, 12, 00, 00);
            //String dTime;
            //dTime = defDTime.ToString("yyyy-MM-dd HH:mm tt");

            Base.Attribute dateQuoteStartAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "QUOTE_START_DT"), DateTime.Now);
            dateQuoteStartAttr.SetParent(newQuote.Attributes);

            Base.Attribute dateAssessStartAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "ASSESS_START_DT"), DateTime.Now);
            dateAssessStartAttr.SetParent(newQuote.Attributes);

            Base.Attribute dateQuoteDueeAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "QUOTE_DUE_DT"), DateTime.Now.AddDays(1));
            dateQuoteDueeAttr.SetParent(newQuote.Attributes);

            Base.Attribute dateAsessDueAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "ASSESS_DUE_DT"), DateTime.Now.AddDays(1));
            dateAsessDueAttr.SetParent(newQuote.Attributes);

            /*
             * Base.Attribute dateAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "PROJECT_DUE_DT"), dTime);
             *  dateAttr.SetParent(newQuote.Attributes);
             * Base.Attribute dateAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "PROD_DUE_DT"), dTime);
             *  dateAttr.SetParent(newQuote.Attributes);
             */

            svc.Store(newQuote);


            msg.quoteOID = newQuote.OID;
            // Update Quote if first
            ProspectCollection prospects = svc.LoadProspectCollection(Convert.ToInt32("5157"));

            if (prospects.Count > 0)
            {
                Prospect updateProspect = (Prospect)prospects[0];
                if (updateProspect.Quote_IID == -1)
                {
                    updateProspect.Quote_IID = newQuote.Entity_IID;
                    svc.Store(updateProspect);
                }
            }

            BaseExtendable m_project = newQuote;

            return(m_project);
        }
        public BaseExtendable createMTDProject(int contact_iid, string projDesc, TMAMessage msg, IMTDService svc, UserSession us, Guid mtdGUID, int srcLangCID, int[] targetLangCIDs, bool monthlyFlag)
        {
            BaseExtendable newQuote = new BaseExtendable(Code.Find(AppCodes.PROJECT_TARGET_TYPE).CID);

            if (msg.name != null)
            {
                newQuote.Description = msg.name;
            }
            else
            {
                newQuote.Description = projDesc;
            }
            newQuote.OID = svc.NextSequenceNumber(true);
            svc.Store(newQuote);
            ///// Add Attributes
            /////////////////////////////////////////////////////////////////////////////////////

            //           int contact_iid = Convert.ToInt32(ConfigurationSettings.AppSettings["CONTACT_IID"]);

            Contact      contact        = svc.LoadContact(contact_iid);
            CustomerSite site           = svc.LoadCustomerSite(contact.Site_IID);
            int          salesPersonIID = site.Sales_Employee_IID;

            if (salesPersonIID == -1)
            {
                salesPersonIID = us.Current_User.Employee.Employee_IID; // vilma
            }

            Base.Attribute salesAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "SALESPERSON"), salesPersonIID);
            salesAttr.SetParent(newQuote.Attributes);

            Base.Attribute contactAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "CONTACT"), contact_iid);
            contactAttr.SetParent(newQuote.Attributes);
            // msg.status ='approved"
            Base.Attribute statusAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "STATUS"), Code.Find(10033));
            statusAttr.SetParent(newQuote.Attributes);
            // Quoted
            decimal perCt = 10;

            Base.Attribute pmPercentAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "PM_PERCENT"), perCt);
            pmPercentAttr.SetParent(newQuote.Attributes);

            decimal internalRate = 35;

            Base.Attribute internalRateAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "BASE_INTERNAL_RATE"), internalRate);
            internalRateAttr.SetParent(newQuote.Attributes);                                            // use default from MTD web config

            Base.Attribute sourceAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "SOURCE_LANG"), Code.Find(srcLangCID));
            sourceAttr.SetParent(newQuote.Attributes);
            int targetCID;
            int numLangs = targetLangCIDs.Length;

            for (int i = 0; i < numLangs; i++)
            {
                targetCID = targetLangCIDs[i];
                if (targetCID > 0)
                {
                    Base.Attribute targetLang = newQuote.Attributes.Add(CodeTranslator.Find("CTYPE", "LOC"), Code.Find(targetCID), 0);
                    targetLang.SetParent(newQuote.Attributes);
                }
            }

            /*
             * Base.Attribute budgetAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "BUDGET"), this.BudgetCheckBox.Checked);
             * budgetAttr.SetParent(newQuote.Attributes);
             * Base.Attribute rushAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "RUSH_JOB"), this.RushCheckBox.Checked);
             * rushAttr.SetParent(newQuote.Attributes);
             * Base.Attribute reverseAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "LANGUAGES_REVERSED"), this.ReverseCheckBox.Checked);
             * reverseAttr.SetParent(newQuote.Attributes);
             * Base.Attribute cleanAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "PRE_TRANS_CLEANING"), this.CleanCheckBox.Checked);
             * cleanAttr.SetParent(newQuote.Attributes);
             */

            //DateTime dTime = new DateTime(2012, 09, 01, 12, 00, 00);
            //String dTime;
            //dTime = defDTime.ToString("yyyy-MM-dd HH:mm tt");

            Base.Attribute dateQuoteStartAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "QUOTE_START_DT"), DateTime.Now);
            dateQuoteStartAttr.SetParent(newQuote.Attributes);

            Base.Attribute dateAssessStartAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "ASSESS_START_DT"), DateTime.Now);
            dateAssessStartAttr.SetParent(newQuote.Attributes);

            Base.Attribute dateQuoteDueeAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "QUOTE_DUE_DT"), DateTime.Now.AddDays(1));
            dateQuoteDueeAttr.SetParent(newQuote.Attributes);

            Base.Attribute dateAsessDueAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "ASSESS_DUE_DT"), DateTime.Now.AddDays(1));
            dateAsessDueAttr.SetParent(newQuote.Attributes);

            /*
             * Base.Attribute dateAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "ASSESS_DUE_DT"), dTime);
             *  dateAttr.SetParent(newQuote.Attributes);
             *
             * Base.Attribute dateAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "PROJECT_DUE_DT"), dTime);
             *  dateAttr.SetParent(newQuote.Attributes);
             * Base.Attribute dateAttr = newQuote.Attributes.Add(Code.Find("PROJECT_ATTR", "PROD_DUE_DT"), dTime);
             *  dateAttr.SetParent(newQuote.Attributes);
             */

            svc.Store(newQuote);


            msg.quoteOID = newQuote.OID;



            //convert Quote to Project
            string projectNum = svc.NextSequenceNumber(false);

            BaseExtendable m_project = newQuote;

            Code statusCode = Code.Find("PROJECT_STATUS", "LINGUISTIC");

            statusAttr = m_project.Attributes.Find(CodeTranslator.Find("PROJECT_ATTR", "STATUS"));
            if (statusAttr == null)
            {
                statusAttr = m_project.Attributes.Add(CodeTranslator.Find("PROJECT_ATTR", "STATUS"), statusCode);
                statusAttr.SetParent(m_project.Attributes);
            }
            else
            {
                statusAttr.Value = statusCode;
            }
            Base.Attribute projStartDate = m_project.Attributes.Add(Code.Find("PROJECT_ATTR", "PROJECT_START_DT"), DateTime.Now);
            projStartDate.SetParent(m_project.Attributes);

            Base.Attribute prodStartDate = m_project.Attributes.Add(Code.Find("PROJECT_ATTR", "PROD_START_DT"), DateTime.Now);
            prodStartDate.SetParent(m_project.Attributes);


            Base.Attribute monthlyAttr = m_project.Attributes.Find(CodeTranslator.Find("PROJECT_ATTR", "MONTHLY"));
            if (monthlyAttr == null && monthlyFlag == true)
            {
                monthlyAttr = m_project.Attributes.Add(CodeTranslator.Find("PROJECT_ATTR", "MONTHLY"), monthlyFlag);
                monthlyAttr.SetParent(m_project.Attributes);
            }

            m_project.Attributes.Add(CodeTranslator.Find("PROJECT_ATTR", "PROJECTNUM"), projectNum);

            bool itar = false;

            Base.Attribute itarAttr = m_project.Attributes.Find(CodeTranslator.Find("PROJECT_ATTR", "ITAR"));
            if (itarAttr != null)
            {
                itar = ((bool)itarAttr.Value);
                itarAttr.SetParent(m_project.Attributes);
            }

            svc.Store(m_project);
            return(m_project);
        }