示例#1
0
 private void ToolStripBotComboSelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         Professionbuddy.ChangeSecondaryBot((string)toolStripBotCombo.SelectedItem);
     }
     catch (Exception ex)
     {
         Professionbuddy.Err(ex.ToString());
     }
 }
示例#2
0
        public PBIdentityComposite LoadFromFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    Professionbuddy.Log("Loading profile {0}", path);
                    ProfilePath = path;

                    if (Path.GetExtension(path).Equals(".package", StringComparison.InvariantCultureIgnoreCase))
                    {
                        using (Package zipFile = Package.Open(path, FileMode.Open, FileAccess.Read))
                        {
                            var packageRelation = zipFile.GetRelationships().FirstOrDefault();
                            if (packageRelation == null)
                            {
                                Professionbuddy.Err("{0} contains no usable profiles", path);
                                return(null);
                            }
                            PackagePart pbProfilePart = zipFile.GetPart(packageRelation.TargetUri);
                            path = ExtractPart(pbProfilePart, _pb.TempFolder);
                            var pbProfileRelations = pbProfilePart.GetRelationships();
                            foreach (var rel in pbProfileRelations)
                            {
                                var hbProfilePart = zipFile.GetPart(rel.TargetUri);
                                ExtractPart(hbProfilePart, _pb.TempFolder);
                            }
                        }
                    }
                    Branch.Children.Clear();
                    PBIdentityComposite idComp;
                    XmlReaderSettings   settings = new XmlReaderSettings();
                    settings.IgnoreWhitespace             = true;
                    settings.IgnoreProcessingInstructions = true;
                    settings.IgnoreComments = true;

                    using (XmlReader reader = XmlReader.Create(path, settings))
                    {
                        idComp = new PBIdentityComposite(Branch);
                        idComp.ReadXml(reader);
                    }
                    XmlPath = path;
                    return(idComp);
                }
                else
                {
                    Professionbuddy.Err("Profile: {0} does not exist", path);
                    return(null);
                }
            }
            catch (Exception ex) { Professionbuddy.Err(ex.ToString()); return(null); }
        }
示例#3
0
        public MainForm()
        {
            try
            {
                Instance = this;
                _pb      = Professionbuddy.Instance;
                InitializeComponent();
                // assign the localized strings
                toolStripOpen.Text            = _pb.Strings["UI_FileOpen"];
                toolStripSave.Text            = _pb.Strings["UI_FileSave"];
                toolStripHelp.Text            = _pb.Strings["UI_Help"];
                toolStripCopy.Text            = _pb.Strings["UI_Copy"];
                toolStripCut.Text             = _pb.Strings["UI_Cut"];
                toolStripPaste.Text           = _pb.Strings["UI_Paste"];
                toolStripDelete.Text          = _pb.Strings["UI_Delete"];
                toolStripBotConfigButton.Text = _pb.Strings["UI_Settings"];
                ProfileTab.Text              = _pb.Strings["UI_Profiles"];
                ActionsColumn.HeaderText     = ActionsTab.Text = _pb.Strings["UI_Actions"];
                TradeSkillTab.Text           = _pb.Strings["UI_Tradeskill"];
                TabPageProfile.Text          = _pb.Strings["UI_Profile"];
                IngredientsColumn.HeaderText = _pb.Strings["UI_Ingredients"];
                NeedColumn.HeaderText        = _pb.Strings["UI_Need"];
                BagsColumn.HeaderText        = _pb.Strings["UI_Bags"];
                BankColumn.HeaderText        = _pb.Strings["UI_Bank"];
                toolStripAddBtn.Text         = _pb.Strings["UI_Add"];
                toolStripReloadBtn.Text      = _pb.Strings["UI_Reload"];
                LoadProfileButton.Text       = _pb.Strings["UI_LoadProfile"];

                saveFileDialog.InitialDirectory = _pb.ProfilePath;
                _profileWatcher = new FileSystemWatcher(_pb.ProfilePath)
                {
                    NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName
                };
                _profileWatcher.Changed            += ProfileWatcherChanged;
                _profileWatcher.Created            += ProfileWatcherChanged;
                _profileWatcher.Deleted            += ProfileWatcherChanged;
                _profileWatcher.Renamed            += ProfileWatcherChanged;
                _profileWatcher.EnableRaisingEvents = true;

                // used by the dev to display the 'Secret button', a button that dumps some debug info of the Task list.
                if (Environment.UserName == "highvoltz")
                {
                    toolStripSecretButton.Visible = true;
                }
            }
            catch (Exception ex)
            {
                Professionbuddy.Err(ex.ToString());
            }
        }
示例#4
0
 public static void CheckForUpdate()
 {
     try
     {
         Professionbuddy.Log("Checking for new version");
         {
             Professionbuddy.Log("A new version was found.Downloading Update");
             Professionbuddy.Log("Download complete :P");
             Logging.Write(Color.DodgerBlue, "************* Change Log ****************");
             Logging.Write(Color.DodgerBlue, "*****************************************");
         }
     }
     catch (Exception ex)
     {
         Professionbuddy.Err(ex.ToString());
     }
 }
示例#5
0
        /// <summary>
        /// Profile behavior.
        /// </summary>
        //public PrioritySelector Branch { get; protected set; }
        public PbDecorator LoadFromFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    ProfilePath = path;

                    string extension = Path.GetExtension(path);
                    if (extension != null && extension.Equals(".package", StringComparison.InvariantCultureIgnoreCase))
                    {
                        using (Package zipFile = Package.Open(path, FileMode.Open, FileAccess.Read))
                        {
                            PackageRelationship packageRelation = zipFile.GetRelationships().FirstOrDefault();
                            if (packageRelation == null)
                            {
                                Professionbuddy.Err("{0} contains no usable profiles", path);
                                return(null);
                            }
                            PackagePart pbProfilePart = zipFile.GetPart(packageRelation.TargetUri);
                            path = ExtractPart(pbProfilePart, DynamicCodeCompiler.TempFolder);
                            PackageRelationshipCollection pbProfileRelations = pbProfilePart.GetRelationships();
                            foreach (PackageRelationship rel in pbProfileRelations)
                            {
                                PackagePart hbProfilePart = zipFile.GetPart(rel.TargetUri);
                                ExtractPart(hbProfilePart, DynamicCodeCompiler.TempFolder);
                            }
                        }
                    }
                    XmlPath = path;
                    return((PbDecorator)Load(XElement.Load(path), new PbDecorator()));
                }
                Professionbuddy.Err("Profile: {0} does not exist", path);
                return(null);
            }
            catch (Exception ex)
            {
                Professionbuddy.Err(ex.ToString());
                return(null);
            }
        }
示例#6
0
        // used to update GUI controls via other threads

        #region Initalize/update methods
        public MainForm()
        {
            Instance = this;
            PB = Professionbuddy.Instance;
            InitializeComponent();
            saveFileDialog.InitialDirectory = PB.ProfilePath;

            profileWatcher = new FileSystemWatcher(PB.ProfilePath);
            profileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
            profileWatcher.Changed += profileWatcher_Changed;
            profileWatcher.Created += profileWatcher_Changed;
            profileWatcher.Deleted += profileWatcher_Changed;
            profileWatcher.Renamed += profileWatcher_Changed;
            profileWatcher.EnableRaisingEvents = true;

            // used by the dev to display the 'Secret button', a button that dumps some debug info of the Task list.
            if (Environment.UserName == "highvoltz")
            {
                toolStripSecretButton.Visible = true;
            }
        }
示例#7
0
 private void toolStripSave_Click(object sender, EventArgs e)
 {
     saveFileDialog.DefaultExt = "xml";
     saveFileDialog.FilterIndex = 1;
     if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         bool zip = Path.GetExtension(saveFileDialog.FileName).Equals(".package", StringComparison.InvariantCultureIgnoreCase);
         // if we are saving to a zip check if CurrentProfile.XmlPath is not blank/null and use it if not. 
         // otherwise use the selected zipname with xml ext.
         string xmlfile = zip ? (string.IsNullOrEmpty(PB.CurrentProfile.XmlPath) ?
             Path.ChangeExtension(saveFileDialog.FileName, ".xml") : PB.CurrentProfile.XmlPath)
             : saveFileDialog.FileName;
         Professionbuddy.Log("Packaging profile to {0}", saveFileDialog.FileName);
         PB.CurrentProfile.SaveXml(xmlfile);
         if (zip)
             PB.CurrentProfile.CreatePackage(saveFileDialog.FileName, xmlfile);
         PB.MySettings.LastProfile = saveFileDialog.FileName;
         PB.MySettings.Save();
         UpdateControls();
     }
 }
示例#8
0
        private static void DownloadFilesFromSvn(WebClient client, string url)
        {
            string          html    = client.DownloadString(url);
            MatchCollection results = _linkPattern.Matches(html);

            IEnumerable <Match> matches = from match in results.OfType <Match>()
                                          where match.Success && match.Groups["ln"].Success
                                          select match;

            foreach (Match match in matches)
            {
                string file   = RemoveXmlEscapes(match.Groups["ln"].Value);
                string newUrl = url + file;
                if (newUrl[newUrl.Length - 1] == '/') // it's a directory...
                {
                    DownloadFilesFromSvn(client, newUrl);
                }
                else // its a file.
                {
                    string filePath, dirPath;
                    if (url.Length > PbSvnUrl.Length)
                    {
                        string relativePath = url.Substring(PbSvnUrl.Length);
                        dirPath  = Path.Combine(Professionbuddy.BotPath, relativePath);
                        filePath = Path.Combine(dirPath, file);
                    }
                    else
                    {
                        dirPath  = Environment.CurrentDirectory;
                        filePath = Path.Combine(Professionbuddy.BotPath, file);
                    }
                    Professionbuddy.Debug("Downloading {0}", file);
                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }
                    client.DownloadFile(newUrl, filePath);
                }
            }
        }
 // test some culture specific stuff.
 public Professionbuddy()
 {
     Instance = this;
     new Thread((ThreadStart) delegate
     {
         try
         {
             var mod = Process.GetCurrentProcess().MainModule;
             using (HashAlgorithm hashAlg = new SHA1Managed())
             {
                 using (Stream file = new FileStream(mod.FileName, FileMode.Open, FileAccess.Read))
                 {
                     byte[] hash = hashAlg.ComputeHash(file);
                     Logging.WriteDebug("H: {0}", BitConverter.ToString(hash));
                 }
             }
             var vInfo = mod.FileVersionInfo;
             Logging.WriteDebug("V: {0}", vInfo.FileVersion);
         }
         catch { }
     }).Start();
 }
示例#10
0
        public void CreatePackage(string path, string profilePath)
        {
            try
            {
                Uri partUriProfile = PackUriHelper.CreatePartUri(
                    new Uri(Path.GetFileName(profilePath), UriKind.Relative));
                var hbProfileUrls = new Dictionary <string, Uri>();
                GetHbprofiles(profilePath, Professionbuddy.Instance.PbBehavior, hbProfileUrls);
                using (Package package = Package.Open(path, FileMode.Create))
                {
                    // Add the PB profile
                    PackagePart packagePartDocument =
                        package.CreatePart(partUriProfile, MediaTypeNames.Text.Xml, CompressionOption.Normal);
                    using (var fileStream = new FileStream(
                               profilePath, FileMode.Open, FileAccess.Read))
                    {
                        CopyStream(fileStream, packagePartDocument.GetStream());
                    }
                    package.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, PackageRelationshipType);

                    foreach (var kv in hbProfileUrls)
                    {
                        PackagePart packagePartHbProfile =
                            package.CreatePart(kv.Value, MediaTypeNames.Text.Xml, CompressionOption.Normal);

                        using (var fileStream = new FileStream(kv.Key, FileMode.Open, FileAccess.Read))
                        {
                            CopyStream(fileStream, packagePartHbProfile.GetStream());
                        }
                        packagePartDocument.CreateRelationship(kv.Value, TargetMode.Internal, ResourceRelationshipType);
                    }
                }
            }
            catch (Exception ex)
            {
                Professionbuddy.Err(ex.ToString());
            }
        }
示例#11
0
 private void ToolStripSaveClick(object sender, EventArgs e)
 {
     saveFileDialog.DefaultExt  = "xml";
     saveFileDialog.FilterIndex = 1;
     saveFileDialog.FileName    = _pb.CurrentProfile != null && _pb.CurrentProfile.XmlPath != null
                                   ? _pb.CurrentProfile.XmlPath
                                   : "";
     if (saveFileDialog.ShowDialog() == DialogResult.OK)
     {
         string extension = Path.GetExtension(saveFileDialog.FileName);
         bool   zip       = extension != null && extension.Equals(".package",
                                                                  StringComparison.InvariantCultureIgnoreCase);
         // if we are saving to a zip check if CurrentProfile.XmlPath is not blank/null and use it if not.
         // otherwise use the selected zipname with xml ext.
         if (_pb.CurrentProfile != null)
         {
             string xmlfile = zip
                                  ? (_pb.CurrentProfile != null &&
                                     string.IsNullOrEmpty(_pb.CurrentProfile.XmlPath)
                                         ? Path.ChangeExtension(saveFileDialog.FileName, ".xml")
                                         : _pb.CurrentProfile.XmlPath)
                                  : saveFileDialog.FileName;
             Professionbuddy.Log("Saving profile to {0}", saveFileDialog.FileName);
             if (_pb.CurrentProfile != null)
             {
                 _pb.CurrentProfile.SaveXml(xmlfile);
                 if (zip)
                 {
                     _pb.CurrentProfile.CreatePackage(saveFileDialog.FileName, xmlfile);
                 }
             }
         }
         _pb.MySettings.LastProfile = saveFileDialog.FileName;
         _pb.MySettings.Save();
         UpdateControls();
     }
 }
示例#12
0
        public MainForm()
        {
            try
            {
                Instance = this;
                _pb = Professionbuddy.Instance;
                InitializeComponent();
                // assign the localized strings
                toolStripOpen.Text = _pb.Strings["UI_FileOpen"];
                toolStripSave.Text = _pb.Strings["UI_FileSave"];
                toolStripHelp.Text = _pb.Strings["UI_Help"];
                toolStripCopy.Text = _pb.Strings["UI_Copy"];
                toolStripCut.Text = _pb.Strings["UI_Cut"];
                toolStripPaste.Text = _pb.Strings["UI_Paste"];
                toolStripDelete.Text = _pb.Strings["UI_Delete"];
                toolStripBotConfigButton.Text = _pb.Strings["UI_Settings"];
                ProfileTab.Text = _pb.Strings["UI_Profiles"];
                ActionsColumn.HeaderText = ActionsTab.Text = _pb.Strings["UI_Actions"];
                TradeSkillTab.Text = _pb.Strings["UI_Tradeskill"];
                TabPageProfile.Text = _pb.Strings["UI_Profile"];
                IngredientsColumn.HeaderText = _pb.Strings["UI_Ingredients"];
                NeedColumn.HeaderText = _pb.Strings["UI_Need"];
                BagsColumn.HeaderText = _pb.Strings["UI_Bags"];
                BankColumn.HeaderText = _pb.Strings["UI_Bank"];
                toolStripAddBtn.Text = _pb.Strings["UI_Add"];
                toolStripReloadBtn.Text = _pb.Strings["UI_Reload"];
                LoadProfileButton.Text = _pb.Strings["UI_LoadProfile"];

                saveFileDialog.InitialDirectory = _pb.ProfilePath;
                _profileWatcher = new FileSystemWatcher(_pb.ProfilePath)
                                      {NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName};
                _profileWatcher.Changed += ProfileWatcherChanged;
                _profileWatcher.Created += ProfileWatcherChanged;
                _profileWatcher.Deleted += ProfileWatcherChanged;
                _profileWatcher.Renamed += ProfileWatcherChanged;
                _profileWatcher.EnableRaisingEvents = true;

                // used by the dev to display the 'Secret button', a button that dumps some debug info of the Task list.
                if (Environment.UserName == "highvoltz")
                {
                    toolStripSecretButton.Visible = true;
                }
            }
            catch (Exception ex)
            {
                Professionbuddy.Err(ex.ToString());
            }
        }
示例#13
0
 private XElement Save(XElement xml, GroupComposite comp)
 {
     foreach (IPBComposite pbComp in comp.Children)
     {
         if (pbComp is Comment)
         {
             xml.Add(new XComment(((Comment)pbComp).Text));
         }
         else
         {
             var newElement = new XElement(pbComp.GetType().Name);
             var rootAttr   =
                 (XmlRootAttribute)
                 pbComp.GetType().GetCustomAttributes(typeof(XmlRootAttribute), true).FirstOrDefault();
             if (rootAttr != null)
             {
                 newElement.Name = rootAttr.ElementName;
             }
             pbComp.OnProfileSave(newElement);
             List <PropertyInfo> piList = pbComp.GetType().GetProperties().
                                          Where(p => p.GetCustomAttributes(typeof(PbXmlAttributeAttribute), true).
                                                Any()).ToList();
             foreach (PropertyInfo pi in piList)
             {
                 List <PbXmlAttributeAttribute> pList =
                     ((PbXmlAttributeAttribute[])pi.GetCustomAttributes(typeof(PbXmlAttributeAttribute), true))
                     .ToList();
                 string name              = pList.Any(a => a.AttributeName == null) ? pi.Name : pList[0].AttributeName;
                 string value             = "";
                 var    typeConverterAttr =
                     (TypeConverterAttribute)
                     pi.GetCustomAttributes(typeof(TypeConverterAttribute), true).FirstOrDefault();
                 if (typeConverterAttr != null)
                 {
                     try
                     {
                         var typeConverter =
                             (TypeConverter)
                             Activator.CreateInstance(Type.GetType(typeConverterAttr.ConverterTypeName));
                         if (typeConverter.CanConvertTo(typeof(string)))
                         {
                             value = (string)typeConverter.ConvertTo(pi.GetValue(pbComp, null), typeof(string));
                         }
                         else
                         {
                             Professionbuddy.Err("The TypeConvert {0} can not convert to string.",
                                                 typeConverterAttr.ConverterTypeName);
                         }
                     }
                     catch (Exception ex)
                     {
                         Professionbuddy.Err("Type conversion for {0}->{1} has failed.\n{2}", comp.GetType().Name,
                                             pi.Name, ex);
                     }
                 }
                 else
                 {
                     value = pi.GetValue(pbComp, null).ToString();
                 }
                 newElement.Add(new XAttribute(name, value));
             }
             if (pbComp is GroupComposite)
             {
                 Save(newElement, (GroupComposite)pbComp);
             }
             xml.Add(newElement);
         }
     }
     return(xml);
 }
示例#14
0
 public MaterialListForm()
 {
     InitializeComponent();
     PB = Professionbuddy.Instance;
 }
示例#15
0
        public void ImportDataStore()
        {
            Clear();
            int tableIndex = 1;

            if (_settings.DataStoreTable == null)
            {
                _settings.DataStoreTable = Util.RandomString;
            }
            string storeInTableLua =
                "if DataStoreDB and DataStore_ContainersDB  and DataStore_AuctionsDB and DataStore_MailsDB then " +
                "local realm = GetRealmName() " +
                "local faction = UnitFactionGroup('player') " +
                "local profiles = {} " +
                "local items = {} " +
                "local guilds = {} " +
                "local storeItem = function (id,cnt) id=tonumber(id) cnt=tonumber(cnt) if items[id]  then items[id] = items[id] + cnt else items[id] = cnt end end " +
                "for k,v in pairs(DataStoreDB.global.Characters) do " +
                @"local r = string.match(k,'[^%.]+%.([^%.]+)%.[^%.]+') " +
                "if r and r == realm and v and v.faction == faction then " +
                "table.insert (profiles,k) " +
                "if v.guildName then " +
                "guilds[string.format('%s.%s',realm,v.guildName)] = 1 " +
                "end " +
                "end " +
                "end " +
                "for k,v in ipairs(profiles) do " +
                "local char=DataStore_ContainersDB.global.Characters[v] " +
                "if char then " +
                "for i=-2,100 do " +
                "local x = char.Containers['Bag'..i] " +
                "if x then " +
                "for i=1, x.size do " +
                "if x.ids[i] then " +
                "storeItem (x.ids[i],x.counts[i] or 1) " +
                "end " +
                "end " +
                "end " +
                "end " +
                "end " +
                "char=DataStore_AuctionsDB.global.Characters[v] " +
                "if char and char.Auctions then " +
                "for k,v in ipairs(char.Auctions) do " +
                "storeItem(string.match(v,'%d+|(%d+)'),string.match(v,'%d+|%d+|(%d+)')) " +
                "end " +
                "end " +
                "char=DataStore_MailsDB.global.Characters[v] " +
                "if char then " +
                "for k,v in pairs(char.Mails) do " +
                "if v.link and v.count then " +
                "storeItem(string.match(v.link,'|Hitem:(%d+)'),v.count) " +
                "end " +
                "end " +
                "end " +
                "end " +
                "for k,v in pairs(DataStore_ContainersDB.global.Guilds) do " +
                "for g,_ in pairs(guilds) do " +
                "if string.find(k,g) and v.Tabs then " +
                "for k2,v2 in ipairs(v.Tabs) do " +
                "if v2 and v2.ids then " +
                "for k3,v3 in pairs(v2.ids) do " +
                "storeItem (v3,v2.counts[k3] or 1) " +
                "end " +
                "end " +
                "end " +
                "end " +
                "end " +
                "end " +
                _settings.DataStoreTable + " = {} " +
                "for k,v in pairs(items) do " +
                "table.insert(" + _settings.DataStoreTable + ",k) " +
                "table.insert(" + _settings.DataStoreTable + ",v) " +
                "end " +
                "return #" + _settings.DataStoreTable + " " +
                "end " +
                "return 0 ";

            using (new FrameLock())
            {
                List <string> retVals = Lua.GetReturnValues(storeInTableLua);
                if (retVals != null && retVals[0] != "0")
                {
                    HasDataStoreAddon = true;
                    int tableSize;
                    int.TryParse(retVals[0], out tableSize);
                    while (true)
                    {
                        string getTableDataLua =
                            "local retVals = {" + tableIndex + "} " +
                            "for i=retVals[1], #" + _settings.DataStoreTable + " do " +
                            "table.insert(retVals," + _settings.DataStoreTable + "[i]) " +
                            "if #retVals >= 501 then " +
                            "retVals[1] = i +1 " +
                            "return unpack(retVals) " +
                            "end " +
                            "end " +
                            "retVals[1] = #" + _settings.DataStoreTable + " " +
                            "return unpack(retVals) ";
                        retVals = Lua.GetReturnValues(getTableDataLua);
                        int.TryParse(retVals[0], out tableIndex);
                        for (int i = 2; i < retVals.Count; i += 2)
                        {
                            uint id, num;
                            uint.TryParse(retVals[i - 1], out id);
                            uint.TryParse(retVals[i], out num);
                            this[id] = (int)num;
                        }
                        if (tableIndex >= tableSize)
                        {
                            break;
                        }
                    }
                    Lua.DoString(_settings.DataStoreTable + "={}");
                    Professionbuddy.Debug("DataStore Imported");
                }
                else
                {
                    Professionbuddy.Debug("No DataStore Addon found");
                }
            }
        }
示例#16
0
        public Type CompileAndLoad()
        {
            CompilerResults results = null;

            using (CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary <string, string>()
            {
                { "CompilerVersion", "v3.5" },
            }))
            {
                CompilerParameters options = new CompilerParameters();
                foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (!asm.GetName().Name.Contains(Name))
                    {
                        options.ReferencedAssemblies.Add(asm.Location);
                    }
                }
                options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

                // disabled due to a bug in 2.0.0.3956;
                //options.GenerateInMemory = true;
                options.GenerateExecutable      = false;
                options.TempFiles               = new TempFileCollection(TempFolder, false);
                options.IncludeDebugInformation = false;
                options.OutputAssembly          = string.Format("{0}\\CodeAssembly{1:N}.dll", TempFolder, Guid.NewGuid());
                options.CompilerOptions         = "/optimize";
                CsharpStringBuilder             = new StringBuilder();
                CsharpStringBuilder.Append(prefix);
                // Line numbers are used to identify actions that genorated compile errors.
                int currentLine = CsharpStringBuilder.ToString().Count(c => c == '\n') + 1;
                // genorate CanRun Methods
                foreach (var met in CsharpCodeDict)
                {
                    if (met.Value.CodeType == CsharpCodeType.BoolExpression)
                    {
                        CsharpStringBuilder.AppendFormat("public bool {0} (object context){{return {1};}}\n", met.Key, met.Value.Code);
                    }
                    else if (met.Value.CodeType == CsharpCodeType.Statements)
                    {
                        CsharpStringBuilder.AppendFormat("public void {0} (object context){{{1}}}\n", met.Key, met.Value.Code);
                    }
                    met.Value.CodeLineNumber = currentLine++;
                }
                CsharpStringBuilder.Append(postfix);
                results = provider.CompileAssemblyFromSource(
                    options, CsharpStringBuilder.ToString());
            }
            if (results.Errors.HasErrors)
            {
                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError error in results.Errors)
                    {
                        ICSharpCode icsc = CsharpCodeDict.Values.FirstOrDefault(c => c.CodeLineNumber == error.Line);
                        if (icsc != null)
                        {
                            Professionbuddy.Err("{0}\nCompile Error : {1}\n", ((IPBComposite)icsc).Title, error.ErrorText);
                            icsc.CompileError = error.ErrorText;
                        }
                        else
                        {
                            Professionbuddy.Err("Unable to link action that produced Error: {0}", error.ErrorText);
                        }
                    }
                    MainForm.Instance.RefreshActionTree(typeof(ICSharpCode));
                }
                return(null);
            }
            else
            {
                CodeWasModified = false;
                return(results.CompiledAssembly.GetType("CodeDriver"));
            }
        }
示例#17
0
 // test some culture specific stuff.
 public Professionbuddy()
 {
     Instance = this;
 }
示例#18
0
        private GroupComposite Load(XElement xml, GroupComposite comp)
        {
            foreach (XNode node in xml.Nodes())
            {
                if (node.NodeType == XmlNodeType.Comment)
                {
                    comp.AddChild(new Comment(((XComment)node).Value));
                }
                else if (node.NodeType == XmlNodeType.Element)
                {
                    var  element = (XElement)node;
                    Type type    = Type.GetType("HighVoltz.Composites." + element.Name);
                    if (type == null)
                    {
                        IEnumerable <Type> pbTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                                     where (typeof(IPBComposite)).IsAssignableFrom(t) && !t.IsAbstract
                                                     select t;
                        type =
                            pbTypes.FirstOrDefault(
                                t =>
                                t.GetCustomAttributes(typeof(XmlRootAttribute), true).Any(
                                    a => ((XmlRootAttribute)a).ElementName == element.Name));
                        if (type == null)
                        {
                            throw new InvalidOperationException(
                                      string.Format("Unable to bind XML Element: {0} to a Type", element.Name));
                        }
                    }
                    var pbComp = (IPBComposite)Activator.CreateInstance(type);
                    pbComp.OnProfileLoad(element);
                    var pbXmlAttrs = from pi in type.GetProperties()
                                     from attr in
                                     (PbXmlAttributeAttribute[])
                                     pi.GetCustomAttributes(typeof(PbXmlAttributeAttribute), true)
                                     where attr != null
                                     let name = attr.AttributeName ?? pi.Name
                                                select new { name, pi };

                    Dictionary <string, PropertyInfo> piDict     = pbXmlAttrs.ToDictionary(kv => kv.name, kv => kv.pi);
                    Dictionary <string, string>       attributes = element.Attributes().ToDictionary(k => k.Name.ToString(),
                                                                                                     v => v.Value);
                    // use legacy X,Y,Z location for backwards compatability
                    if (attributes.ContainsKey("X"))
                    {
                        string location = string.Format("{0},{1},{2}", attributes["X"], attributes["Y"], attributes["Z"]);
                        piDict["Location"].SetValue(pbComp, location, null);
                        attributes.Remove("X");
                        attributes.Remove("Y");
                        attributes.Remove("Z");
                    }
                    foreach (var attr in attributes)
                    {
                        if (piDict.ContainsKey(attr.Key))
                        {
                            PropertyInfo pi = piDict[attr.Key];
                            // check if there is a type converter attached
                            var typeConverterAttr =
                                (TypeConverterAttribute)
                                pi.GetCustomAttributes(typeof(TypeConverterAttribute), true).FirstOrDefault();
                            if (typeConverterAttr != null)
                            {
                                try
                                {
                                    var typeConverter =
                                        (TypeConverter)
                                        Activator.CreateInstance(Type.GetType(typeConverterAttr.ConverterTypeName));
                                    if (typeConverter.CanConvertFrom(typeof(string)))
                                    {
                                        pi.SetValue(pbComp,
                                                    typeConverter.ConvertFrom(null, CultureInfo.CurrentCulture,
                                                                              attr.Value), null);
                                    }
                                    else
                                    {
                                        Professionbuddy.Err("The TypeConvert {0} can not convert from string.",
                                                            typeConverterAttr.ConverterTypeName);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Professionbuddy.Err("Type conversion for {0} has failed.\n{1}", type.Name + attr.Key,
                                                        ex);
                                }
                            }
                            else
                            {
                                pi.SetValue(pbComp,
                                            pi.PropertyType.IsEnum
                                                ? Enum.Parse(pi.PropertyType, attr.Value)
                                                : Convert.ChangeType(attr.Value, pi.PropertyType), null);
                            }
                        }
                        else
                        {
                            Professionbuddy.Log("{0}->{1} appears to be unused", type, attr.Key);
                        }
                    }
                    if (pbComp is GroupComposite)
                    {
                        Load(element, pbComp as GroupComposite);
                    }
                    comp.AddChild((Composite)pbComp);
                }
            }
            return(comp);
        }
示例#19
0
 public MaterialListForm()
 {
     InitializeComponent();
     PB = Professionbuddy.Instance;
 }
示例#20
0
        public MainForm()
        {
            try
            {
                Instance = this;
                _pb = Professionbuddy.Instance;
                InitializeComponent();
                saveFileDialog.InitialDirectory = _pb.ProfilePath;

                _profileWatcher = new FileSystemWatcher(_pb.ProfilePath) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName };
                _profileWatcher.Changed += ProfileWatcherChanged;
                _profileWatcher.Created += ProfileWatcherChanged;
                _profileWatcher.Deleted += ProfileWatcherChanged;
                _profileWatcher.Renamed += ProfileWatcherChanged;
                _profileWatcher.EnableRaisingEvents = true;

                // used by the dev to display the 'Secret button', a button that dumps some debug info of the Task list.
                if (Environment.UserName == "highvoltz")
                {
                    toolStripSecretButton.Visible = true;
                }
            }
            catch (Exception ex)
            {
                Professionbuddy.Err(ex.ToString());
            }
        }