Ejemplo n.º 1
0
        public void ProcessRequest(HttpContext context)
        {
            //write your handler implementation here.
            string Obj = context.Request["object"];
            if (!string.IsNullOrEmpty(Obj)) {
                switch (Obj.ToLower()) {
                    case "dashboard":
                        string nodeType = context.Request["nodeType"];
                        switch (nodeType) {
                            case "RootNode":
                                Newtonsoft.Json.Linq.JObject ResultSet = new Newtonsoft.Json.Linq.JObject();
                                System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                                xDoc.Load(context.Server.MapPath("~/Admin/Config/ApplicationSettings.xml"));
                                Newtonsoft.Json.Converters.XmlNodeConverter converter = new Newtonsoft.Json.Converters.XmlNodeConverter();
                                string OutputJSON = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xDoc).Replace("@", string.Empty);
                                context.Response.Write(OutputJSON);
                                break;
                            default:
                                string[] TypeParts = nodeType.Split(',');

                                break;
                        }
                        break;
                }
            }
        }
        /// <summary>
        /// Adjusts for dynamic loading when no entry assembly is available/configurable.
        /// </summary>
        /// <remarks>
        /// When dynamic loading is used, the configuration path from the
        /// applications entry assembly to the connection setting might be broken.
        /// This method makes up the necessary configuration entries.
        /// </remarks>
        public static void AdjustForDynamicLoad()
        {
            if (theObjectScopeProvider1 == null)
                theObjectScopeProvider1 = new ObjectScopeProvider1();

            if (theObjectScopeProvider1.myDatabase == null)
            {
                string assumedInitialConfiguration =
                           "<openaccess>" +
                               "<references>" +
                                   "<reference assemblyname='PLACEHOLDER' configrequired='True'/>" +
                               "</references>" +
                           "</openaccess>";
                System.Reflection.Assembly dll = theObjectScopeProvider1.GetType().Assembly;
                assumedInitialConfiguration = assumedInitialConfiguration.Replace(
                                                    "PLACEHOLDER", dll.GetName().Name);
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.LoadXml(assumedInitialConfiguration);
                Database db = Telerik.OpenAccess.Database.Get("DatabaseConnection1",
                                            xmlDoc.DocumentElement,
                                            new System.Reflection.Assembly[] { dll });

                theObjectScopeProvider1.myDatabase = db;
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Contructor for BasicEGV class object
 /// </summary>
 /// <param name="receiverData">XML formatted data from G4</param>
 public BasicEGV(System.Xml.XmlDocument receiverData)
 {
     pReceiverData = receiverData;
     Dexcom.ReceiverApi.ReceiverDatabaseRecordsParser parser = new Dexcom.ReceiverApi.ReceiverDatabaseRecordsParser();
     parser.Parse(pReceiverData);
     pAllEGV = parser.EgvRecords;
 }
Ejemplo n.º 4
0
        public void EnsureLoaded(Assembly a)
        {
            if (assembliesProcessed.Contains(a.FullName)) return;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            try {
                object[] attrs = a.GetCustomAttributes(typeof(Util.NativeDependenciesAttribute), true);
                if (attrs.Length == 0) return;
                var attr = attrs[0] as Util.NativeDependenciesAttribute;
                string shortName = a.GetName().Name;
                string resourceName = shortName + "." + attr.Value;

                var info = a.GetManifestResourceInfo(resourceName);
                if (info == null) { this.AcceptIssue(new Issues.Issue("Plugin error - failed to find embedded resource " + resourceName, Issues.IssueSeverity.Error)); return; }

                using (Stream s = a.GetManifestResourceStream(resourceName)){
                    var x = new System.Xml.XmlDocument();
                    x.Load(s);

                    var n = new Node(x.DocumentElement, this);
                    EnsureLoaded(n, shortName,sw);
                }

            } finally {
                assembliesProcessed.Add(a.FullName);
            }
        }
Ejemplo n.º 5
0
        public static ImageInfo toImgur(Bitmap bmp)
        {
            ImageConverter convert = new ImageConverter();
            byte[] toSend = (byte[])convert.ConvertTo(bmp, typeof(byte[]));
            using (WebClient wc = new WebClient())
            {
                NameValueCollection nvc = new NameValueCollection
                {
                    { "image", Convert.ToBase64String(toSend) }
                };
                wc.Headers.Add("Authorization", Imgur.getAuth());
                ImageInfo info = new ImageInfo();
                try  
                {
                    byte[] response = wc.UploadValues("https://api.imgur.com/3/upload.xml", nvc);
                    string res = System.Text.Encoding.Default.GetString(response);

                    var xmlDoc = new System.Xml.XmlDocument();
                    xmlDoc.LoadXml(res);
                    info.link = new Uri(xmlDoc.SelectSingleNode("data/link").InnerText);
                    info.deletehash = xmlDoc.SelectSingleNode("data/deletehash").InnerText;
                    info.id = xmlDoc.SelectSingleNode("data/id").InnerText;
                    info.success = true;
                }
                catch (Exception e)
                {
                    info.success = false;
                    info.ex = e;
                }
                return info;
            }
        }
Ejemplo n.º 6
0
        private bool CheckVersion(string lookingFor)
        {
            try
            {
                using (var wc = new System.Net.WebClient())
                {
                    var xDoc = new System.Xml.XmlDocument();                    
                    xDoc.Load(@"http://www.sqlcompact.dk/SqlCeToolboxVersions.xml");

                    string newVersion = xDoc.DocumentElement.Attributes[lookingFor].Value;

                    Version vN = new Version(newVersion);
                    if (vN > Assembly.GetExecutingAssembly().GetName().Version)
                    {
                        return true;
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return false;
        }
Ejemplo n.º 7
0
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            //Save the values to an XML file
            //Could save to data source, Message Queue, etc.
            System.Xml.XmlDocument aDOM = new System.Xml.XmlDocument();
            System.Xml.XmlAttribute aAttribute;

            aDOM.LoadXml("<AutomobileData/>");

            //Add the First Name attribute to XML
            aAttribute = aDOM.CreateAttribute("Manufacturer");
            aAttribute.Value = txtManufact.Text;
            aDOM.DocumentElement.Attributes.Append(aAttribute);
            //Add the Last Name attribute to XML
            aAttribute = aDOM.CreateAttribute("Model");
            aAttribute.Value = txtModel.Text;
            aDOM.DocumentElement.Attributes.Append(aAttribute);
            //Add the DOB attribute to XML
            aAttribute = aDOM.CreateAttribute("Year");
            aAttribute.Value = txtYear.Text;
            aDOM.DocumentElement.Attributes.Append(aAttribute);
            //Add the SSN attribute to XML
            aAttribute = aDOM.CreateAttribute("Color");
            aAttribute.Value = txtColor.Text;
            aDOM.DocumentElement.Attributes.Append(aAttribute);

            //Save file to the file system
            aDOM.Save("AutomobileData.xml");
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Retrieves list of goofs from specified xml file
 /// </summary>
 /// <param name="xmlPath">path of xml file to read from</param>
 public IList<IIMDbGoof> ReadGoofs(
     string xmlPath)
 {
     try
     {
         List<IIMDbGoof> goofs = new List<IIMDbGoof>();
         System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
         doc.Load(xmlPath);
         System.Xml.XmlNodeList goofList = doc.SelectNodes("/Goofs/Goof");
         if (goofList != null)
             foreach (System.Xml.XmlNode goofNode in goofList)
             {
                 if (goofNode["Category"] != null
                     && goofNode["Category"].InnerText != null
                     && goofNode["Category"].InnerText.Trim() != ""
                     && goofNode["Description"] != null
                     && goofNode["Description"].InnerText != null
                     && goofNode["Description"].InnerText.Trim() != "")
                 {
                     IMDbGoof goof = new IMDbGoof();
                     goof.Category = goofNode["Category"].InnerText;
                     goof.Description = goofNode["Description"].InnerText;
                     goofs.Add(goof);
                 }
             }
         return goofs;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 9
0
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            //Save the values to an XML file
            //Could save to data source, Message Queue, etc.
            System.Xml.XmlDocument aDOM = new System.Xml.XmlDocument();
            System.Xml.XmlAttribute aAttribute;

            aDOM.LoadXml("<PersonnelData/>");

            //Add the First Name attribute to XML
            aAttribute = aDOM.CreateAttribute("FirstName");
            aAttribute.Value = txtFName.Text;
            aDOM.DocumentElement.Attributes.Append(aAttribute);
            //Add the Last Name attribute to XML
            aAttribute = aDOM.CreateAttribute("LastName");
            aAttribute.Value = txtLName.Text;
            aDOM.DocumentElement.Attributes.Append(aAttribute);
            //Add the DOB attribute to XML
            aAttribute = aDOM.CreateAttribute("DOB");
            aAttribute.Value = txtDOB.Text;
            aDOM.DocumentElement.Attributes.Append(aAttribute);
            //Add the SSN attribute to XML
            aAttribute = aDOM.CreateAttribute("SSN");
            aAttribute.Value = txtSSN.Text;
            aDOM.DocumentElement.Attributes.Append(aAttribute);

            //Save file to the file system
            aDOM.Save("PersonnelData.xml");
        }
Ejemplo n.º 10
0
        public System.Xml.XmlDocument getClaims()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            System.Xml.XmlElement claims = doc.CreateElement("claims");

            foreach(TurfWarsGame.Claim c in TurfWars.Global.game.getClaims())
            {
                System.Xml.XmlElement claim = doc.CreateElement("claim");

                System.Xml.XmlElement owners = doc.CreateElement("owners");
                foreach (string u in c.getOwners().Keys)
                {
                    System.Xml.XmlElement owner = doc.CreateElement("owner");
                    owner.SetAttribute("name", u);
                    owner.SetAttribute("share", c.getOwners()[u].ToString());
                    owners.AppendChild(owner);
                }

                System.Xml.XmlElement tile = doc.CreateElement("tile");
                tile.SetAttribute("north",c.box.north.ToString());
                tile.SetAttribute("south",c.box.south.ToString());
                tile.SetAttribute("west", c.box.west.ToString());
                tile.SetAttribute("east", c.box.east.ToString());
                claim.AppendChild(owners);
                claim.AppendChild(tile);
                claims.AppendChild(claim);
            }

            doc.AppendChild(claims);
            return doc;
        }
 internal LogFileDataStore()
 {
     _currentLogTimeInterval = LogTimeInterval.day;
     LOG_BASE_PATH = Properties.Settings.Default.Log_file_base_path;
     CreateNewLogFile();
     _xmlDocument = new System.Xml.XmlDocument();
 }
Ejemplo n.º 12
0
Archivo: Xml.cs Proyecto: sopindm/bjeb
            public static Xml read(Connection connection)
            {
                System.Xml.XmlDocument document = new System.Xml.XmlDocument();
                document.LoadXml(connection.stream.readString());

                return new Xml(document);
            }
Ejemplo n.º 13
0
 static void Main() {
     System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
     doc.Load("../../XmlFile1.xml");
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new DekiPublishTestForm());
 }
        public void TestForAdminPackageOfWebDashboardIsEmpty()
        {
#if BUILD
            string configFile = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"..\..\Project\Webdashboard\dashboard.config");
#else
            string configFile = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"..\..\..\Webdashboard\dashboard.config");
#endif           

            Assert.IsTrue(System.IO.File.Exists(configFile), "Dashboard.config not found at {0}", configFile);

            System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
            xdoc.Load(configFile);

            var adminPluginNode = xdoc.SelectSingleNode("/dashboard/plugins/farmPlugins/administrationPlugin");

            Assert.IsNotNull(adminPluginNode, "Admin package configuration not found in dashboard.config at {0}", configFile);

            var pwd = adminPluginNode.Attributes["password"];

            Assert.IsNotNull(pwd, "password attribute not defined in admin packackage in dashboard.config at {0}", configFile);

            Assert.AreEqual("", pwd.Value, "Password must be empty string, to force users to enter one. No default passwords allowed in distribution");


        }
Ejemplo n.º 15
0
        public List<Queue> ListQueues(
            string prefix = null,
            bool IncludeMetadata = false,
            int timeoutSeconds = 0,
            Guid? xmsclientrequestId = null)
        {
            List<Queue> lQueues = new List<Queue>();
            string strNextMarker = null;
            do
            {
                string sRet = Internal.InternalMethods.ListQueues(UseHTTPS, SharedKey, AccountName, prefix, strNextMarker,
                    IncludeMetadata: IncludeMetadata, timeoutSeconds: timeoutSeconds, xmsclientrequestId: xmsclientrequestId);

                //Microsoft.SqlServer.Server.SqlContext.Pipe.Send("After Internal.InternalMethods.ListQueues = " + sRet);

                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                using (System.IO.StringReader sr = new System.IO.StringReader(sRet))
                {
                    doc.Load(sr);
                }

                foreach (System.Xml.XmlNode node in doc.SelectNodes("EnumerationResults/Queues/Queue"))
                {
                    lQueues.Add(Queue.ParseFromXmlNode(this, node));
                };

                strNextMarker = doc.SelectSingleNode("EnumerationResults/NextMarker").InnerText;

                //Microsoft.SqlServer.Server.SqlContext.Pipe.Send("strNextMarker == " + strNextMarker);

            } while (!string.IsNullOrEmpty(strNextMarker));

            return lQueues;
        }
        protected string HostIpToLocation()
        {
            string sourceIP = string.IsNullOrEmpty(Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
            ? Request.ServerVariables["REMOTE_ADDR"]
            : Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            string url = "http://api.ipinfodb.com/v2/ip_query.php?key={0}&ip={1}&timezone=true";

            url = String.Format(url, "90d4f5e07ed75a6ed8ad13221d88140001aebf6730eec98978151d2a455d5e95", sourceIP);

            HttpWebRequest httpWRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse httpWResponse = (HttpWebResponse)httpWRequest.GetResponse();

            System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();

            xdoc.Load(httpWResponse.GetResponseStream());

            string city = "", state = "";

            foreach (System.Xml.XmlNode x in xdoc.SelectSingleNode("Response").ChildNodes)
            {
                //Response.Write(x.Name + "<br>");
                if (x.Name == "City") { city = x.InnerText + ", "; }
                if (x.Name == "RegionName") { state = x.InnerText; }
            }

            return city + state;
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            string applicationDirectory = System.Reflection.Assembly.GetExecutingAssembly().Location;
            applicationDirectory = applicationDirectory.Substring(0, applicationDirectory.LastIndexOf(@"\")+1);
            using (StreamReader reader = File.OpenText( FilePath ) )
            {
                string line = null;
                do
                {
                    line = reader.ReadLine();
                    if (line != null)
                    {
                        string[] items = line.Split(',');
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                        string url = items[XmlColumn];
                        try
                        {
                            doc.Load(url);
                            string filename = items[XmlColumn].Substring(items[XmlColumn].LastIndexOf("/") + 1);
                            string filepath = Path.Combine(applicationDirectory, SaveFolder, filename);
                            doc.Save(filepath);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Exception: " + url + "\r\n" + e.Message);
                        }

                    }
                }
                while( line != null );
            }
            Console.Write("Press Enter key to close. ");
            while( Console.ReadKey().Key != ConsoleKey.Enter );
        }
Ejemplo n.º 18
0
        public static void ImportProvince( string source, string target, ExportMode mode )
        {
            Console.WriteLine( "Opening source file \"{0}\"...", Path.GetFileName( source ) );
            ProvinceList provinces = new ProvinceList();
            FileStream stream = null;
            try {
                stream = new FileStream( source, FileMode.Open, FileAccess.Read, FileShare.Read );
                if ( mode == ExportMode.XML ) {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load( stream );
                    provinces.ReadFrom( doc );
                }
                else {
                    provinces.ReadFrom( new EU2.IO.CSVReader( stream ) );
                }
            }
            finally {
                if ( stream != null ) stream.Close();
            }

            Console.WriteLine( "Opening target file \"{0}\"...", Path.GetFileName( target ) );
            EU2.Edit.File file = new EU2.Edit.File();
            try {
                file.ReadFrom( target );
            }
            catch ( EU2.Edit.InvalidFileFormatException ) {
                Console.WriteLine( "The specified target file is not an EU2Map file, or is corrupt." );
                return;
            }

            file.Provinces = provinces;

            file.WriteTo( target );
            Console.WriteLine( "Import successful." );
        }
Ejemplo n.º 19
0
        public System.Collections.Generic.IEnumerable<Table> ListTables(string xmsclientrequestId = null)
        {
            List<Table> lTables = new List<Table>();

            string strResult = Internal.InternalMethods.QueryTables(AccountName, SharedKey, UseHTTPS, xmsclientrequestId);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            using (System.Xml.XmlReader re = System.Xml.XmlReader.Create(new System.IO.StringReader(strResult)))
            {
                doc.Load(re);
            }
            System.Xml.XmlNamespaceManager man = new System.Xml.XmlNamespaceManager(doc.NameTable);
            man.AddNamespace("f", "http://www.w3.org/2005/Atom");
            man.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
            man.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");

            foreach (System.Xml.XmlNode n in doc.SelectNodes("//f:feed/f:entry", man))
            {
                yield return new Table()
                {
                    AzureTableService = this,
                    Url = new Uri(n.SelectSingleNode("f:id", man).InnerText),
                    Name = n.SelectSingleNode("f:content/m:properties/d:TableName", man).InnerText
                };

            }
        }
        public static object deserialize(string json, Type type)
        {
        try
        {
                if (json.StartsWith("{") || json.StartsWith("["))
            return JsonConvert.DeserializeObject(json, type);
                else
                {
                    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                    xmlDoc.LoadXml(json);
                    return JsonConvert.SerializeXmlNode(xmlDoc);
        }

            }
            catch (IOException e)
            {
          throw new ApiException(500, e.Message);
        }
            catch (JsonSerializationException jse)
            {
                throw new ApiException(500, jse.Message);
      }
            catch (System.Xml.XmlException xmle)
            {
                throw new ApiException(500, xmle.Message);
            }
      }
Ejemplo n.º 21
0
 public void LoadData(bool show_error)
 {
     buttonAggiorna.Enabled = numStagione.Enabled = false;
     try
     {
         Internal.Main.StatusString = "Download dell'elenco delle partite in corso...";
         string stagione = numStagione.Value.ToString();
         string url = string.Format(@"http://www.rugbymania.net/export_xml_part.php?lang=italiano&season={2}&id={0}&access_key={1}&object=calendar",
             Properties.Settings.Default.RM_Id, Properties.Settings.Default.RM_Codice, stagione);
         System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
         try
         {
             doc.Load(url);
         }
         catch (Exception ex)
         {
             if (show_error) My.Box.Errore("Impossibile scaricare i dati delle partite\r\n"+ex.Message);
             if (System.IO.File.Exists(DEFAULT_DATA)) doc.Load(DEFAULT_DATA);
         }
         Internal.Main.StatusString = "Download dell'elenco delle partite terminato!";
         ShowPartite(doc);
         if (doc.HasChildNodes) doc.Save(DEFAULT_DATA);
     }
     catch (Exception ex)
     {
         #if(DEBUG)
         My.Box.Info("TabClassifica::LoadData\r\n" + ex.Message);
         #endif
         Internal.Main.Error_on_xml();
     }
     buttonAggiorna.Enabled = numStagione.Enabled = true;
 }
        /// <summary>
        ///   Retrieves the names of all the entries inside a section. </summary>
        /// <param name="section">
        ///   The name of the section holding the entries. </param>
        /// <returns>
        ///   If the section exists, the return value is an array with the names of its entries; 
        ///   otherwise it's null. </returns>
        /// <exception cref="InvalidOperationException">
        ///	  <see cref="Profile.Name" /> is null or empty. </exception>
        /// <exception cref="ArgumentNullException">
        ///   section is null. </exception>
        /// <exception cref="XmlException">
        ///	  Parse error in the XML being loaded from the file. </exception>
        /// <seealso cref="Profile.HasEntry" />
        /// <seealso cref="GetSectionNames" />
        public string[] GetEntryNames(string section)
        {
            // Verify the section exists
              if (!UserSectionExists(section))
            return null;

              VerifyAndAdjustSection(ref section);

              System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
              doc.Load(_filePath);

              if (doc == null)
            return null;

              // Get the root node, if it exists
              System.Xml.XmlElement root = doc.DocumentElement;
              if (root == null)
            return null;

              // Get the entry nodes
              System.Xml.XmlNodeList entryNodes = root.SelectNodes(GetSectionsPath(section) + "/entry[@name]");
              if (entryNodes == null)
            return null;

              // Add all entry names to the string array
              string[] entries = new string[entryNodes.Count];
              int i = 0;

              foreach (System.Xml.XmlNode node in entryNodes)
            entries[i++] = node.Attributes["name"].Value;

              //  Return the Array of Entry Names to the calling method.
              return entries;
        }
Ejemplo n.º 23
0
        private void btnPublishFolder_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtFolderPath.Text))
            {
                //To Publish Folder, add Data to XML
                System.Xml.XmlDocument objXmlDocument = new System.Xml.XmlDocument();
                // Load XML
                objXmlDocument.Load(@".\Data\PublishedFolders.xml");
                System.Xml.XmlNode objXmlNode = objXmlDocument.CreateNode(System.Xml.XmlNodeType.Element,"Folder", "Folder");

                // Attribute Name
                System.Xml.XmlAttribute objXmlAttribute = objXmlDocument.CreateAttribute("Name");
                objXmlAttribute.Value = "Carpeta";
                objXmlNode.Attributes.Append(objXmlAttribute);
                // Attribute Status
                objXmlAttribute = objXmlDocument.CreateAttribute("Status");
                objXmlAttribute.Value = "Enabled";
                objXmlNode.Attributes.Append(objXmlAttribute);
                // Attribute Path
                objXmlAttribute = objXmlDocument.CreateAttribute("Path");
                objXmlAttribute.Value = txtFolderPath.Text;
                objXmlNode.Attributes.Append(objXmlAttribute);

                // Add Node
                objXmlDocument.SelectSingleNode("/PublishedFolders").AppendChild(objXmlNode);
                // Update File
                objXmlDocument.Save(@".\Data\PublishedFolders.xml");

                // Refresh List
                LoadFolders();
            }
        }
Ejemplo n.º 24
0
        public void Init(HttpApplication context)
        {
            System.Xml.XmlDocument _document = new System.Xml.XmlDocument();
            _document.Load(Xy.Tools.IO.File.foundConfigurationFile("App", Xy.AppSetting.FILE_EXT));
            foreach (System.Xml.XmlNode _item in _document.GetElementsByTagName("Global")) {
                string _className = _item.InnerText;
                Type _tempCtonrlType = Type.GetType(_className, false, true);
                IGlobal _tempGlobal;
                if (_tempCtonrlType == null) {
                    System.Reflection.Assembly asm = System.Reflection.Assembly.Load(_className.Split(',')[0]);
                    _tempCtonrlType = asm.GetType(_className.Split(',')[1], false, true);
                }
                _tempGlobal = System.Activator.CreateInstance(_tempCtonrlType) as IGlobal;
                if (_tempGlobal != null) {
                    global = _tempGlobal;
                }
            }
            if (global == null) { global = new EmptyGlobal(); }
            global.ApplicationInit(context);

            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.Error += new EventHandler(context_Error);
            context.EndRequest += new EventHandler(context_EndRequest);
            _urlManager = URLManage.URLManager.GetInstance();
        }
        public void Load()
        {
            var redirectRuleConfigFile = System.Configuration.ConfigurationManager.AppSettings["RedirectRuleConfigFile"];
            if (System.IO.File.Exists(redirectRuleConfigFile))
            {
                var xmd = new System.Xml.XmlDocument();
                xmd.Load(redirectRuleConfigFile);

                var nodes = xmd.GetElementsByTagName("RedirectRule");
                foreach (System.Xml.XmlElement xme in nodes)
                {
                    var callingClient = IPAddress.Any; //Not yet supported "CallingClient"
                    var requestHost = xme.Attributes["RequestHost"].Value;
                    var requestPort = int.Parse(xme.Attributes["RequestPort"].Value);
                    var targetAddress = xme.Attributes["TargetAddress"].Value;
                    var targetPort = int.Parse(xme.Attributes["TargetPort"].Value);

                    Instance.Add(new RedirectRule(callingClient, requestHost, requestPort, IPAddress.Parse(targetAddress), targetPort), false);
                }
            }

            //Append sample redirect rules
            //Instance.Add(new RedirectRule(IPAddress.Any, null, 3001, IPAddress.Parse("127.0.0.1"), 3002), false);
            //Instance.Add(new RedirectRule(IPAddress.Any, "ws1.test.com", 3003, IPAddress.Parse("127.0.0.1"), 3002), false);
            //Save();
        }
Ejemplo n.º 26
0
		/// <summary>
		/// 新建
		/// </summary>
		/// <returns></returns>
		public static System.Xml.XmlDocument NewXmlDocument()
		{
			System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
			xd.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Root/>");
			return xd;
		}
        static void Main()
        {
            var xmlSearch = new System.Xml.XmlDocument();

            //select one of the above Query, Query1
            xmlSearch.Load(Query1);
            
            var query = xmlSearch.SelectSingleNode("/query");
            
            var author = query[Author].GetText();
            var title = query[Title].GetText();
            var isbn = query[ISBN].GetText();
         
            var dbContext = new BookstoreDbContext();

            var queryLogEntry = new SearchLogEntry
            {
                Date = DateTime.Now,
                QueryXml = query.OuterXml
            };

            var foundBooks = GenerateQuery(author, title, isbn, dbContext);

            dbContext.SearchLog.Add(queryLogEntry);
            dbContext.SaveChanges();

            PrintResult(foundBooks);
        }
Ejemplo n.º 28
0
        public void DeserializeBannerTestSuccessfull()
        {
            string content =
                "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Banners><Banner><id>605881</id><BannerPath>fanart/original/83462-18.jpg</BannerPath><BannerType>fanart</BannerType><BannerType2>1920x1080</BannerType2><Colors>|217,177,118|59,40,68|214,192,205|</Colors><Language>de</Language><Rating>9.6765</Rating><RatingCount>34</RatingCount><SeriesName>false</SeriesName><ThumbnailPath>_cache/fanart/original/83462-18.jpg</ThumbnailPath><VignettePath>fanart/vignette/83462-18.jpg</VignettePath></Banner></Banners>";

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(content);

            System.Xml.XmlNode bannersNode = doc.ChildNodes[1];
            System.Xml.XmlNode bannerNode = bannersNode.ChildNodes[0];

            Banner target = new Banner();
            target.Deserialize(bannerNode);

            Assert.Equal(605881, target.Id);
            Assert.Equal("fanart/original/83462-18.jpg", target.BannerPath);
            Assert.Equal(BannerTyp.fanart, target.Type);
            Assert.Equal("1920x1080", target.Dimension);
            Assert.Equal("|217,177,118|59,40,68|214,192,205|", target.Color);
            Assert.Equal("de", target.Language);
            Assert.Equal(9.6765, target.Rating);
            Assert.Equal(34, target.RatingCount);
            Assert.Equal(false, target.SeriesName);
            Assert.Equal("_cache/fanart/original/83462-18.jpg", target.ThumbnailPath);
            Assert.Equal("fanart/vignette/83462-18.jpg", target.VignettePath);
        }
        public override bool ShowConfiguration(XElement config)
        {
            var dialog = new LiveSplitConfigurationDialog(config);
            if (dialog.ShowDialog().GetValueOrDefault(false))
            {
                if (config.Parent.GetInt("cx") == 0 || config.Parent.GetInt("cy") == 0)
                {
                    try
                    {
                        using (var layoutStream = System.IO.File.OpenRead(config.GetString("layoutpath")))
                        {
                            var xmlDoc = new System.Xml.XmlDocument();
                            xmlDoc.Load(layoutStream);

                            var parent = xmlDoc["Layout"];
                            var width = parent["VerticalWidth"];
                            config.Parent.SetInt("cx", int.Parse(width.InnerText));
                            var height = parent["VerticalHeight"];
                            config.Parent.SetInt("cy", int.Parse(height.InnerText)); //TODO Will break with horizontal
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                    }
                }

                return true;
            }
            return false;
        }
Ejemplo n.º 30
0
		void menuitem_Click(object sender, EventArgs e)
		{

			System.Windows.Forms.OpenFileDialog of = new System.Windows.Forms.OpenFileDialog();
			of.DefaultExt = ".xml";
			of.Filter = "XMLファイル(*.xml)|*.xml";
			if (of.ShowDialog((System.Windows.Forms.IWin32Window)_host.Win32WindowOwner) == System.Windows.Forms.DialogResult.OK) {
				try {
					System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
					xdoc.Load(of.FileName);

					// 擬似的に放送に接続した状態にする
					_host.StartMockLive("lv0", System.IO.Path.GetFileNameWithoutExtension(of.FileName), DateTime.Now);
					
					// ファイル内のコメントをホストに登録する
					foreach (System.Xml.XmlNode node in xdoc.SelectNodes("packet/chat")) {
						Hal.OpenCommentViewer.Control.OcvChat chat = new Hal.OpenCommentViewer.Control.OcvChat(node);
						_host.InsertPluginChat(chat);
					}
					_host.ShowStatusMessage("インポートに成功しました。");

				}catch(Exception ex){
					NicoApiSharp.Logger.Default.LogException(ex);
					_host.ShowStatusMessage("インポートに失敗しました。");

				}
			}
			
		}
Ejemplo n.º 31
0
 /// <summary>
 /// 获取当前筛选器的状态,将序列化的内容填充至 XmlNode 的 InnerText 属性或者 ChildNodes 子节点中。
 /// </summary>
 /// <param name="xmlDoc">创建 XmlNode 时所需使用到的 System.Xml.XmlDocument。</param>
 public System.Xml.XmlNode GetFilterConfig(System.Xml.XmlDocument xmlDoc)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 32
0
        public static byte[] SvgToPdf(string svg, bool current_view)
        {
            if (string.IsNullOrEmpty(svg))
            {
                throw new System.ArgumentNullException("svg");
            }



            string styleTemplate = @"
path:not([fill]){fill: none}
path:not([stroke]){stroke: #000}
path:not([stroke-width]){stroke-width: 1}
";



            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            doc.XmlResolver = null; // https://stackoverflow.com/questions/4445348/net-prevent-xmldocument-loadxml-from-retrieving-dtd
            doc.LoadXml(svg);



            System.Xml.XmlNamespaceManager nsmgr = XmlHelper.GetNamespaceManager(doc);
            string realDefaultNamespace          = nsmgr.LookupNamespace("dft");

            // System.Xml.XmlElement style = doc.CreateElement("", "style", realDefaultNamespace);
            System.Xml.XmlElement style = doc.CreateElement("style");
            style.SetAttribute("type", "text/css");
            style.SetAttribute("media", "all");
            style.InnerXml = styleTemplate;
            doc.DocumentElement.PrependChild(style);

            // string svgContent = doc.OuterXml.Replace("xmlns=\"\"", "");
            // doc.LoadXml(svgContent);
            // System.Console.WriteLine(doc.InnerXml);



            // data-height="967px" data-width="1324px"
            System.Xml.XmlAttribute dataWidth  = doc.DocumentElement.Attributes["data-width"];
            System.Xml.XmlAttribute dataHeight = doc.DocumentElement.Attributes["data-height"];



            string swidth  = "967px";
            string sheight = "967px";

            swidth  = dataWidth.Value;
            sheight = dataHeight.Value;



            if (string.IsNullOrEmpty(swidth))
            {
                throw new System.ArgumentNullException("swidth");
            }

            if (string.IsNullOrEmpty(sheight))
            {
                throw new System.ArgumentNullException("sheight");
            }

            swidth  = swidth.Trim();
            sheight = sheight.Trim();


            string templatePre  = @"<!doctype html>
<html>
<head>
<title></title>
<style>
html, body, div, svg { margin: 0px; padding: 0px; }

#SVG svg 
{
    -ms-transform: translate(-50%, -50%) translateZ(0);
    -ms-transform-origin: 50% 50% 0px;
    -webkit-transform: translate(-50%, -50%) translateZ(0);
    -webkit-transform-origin: 50% 50% 0px;
    background: #fff;
    fill: #ffffff;
    left: 50%;
    position: absolute;
    user-select: none;
    top: 50%;
    transform: translate(-50%, -50%);
    transform-origin: 50% 50% 0px;
}

</style>
</head>
<body>
<div id=""SVG"" style=""display: block; width: " + swidth + "; height: " + sheight + @"; position: relative; background-color: hotpink; overflow: hidden;"">
";
            string templatePost = @"
</div>
</body>
</html>
";

            svg = doc.DocumentElement.OuterXml;


            string html = templatePre + svg + templatePost;



            if (swidth.EndsWith("px", System.StringComparison.InvariantCultureIgnoreCase))
            {
                swidth = swidth.Substring(0, swidth.Length - 2);
            }

            if (sheight.EndsWith("px", System.StringComparison.InvariantCultureIgnoreCase))
            {
                sheight = sheight.Substring(0, sheight.Length - 2);
            }

            int width  = 1324;
            int height = 967;

            if (!int.TryParse(swidth, out width))
            {
                throw new System.ArgumentException("swidth");
            }

            if (!int.TryParse(sheight, out height))
            {
                throw new System.ArgumentException("sheight");
            }

            if (current_view)
            {
                return(Html2Pdf(html, width + 37, height + 37));
            }


            System.Xml.XmlAttribute attWidth   = doc.DocumentElement.Attributes["width"];
            System.Xml.XmlAttribute attHeight  = doc.DocumentElement.Attributes["height"];
            System.Xml.XmlAttribute attViewBox = doc.DocumentElement.Attributes["viewBox"];



            swidth  = attWidth.Value;
            sheight = attHeight.Value;
            string viewBox = attViewBox.Value;

            //System.Console.WriteLine(width);
            //System.Console.WriteLine(height);
            //System.Console.WriteLine(viewBox);
            string[] viewBoxValues = viewBox.Split(' ');

            string viewbox_width  = viewBoxValues[2];
            string viewbox_height = viewBoxValues[3];

            //System.Console.WriteLine(viewBoxValues);


            if (viewbox_width.EndsWith("px", System.StringComparison.InvariantCultureIgnoreCase))
            {
                viewbox_width = viewbox_width.Substring(0, viewbox_width.Length - 2);
            }

            if (viewbox_height.EndsWith("px", System.StringComparison.InvariantCultureIgnoreCase))
            {
                viewbox_height = viewbox_height.Substring(0, viewbox_height.Length - 2);
            }

            double viewbox_dblwidth  = 1324.0;
            double viewbox_dblHeight = 967.0;

            if (!double.TryParse(viewbox_width, out viewbox_dblwidth))
            {
                throw new System.ArgumentException("viewbox_width");
            }

            if (!double.TryParse(viewbox_height, out viewbox_dblHeight))
            {
                throw new System.ArgumentException("viewbox_height");
            }


            double r1 = 21.0 / viewbox_dblwidth;
            double r2 = 29.7 / viewbox_dblHeight;
            double r  = System.Math.Min(r1, r2);

            var w = viewbox_dblwidth * r;
            var h = viewbox_dblHeight * r;

            attWidth.Value  = w.ToString("N8", System.Globalization.CultureInfo.InvariantCulture) + "cm";
            attHeight.Value = h.ToString("N8", System.Globalization.CultureInfo.InvariantCulture) + "cm";

            w *= 0.393701 * 100;
            h *= 0.393701 * 100;

            System.IO.File.WriteAllText(@"d:\stefanlol.xml", doc.OuterXml, System.Text.Encoding.UTF8);


            svg = doc.DocumentElement.OuterXml;


            templatePre = @"<!doctype html>
<html>
<head>
<title></title>
<style>
html, body, div, svg { margin: 0px; padding: 0px; }
</style>
</head>
<body>
<div>
";

            html = templatePre + svg + templatePost;

            return(Html2Pdf(html, (int)System.Math.Ceiling(w), (int)System.Math.Ceiling(h)));
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Si imposta il TPU a partire da un oggetto XmlDocument
 /// </summary>
 public void setTPU(System.Xml.XmlDocument doc)
 {
     tpuXML = doc;
     this.reportDoc.setXML(doc, doc.DocumentElement.Name);
 }
Ejemplo n.º 34
0
 public Dictionary <Guid, object> Load(System.Xml.XmlDocument dom)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 35
0
        public Lfx.Types.OperationResult Backup(BackupInfo backupInfo)
        {
            string WorkFolder = backupInfo.Name + System.IO.Path.DirectorySeparatorChar;

            Lfx.Environment.Folders.EnsurePathExists(this.BackupPath);

            if (!System.IO.Directory.Exists(Lfx.Environment.Folders.TemporaryFolder + WorkFolder))
            {
                System.IO.Directory.CreateDirectory(Lfx.Environment.Folders.TemporaryFolder + WorkFolder);
            }

            Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Creando copia de seguridad", "Se está creando un volcado completo del almacén de datos en una carpeta, para resguardar.");
            Progreso.Modal     = true;
            Progreso.Advertise = true;
            Progreso.Begin();
            Progreso.Max = Lfx.Workspace.Master.Structure.Tables.Count + 1;

            Progreso.ChangeStatus("Exportando estructura");
            Progreso.ChangeStatus(Progreso.Value + 1);
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.AppendChild(Lfx.Workspace.Master.Structure.ToXml(doc));
            doc.Save(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "dbstruct.xml");

            BackupWriter Writer = new BackupWriter(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "dbdata.lbd");

            Writer.Write(":BKP");

            IList <string> TableList = Lfx.Data.DatabaseCache.DefaultCache.GetTableNames();

            foreach (string Tabla in TableList)
            {
                string NombreTabla = Tabla;
                if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(Tabla))
                {
                    NombreTabla = Lfx.Workspace.Master.Structure.Tables[Tabla].Label;
                }

                Progreso.ChangeStatus("Volcando " + NombreTabla);
                Progreso.ChangeStatus(Progreso.Value + 1);
                ExportTableBin(Tabla, Writer);
            }
            Writer.Close();

            System.IO.FileStream Archivo = new System.IO.FileStream(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "info.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write);
            using (System.IO.StreamWriter Escribidor = new System.IO.StreamWriter(Archivo, System.Text.Encoding.Default)) {
                Escribidor.WriteLine("Copia de seguridad de Lázaro");
                Escribidor.WriteLine("");
                Escribidor.WriteLine("Empresa=" + backupInfo.CompanyName);
                Escribidor.WriteLine("EspacioTrabajo=" + Lfx.Workspace.Master.Name);
                Escribidor.WriteLine("FechaYHora=" + System.DateTime.Now.ToString("dd-MM-yyyy") + " a las " + System.DateTime.Now.ToString("HH:mm:ss"));
                Escribidor.WriteLine("Usuario=" + backupInfo.UserName);
                Escribidor.WriteLine("Estación=" + Lfx.Environment.SystemInformation.MachineName);
                Escribidor.WriteLine("VersiónLazaro=" + backupInfo.ProgramVersion);
                Escribidor.WriteLine("");
                Escribidor.WriteLine("Por favor no modifique ni elimine este archivo.");
                Escribidor.Close();
                Archivo.Close();
            }

            if (Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting <int>("Sistema.ComprimirCopiasDeSeguridad", 0) != 0)
            {
                Progreso.ChangeStatus("Comprimiendo los datos");
                Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "backup.7z");
                ArchivoComprimido.Add(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "*");
                if (System.IO.File.Exists(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + "backup.7z"))
                {
                    Progreso.ChangeStatus("Eliminando archivos temporales");
                    // Borrar los archivos que acabo de comprimir
                    System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(Lfx.Environment.Folders.TemporaryFolder + WorkFolder);
                    foreach (System.IO.FileInfo DirItem in Dir.GetFiles())
                    {
                        if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt")
                        {
                            System.IO.File.Delete(Lfx.Environment.Folders.TemporaryFolder + WorkFolder + DirItem.Name);
                        }
                    }
                }
            }

            Progreso.ChangeStatus("Almacenando");
            Progreso.ChangeStatus(Progreso.Value + 1);
            Lfx.Environment.Folders.MoveDirectory(Lfx.Environment.Folders.TemporaryFolder + WorkFolder, this.BackupPath + WorkFolder);

            int GuardarBackups = Lfx.Workspace.Master.CurrentConfig.ReadGlobalSetting <int>("Sisteam.Backup.CantMax", 14);

            if (GuardarBackups > 0)
            {
                List <BackupInfo> ListaDeBackups = this.GetBackups();
                if (ListaDeBackups.Count > GuardarBackups)
                {
                    Progreso.ChangeStatus("Eliminando copias de seguridad antiguas");
                    int BorrarBackups = ListaDeBackups.Count - GuardarBackups;
                    if (BorrarBackups < ListaDeBackups.Count)
                    {
                        for (int i = 1; i <= BorrarBackups; i++)
                        {
                            this.Delete(this.GetOldestBackupName());
                        }
                    }
                }
            }

            Progreso.End();

            return(new Lfx.Types.SuccessOperationResult());
        }
Ejemplo n.º 36
0
 internal void Server_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
 {
     if (string.IsNullOrEmpty(e.ClientId))
     {
         _logger.LogInformation($"Message: Topic=[{e.ApplicationMessage.Topic }]");
     }
     else
     {
         _logger.LogInformation($"Server received {e.ClientId}'s message: Topic=[{e.ApplicationMessage.Topic }],Retain=[{e.ApplicationMessage.Retain}],QualityOfServiceLevel=[{e.ApplicationMessage.QualityOfServiceLevel}]");
         if (!lstTopics.ContainsKey(e.ApplicationMessage.Topic))
         {
             lstTopics.Add(e.ApplicationMessage.Topic, 1);
             Task.Run(() => _serverEx.PublishAsync("$SYS/broker/subscriptions/count", lstTopics.Count.ToString()));
         }
         else
         {
             lstTopics[e.ApplicationMessage.Topic]++;
         }
         if (e.ApplicationMessage.Payload != null)
         {
             received += e.ApplicationMessage.Payload.Length;
         }
         string topic = e.ApplicationMessage.Topic;
         var    tpary = topic.Split('/', StringSplitOptions.RemoveEmptyEntries);
         if (tpary.Length >= 3 && tpary[0] == "devices" && Devices.ContainsKey(e.ClientId))
         {
             Device device = JudgeOrCreateNewDevice(tpary, Devices[e.ClientId]);
             if (device != null)
             {
                 Dictionary <string, object> keyValues = new Dictionary <string, object>();
                 if (tpary.Length >= 4)
                 {
                     string keyname = tpary.Length >= 5 ? tpary[4] : tpary[3];
                     if (tpary[3].ToLower() == "xml")
                     {
                         try
                         {
                             var xml = new System.Xml.XmlDocument();
                             xml.LoadXml(e.ApplicationMessage.ConvertPayloadToString());
                             keyValues.Add(keyname, xml);
                         }
                         catch (Exception ex)
                         {
                             _logger.LogWarning(ex, $"xml data error {topic},{ex.Message}");
                         }
                     }
                     else if (tpary[3].ToLower() == "binary")
                     {
                         keyValues.Add(keyname, e.ApplicationMessage.Payload);
                     }
                 }
                 else
                 {
                     try
                     {
                         keyValues = e.ApplicationMessage.ConvertPayloadToDictionary();
                     }
                     catch (Exception ex)
                     {
                         _logger.LogWarning(ex, $"ConvertPayloadToDictionary   Error {topic},{ex.Message}");
                     }
                 }
                 if (tpary[2] == "telemetry")
                 {
                     Task.Run(async() =>
                     {
                         try
                         {
                             var result = await _dbContext.SaveAsync <TelemetryLatest, TelemetryData>(keyValues, device, DataSide.ClientSide);
                         }
                         catch (Exception ex)
                         {
                             _logger.LogError(ex, $"Can't upload telemetry to device {device.Name}({device.Id}).the payload is {e.ApplicationMessage.ConvertPayloadToString()}");
                         }
                     });
                 }
                 else if (tpary[2] == "attributes")
                 {
                     if (tpary.Length > 3 && tpary[3] == "request")
                     {
                         Task.Run(async() =>
                         {
                             await RequestAttributes(tpary, e.ApplicationMessage.ConvertPayloadToDictionary(), device);
                         });
                     }
                     else
                     {
                         Task.Run(async() =>
                         {
                             try
                             {
                                 var result = await _dbContext.SaveAsync <AttributeLatest, AttributeData>(keyValues, device, DataSide.ClientSide);
                             }
                             catch (Exception ex)
                             {
                                 _logger.LogError(ex, $"Can't upload attributes to device {device.Name}({device.Id}).the payload is \"{e.ApplicationMessage.ConvertPayloadToString()}\"");
                             }
                         });
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 37
0
        internal static void LoadConfig()
        {
            if (System.IO.File.Exists(configGuiPath) && System.IO.File.Exists(configGuiPanelPath))
            {
                // 設定ファイルが存在
                {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load(configGuiPath);
                    int x      = doc["GUI"].GetTextAsInt("X");
                    int y      = doc["GUI"].GetTextAsInt("Y");
                    int width  = doc["GUI"].GetTextAsInt("Width");
                    int height = doc["GUI"].GetTextAsInt("Height");
                    MainForm.Location = new System.Drawing.Point(x, y);
                    MainForm.Width    = width;
                    MainForm.Height   = height;
                }

                {
                    Func <string, WeifenLuo.WinFormsUI.Docking.IDockContent> get_dock = (s) =>
                    {
                        if (DockViewer.GetType().FullName == s)
                        {
                            return(DockViewer);
                        }

                        if (DockViewerController.GetType().FullName == s)
                        {
                            return(DockViewerController);
                        }

                        if (DockNodeTreeView.GetType().FullName == s)
                        {
                            return(DockNodeTreeView);
                        }

                        if (DockViewPoint.GetType().FullName == s)
                        {
                            return(DockViewPoint);
                        }

                        if (DockRecorder.GetType().FullName == s)
                        {
                            return(DockRecorder);
                        }

                        if (DockNodeCommonValues.GetType().FullName == s)
                        {
                            return(DockNodeCommonValues);
                        }

                        if (DockNodeLocationValues.GetType().FullName == s)
                        {
                            return(DockNodeLocationValues);
                        }

                        if (DockNodeRotationValues.GetType().FullName == s)
                        {
                            return(DockNodeRotationValues);
                        }

                        if (DockNodeScalingValues.GetType().FullName == s)
                        {
                            return(DockNodeScalingValues);
                        }

                        if (DockNodeLocationAbsValues.GetType().FullName == s)
                        {
                            return(DockNodeLocationAbsValues);
                        }

                        if (DockNodeGenerationLocationValues.GetType().FullName == s)
                        {
                            return(DockNodeGenerationLocationValues);
                        }

                        if (DockNodeDepthValues.GetType().FullName == s)
                        {
                            return(DockNodeDepthValues);
                        }

                        if (DockNodeRendererCommonValues.GetType().FullName == s)
                        {
                            return(DockNodeRendererCommonValues);
                        }

                        if (DockNodeDrawingValues.GetType().FullName == s)
                        {
                            return(DockNodeDrawingValues);
                        }

                        if (DockNodeSoundValues.GetType().FullName == s)
                        {
                            return(DockNodeSoundValues);
                        }

                        if (DockOption.GetType().FullName == s)
                        {
                            return(DockOption);
                        }

                        if (DockGlobal.GetType().FullName == s)
                        {
                            return(DockGlobal);
                        }

                        if (DockCulling.GetType().FullName == s)
                        {
                            return(DockCulling);
                        }

                        if (DockEffectBehavior.GetType().FullName == s)
                        {
                            return(DockEffectBehavior);
                        }


                        if (DockFCurves.GetType().FullName == s)
                        {
                            return(DockFCurves);
                        }

                        if (DockNetwork.GetType().FullName == s)
                        {
                            return(DockNetwork);
                        }

                        if (DockFileViewer.GetType().FullName == s)
                        {
                            return(DockFileViewer);
                        }

                        return(null);
                    };

                    var deserializeDockContent = new WeifenLuo.WinFormsUI.Docking.DeserializeDockContent(get_dock);

                    MainForm.Panel.LoadFromXml(configGuiPanelPath, deserializeDockContent);
                }
            }
            else
            {
                // 設定ファイルが存在しない
                AssignDefaultPosition();
            }

            Network.Load(ConfigNetworkFileName);
        }
Ejemplo n.º 38
0
    // Set soundbank-related bool settings in the wproj file.
    public static bool EnableBoolSoundbankSettingInWproj(string SettingName, string WwiseProjectPath)
    {
        try
        {
            if (WwiseProjectPath.Length == 0)
            {
                return(true);
            }

            var doc = new System.Xml.XmlDocument();
            doc.PreserveWhitespace = true;
            doc.Load(WwiseProjectPath);
            var Navigator = doc.CreateNavigator();

            // Navigate the wproj file (XML format) to where our setting should be
            var pathInXml  = string.Format("/WwiseDocument/ProjectInfo/Project/PropertyList/Property[@Name='{0}']", SettingName);
            var expression = System.Xml.XPath.XPathExpression.Compile(pathInXml);
            var node       = Navigator.SelectSingleNode(expression);
            if (node == null)
            {
                // Setting isn't in the wproj, add it
                // Navigate to the SoundBankHeaderFilePath property (it is always there)
                expression =
                    System.Xml.XPath.XPathExpression.Compile(
                        "/WwiseDocument/ProjectInfo/Project/PropertyList/Property[@Name='SoundBankHeaderFilePath']");
                node = Navigator.SelectSingleNode(expression);
                if (node == null)
                {
                    // SoundBankHeaderFilePath not in wproj, invalid wproj file
                    UnityEngine.Debug.LogError(
                        "WwiseUnity: Could not find SoundBankHeaderFilePath property in Wwise project file. File is invalid.");
                    return(false);
                }

                // Add the setting right above SoundBankHeaderFilePath
                var propertyToInsert = string.Format("<Property Name=\"{0}\" Type=\"bool\" Value=\"True\"/>", SettingName);
                node.InsertBefore(propertyToInsert);
            }
            else if (node.GetAttribute("Value", "") == "False")
            {
                // Value is present, we simply have to modify it.
                if (!node.MoveToAttribute("Value", ""))
                {
                    return(false);
                }

                // Modify the value to true
                node.SetValue("True");
            }
            else
            {
                // Parameter already set, nothing to do!
                return(true);
            }

            doc.Save(WwiseProjectPath);
            return(true);
        }
        catch
        {
            return(false);
        }
    }
Ejemplo n.º 39
0
 public System.Xml.XmlNode GetSettings(System.Xml.XmlDocument document)
 {
     throw new NotSupportedException();
 }
 public System.Xml.XmlNode GetSettings(System.Xml.XmlDocument document)
 {
     return(Settings.GetSettings(document));
 }
Ejemplo n.º 41
0
        static Configuration()
        {
            ParseConfigFiles();

            mt_root             = GetVariable("MONOTOUCH_PREFIX", "/Library/Frameworks/Xamarin.iOS.framework/Versions/Current");
            ios_destdir         = GetVariable("IOS_DESTDIR", null);
            sdk_version         = GetVariable("IOS_SDK_VERSION", "8.0");
            watchos_sdk_version = GetVariable("WATCH_SDK_VERSION", "2.0");
            tvos_sdk_version    = GetVariable("TVOS_SDK_VERSION", "9.0");
            xcode_root          = GetVariable("XCODE_DEVELOPER_ROOT", "/Applications/Xcode.app/Contents/Developer");
            xcode5_root         = GetVariable("XCODE5_DEVELOPER_ROOT", "/Applications/Xcode511.app/Contents/Developer");
            xcode6_root         = GetVariable("XCODE6_DEVELOPER_ROOT", "/Applications/Xcode601.app/Contents/Developer");
            xcode72_root        = GetVariable("XCODE72_DEVELOPER_ROOT", "/Applications/Xcode72.app/Contents/Developer");
            include_ios         = !string.IsNullOrEmpty(GetVariable("INCLUDE_IOS", ""));
            include_mac         = !string.IsNullOrEmpty(GetVariable("INCLUDE_MAC", ""));
            include_tvos        = !string.IsNullOrEmpty(GetVariable("INCLUDE_TVOS", ""));
            include_watchos     = !string.IsNullOrEmpty(GetVariable("INCLUDE_WATCH", ""));
            include_device      = !string.IsNullOrEmpty(GetVariable("INCLUDE_DEVICE", ""));

            var version_plist = Path.Combine(xcode_root, "..", "version.plist");

            if (File.Exists(version_plist))
            {
                var settings = new System.Xml.XmlReaderSettings();
                settings.DtdProcessing = System.Xml.DtdProcessing.Ignore;
                var doc = new System.Xml.XmlDocument();
                using (var fs = new FileStream(version_plist, FileMode.Open, FileAccess.Read)) {
                    using (var reader = System.Xml.XmlReader.Create(fs, settings)) {
                        doc.Load(reader);
                        XcodeVersion = doc.DocumentElement.SelectSingleNode("//dict/key[text()='CFBundleShortVersionString']/following-sibling::string[1]/text()").Value;
                    }
                }
            }
#if MONOMAC
            mac_xcode_root = xcode_root;
#endif

            if (!Directory.Exists(mt_root) && !File.Exists(mt_root) && string.IsNullOrEmpty(ios_destdir))
            {
                mt_root = "/Developer/MonoTouch";
            }

            if (Directory.Exists(Path.Combine(mt_root, "usr")))
            {
                mt_root = Path.Combine(mt_root, "usr");
            }

            if (!string.IsNullOrEmpty(ios_destdir))
            {
                mt_root = Path.Combine(ios_destdir, mt_root.Substring(1));
            }

            Console.WriteLine("Test configuration:");
            Console.WriteLine("  MONOTOUCH_PREFIX={0}", mt_root);
            Console.WriteLine("  IOS_DESTDIR={0}", ios_destdir);
            Console.WriteLine("  SDK_VERSION={0}", sdk_version);
            Console.WriteLine("  XCODE_ROOT={0}", xcode_root);
            Console.WriteLine("  XCODE5_ROOT={0}", xcode5_root);
            Console.WriteLine("  XCODE6_ROOT={0} Exists={1}", xcode6_root, Directory.Exists(xcode6_root));
#if MONOMAC
            Console.WriteLine("  MAC_XCODE_ROOT={0}", mac_xcode_root);
#endif
            Console.WriteLine("  INCLUDE_IOS={0}", include_ios);
            Console.WriteLine("  INCLUDE_MAC={0}", include_mac);
            Console.WriteLine("  INCLUDE_TVOS={0}", include_tvos);
            Console.WriteLine("  INCLUDE_WATCHOS={0}", include_watchos);
        }
Ejemplo n.º 42
0
        /// <summary>
        /// there are 2 APIs to do the insert method
        /// </summary>
        /// <param name="value"></param>
        public override void DisplayValue(string value)
        {
            // base method will display the message in console screen
            base.DisplayValue(value);

            // 1. use the web service to insert into database
            if ((Convert.ToBoolean(ConfigurationManager.AppSettings["UseWebService"])))
            {
                // a. REST service call
                if ((Convert.ToBoolean(ConfigurationManager.AppSettings["RESTfulService"])))
                {
                    try
                    {
                        // this is my localhost uri
                        string uri = Properties.Settings.Default.RESTServiceUriLocal + value;   // "http://localhost:25118/restservice/write/" + value;
                        // this is my dev server uri
                        uri = Properties.Settings.Default.RESTServiceUriDevServer + value;      //"https://ca-dev-ws14:440/restservice/write/" + value;

                        HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
                        req.KeepAlive   = false;
                        req.Method      = "GET";
                        req.ContentType = "application/xml";
                        req.Accept      = "application/xml";

                        // since I created a self-signed certificate on my dev server so it's not trusted
                        // this code it to ignore the SSL error:
                        // "Could not establish trust relationship for the SSL/TLS secure channel with authority"
                        // comment the code below when we have a valid SSL certificate installed on the server for this service
                        System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                            (se, cert, chain, sslerror) =>
                        {
                            return(true);
                        };

                        HttpWebResponse resp             = req.GetResponse() as HttpWebResponse;
                        Encoding        enc              = System.Text.Encoding.GetEncoding(1252);
                        StreamReader    loResponseStream = new StreamReader(resp.GetResponseStream(), enc);
                        string          Response         = loResponseStream.ReadToEnd();
                        loResponseStream.Close();
                        resp.Close();
                        System.Xml.XmlDocument listXML = new System.Xml.XmlDocument();
                        listXML.LoadXml(Response);
                        System.Xml.XmlElement root = listXML.DocumentElement;
                        string result = root.InnerText;
                        Console.WriteLine("Inserted into database by RESTService: " + result);
                        Thread.Sleep(5000);
                    }
                    catch (Exception ex)
                    {
                    }
                }

                // b. WCF service call
                else
                {
                    try
                    {
                        // when the service is added as a local reference
                        WcfService1.Service1 service = new WcfService1.Service1();
                        bool result = service.WriteValue(value);
                        Console.WriteLine("Inserted into database by WCFService: " + result);
                        Thread.Sleep(5000);

                        // when the service is added as a web reference
                        WCFServiceHW.Service1 svc      = new WCFServiceHW.Service1();
                        bool writeValueResult          = false;
                        bool writeValueResultSpecified = true;
                        svc.WriteValue(value, out writeValueResult, out writeValueResultSpecified);
                        Console.WriteLine("Inserted into database by WCFService: " + writeValueResult);
                        Thread.Sleep(5000);
                    }
                    catch
                    {
                    }
                }
            }

            // 2. use the dll to insert into database
            else
            {
                DllHW dll    = new DllHW();
                bool  result = dll.WriteValue(value);
                Console.WriteLine("Inserted into database by DLL: " + result);
                Thread.Sleep(5000);
            }
        }
Ejemplo n.º 43
0
 public virtual System.Xml.XmlElement GetIdElement(System.Xml.XmlDocument document, string idValue)
 {
     throw null;
 }
Ejemplo n.º 44
0
        Serialize()
        {
            var document = new System.Xml.XmlDocument();

            var projectEl = this.CreateRootProject(document);

            projectEl.SetAttribute("DefaultTargets", "Build");

            var visualCMeta = Bam.Core.Graph.Instance.PackageMetaData <VisualC.MetaData>("VisualC");

            projectEl.SetAttribute("ToolsVersion", visualCMeta.VCXProjToolsVersion);

            // define configurations in the project
            var configurationItemGroup = document.CreateVSItemGroup("ProjectConfigurations", projectEl);

            foreach (var config in this.Configurations)
            {
                var projectConfigEl = document.CreateVSElement("ProjectConfiguration", parentEl: configurationItemGroup);
                projectConfigEl.SetAttribute("Include", config.Value.FullName);
                document.CreateVSElement("Configuration", value: config.Value.ConfigurationName, parentEl: projectConfigEl);
                document.CreateVSElement("Platform", value: config.Value.PlatformName, parentEl: projectConfigEl);
            }

            // global properties
            var globalPropertyGroup = document.CreateVSPropertyGroup(label: "Globals", parentEl: projectEl);

            document.CreateVSElement("ProjectGuid", value: this.Guid.ToString("B").ToUpper(), parentEl: globalPropertyGroup);
            var vcEnv = visualCMeta.Environment(GetModuleBitDepth(this.Module));

            if (vcEnv.ContainsKey("WindowsSDKVersion"))
            {
                var windowssdk_version = vcEnv["WindowsSDKVersion"].First().ToString().TrimEnd(System.IO.Path.DirectorySeparatorChar);
                document.CreateVSElement("WindowsTargetPlatformVersion", value: windowssdk_version, parentEl: globalPropertyGroup);
            }
            else
            {
                // appears to automatically fall back to 8.1
            }

            document.CreateVSImport(@"$(VCTargetsPath)\Microsoft.Cpp.Default.props", parentEl: projectEl);

            // configuration properties
            foreach (var config in this.Configurations)
            {
                config.Value.SerializeProperties(document, projectEl);
            }

            document.CreateVSImport(@"$(VCTargetsPath)\Microsoft.Cpp.props", parentEl: projectEl);
            if (this.AssemblyFiles.Any())
            {
                var extensionSettings = document.CreateVSImportGroup("ExtensionSettings", parentEl: projectEl);
                document.CreateVSImport(@"$(VCTargetsPath)\BuildCustomizations\masm.props", parentEl: extensionSettings);
            }

            // configuration paths
            foreach (var config in this.Configurations)
            {
                config.Value.SerializePaths(document, projectEl);
            }

            // tool settings
            foreach (var config in this.Configurations)
            {
                config.Value.SerializeSettings(document, projectEl);
            }

            // input files (these are VSSettingsGroups, but configuration agnostic)
            if (this.Sources.Count > 0)
            {
                var sourcesGroup = document.CreateVSItemGroup(parentEl: projectEl);
                foreach (var group in this.Sources)
                {
                    foreach (var config in this.Configurations)
                    {
                        if (!config.Value.ContainsSource(group))
                        {
                            group.AddSetting("ExcludedFromBuild", "true", config.Value.ConditionText);
                        }
                    }
                    group.Serialize(document, sourcesGroup);
                }
            }
            if (this.Headers.Count > 0)
            {
                var headersGroup = document.CreateVSItemGroup(parentEl: projectEl);
                foreach (var group in this.Headers)
                {
                    foreach (var config in this.Configurations)
                    {
                        if (!config.Value.ContainsHeader(group))
                        {
                            group.AddSetting("ExcludedFromBuild", "true", config.Value.ConditionText);
                        }
                    }
                    group.Serialize(document, headersGroup);
                }
            }
            if (this.Others.Count > 0)
            {
                var otherGroup = document.CreateVSItemGroup(parentEl: projectEl);
                foreach (var group in this.Others)
                {
                    group.Serialize(document, otherGroup);
                }
            }
            if (this.Resources.Count > 0)
            {
                var resourceGroup = document.CreateVSItemGroup(parentEl: projectEl);
                foreach (var group in this.Resources)
                {
                    foreach (var config in this.Configurations)
                    {
                        if (!config.Value.ContainsResourceFile(group))
                        {
                            group.AddSetting("ExcludedFromBuild", "true", config.Value.ConditionText);
                        }
                    }
                    group.Serialize(document, resourceGroup);
                }
            }
            if (this.AssemblyFiles.Count > 0)
            {
                var assemblerGroup = document.CreateVSItemGroup(parentEl: projectEl);
                foreach (var group in this.AssemblyFiles)
                {
                    foreach (var config in this.Configurations)
                    {
                        if (!config.Value.ContainsAssemblyFile(group))
                        {
                            group.AddSetting("ExcludedFromBuild", "true", config.Value.ConditionText);
                        }
                    }
                    group.Serialize(document, assemblerGroup);
                }
            }

            // dependent projects
            this.SerializeDependentProjects(document, projectEl);

            document.CreateVSImport(@"$(VCTargetsPath)\Microsoft.Cpp.targets", parentEl: projectEl);
            if (this.AssemblyFiles.Any())
            {
                var extensionTargets = document.CreateVSImportGroup("ExtensionTargets", parentEl: projectEl);
                document.CreateVSImport(@"$(VCTargetsPath)\BuildCustomizations\masm.targets", parentEl: extensionTargets);
            }

            return(document);
        }
Ejemplo n.º 45
0
 public EncryptedXml(System.Xml.XmlDocument document)
 {
 }
Ejemplo n.º 46
0
 public System.Xml.XmlNode GetSettings(System.Xml.XmlDocument document)
 {
     return(document.CreateElement("SeparatorSettings"));
 }
Ejemplo n.º 47
0
        private void guardarXML(Stream myStream)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            //System.Xml.XmlAttribute atributo;

            System.Xml.XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "");
            doc.AppendChild(declaration);

            System.Xml.XmlNode pmml = doc.CreateElement("PMML");

            /*
             * atributo = doc.CreateAttribute("version");
             * atributo.InnerText = "3.0";
             * pmml.Attributes.Append(atributo);
             * atributo = doc.CreateAttribute("xmlns");
             * atributo.InnerText = "http://www.dmg.org/PMML-3-0";
             * pmml.Attributes.Append(atributo);
             * atributo = doc.CreateAttribute("xmlns:xsi");
             * atributo.InnerText = "http://www.w3.org/2001/XMLSchema_instance";
             * pmml.Attributes.Append(atributo);
             */

            pmml.Attributes.Append(setAtributo(doc, "version", "3.0"));
            pmml.Attributes.Append(setAtributo(doc, "xmlns", "http://www.dmg.org/PMML-3-0"));
            pmml.Attributes.Append(setAtributo(doc, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema_instance"));
            doc.AppendChild(pmml);

            System.Xml.XmlNode sprite = doc.CreateElement("TEXTURA");
            if (textureName.Text.Equals(""))
            {
                sprite.Attributes.Append(setAtributo(doc, "Name", "none"));
            }
            else
            {
                sprite.Attributes.Append(setAtributo(doc, "Name", textureName.Text));
            }

            if (useRelativePath.Checked && !relativeFileLoc.Equals(""))
            {
                sprite.Attributes.Append(setAtributo(doc, "TextureFile", relativeFileLoc.Insert(0, "..\\").Replace('\\', '/')));
            }
            else
            {
                sprite.Attributes.Append(setAtributo(doc, "TextureFile", fileLoc));
            }

            int colorR = color_click.BackColor.R;
            int colorG = color_click.BackColor.G;
            int colorB = color_click.BackColor.B;

            //sprite.Attributes.Append(setAtributo(doc, "ColorKey", "FF"+R+G+B));
            System.Xml.XmlNode colorKey = doc.CreateElement("ColorKey");
            colorKey.Attributes.Append(setAtributo(doc, "R", colorR.ToString()));
            colorKey.Attributes.Append(setAtributo(doc, "G", colorG.ToString()));
            colorKey.Attributes.Append(setAtributo(doc, "B", colorB.ToString()));
            sprite.AppendChild(colorKey);
            pmml.AppendChild(sprite);

            /*
             * doc.AppendChild(XClub);
             * System.Xml.XmlNode Pelicula = doc.CreateElement("Pelicula");
             * XClub.AppendChild(Pelicula);
             * System.Xml.XmlNode Data = doc.CreateElement("Data");
             * System.Xml.XmlAttribute atributo = doc.CreateAttribute("Titulo");
             * atributo.InnerText = "Garganta Profunda(Deep Throat)";
             * Data.Attributes.Append(atributo);
             * System.Xml.XmlAttribute atributo2 = doc.CreateAttribute("Director");
             * atributo2.InnerText = "";
             * Data.Attributes.Append(atributo2);
             * Pelicula.AppendChild(Data);*/
            doc.Save(myStream);
        }
Ejemplo n.º 48
0
 public EncryptedXml(System.Xml.XmlDocument document, System.Security.Policy.Evidence evidence)
 {
 }
Ejemplo n.º 49
0
 public System.Collections.Generic.Dictionary <Guid, object> Load(System.Xml.XmlDocument dom)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 50
0
 public SignedXml(System.Xml.XmlDocument document)
 {
 }
Ejemplo n.º 51
0
        public void Simulate()
        {
            const string projectName1 = "triggerTest01";
            const string projectName2 = "triggerTest02";


            var integrationFolder = System.IO.Path.Combine("scenarioTests", projectName1);
            var ccNetConfigFile   = System.IO.Path.Combine("IntegrationScenarios", "Triggers.xml");
            var project1StateFile = new System.IO.FileInfo(projectName1 + ".state").FullName;
            var project2StateFile = new System.IO.FileInfo(projectName2 + ".state").FullName;

            IntegrationCompleted.Add(projectName1, false);
            IntegrationCompleted.Add(projectName2, false);

            const Int32 secondsToWaitFromNow = 120;
            // adjust triggertime of project 1 to now + 70 seconds (SecondsToWaitFromNow)
            // this will give the unittest time to create an ok build of project2
            // and let the schedule trigger work as normal : check if it is time to integrate and check on the status
            // 70 seconds should be ok, less time may give problems on slower machines
            // keep in mind that cruise server is also starting, so this time must also be taken into account
            // also we want the cuise server to wait for 1 minute, otherwise it starts integrating project 1 immediately
            var xdoc = new System.Xml.XmlDocument();

            xdoc.Load(ccNetConfigFile);
            var xslt            = string.Format(System.Globalization.CultureInfo.CurrentCulture, "/cruisecontrol/project[@name='{0}']/triggers/scheduleTrigger", projectName1);
            var scheduleTrigger = xdoc.SelectSingleNode(xslt);

            if (scheduleTrigger == null)
            {
                throw new CruiseControlException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Schedule trigger not found,via xslt {0} in configfile {1}", xslt, ccNetConfigFile));
            }

            var newIntegrationTime = System.DateTime.Now.AddSeconds(secondsToWaitFromNow).ToString("HH:mm");

            Log("--------------------------------------------------------------------------");
            Log(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0} is scheduled to integrate at {1}", projectName1, newIntegrationTime));
            Log("--------------------------------------------------------------------------");

            scheduleTrigger.Attributes["time"].Value = newIntegrationTime;
            xdoc.Save(ccNetConfigFile);


            Log("Clear existing state file, to simulate first run : " + project1StateFile);
            System.IO.File.Delete(project1StateFile);

            Log("Clear existing state file, to simulate first run : " + project2StateFile);
            System.IO.File.Delete(project2StateFile);


            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(integrationFolder))
            {
                System.IO.Directory.Delete(integrationFolder, true);
            }


            CCNet.Remote.Messages.ProjectStatusResponse psr;
            var pr1 = new CCNet.Remote.Messages.ProjectRequest(null, projectName1);
            var pr2 = new CCNet.Remote.Messages.ProjectRequest(null, projectName2);



            Log("Making CruiseServerFactory");
            var csf = new CCNet.Core.CruiseServerFactory();

            Log("Making cruiseServer with config from :" + ccNetConfigFile);
            using (var cruiseServer = csf.Create(true, ccNetConfigFile))
            {
                // subscribe to integration complete to be able to wait for completion of a build
                cruiseServer.IntegrationCompleted += new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                Log("Forcing build on project " + projectName1 + " to test the innertrigger");
                CheckResponse(cruiseServer.ForceBuild(pr1));

                System.Threading.Thread.Sleep(250); // give time to start the build

                Log("Waiting for integration to complete of : " + projectName1);
                while (!IntegrationCompleted[projectName1])
                {
                    for (int i = 1; i <= 4; i++)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    Log(" waiting ...");
                }


                // un-subscribe to integration complete
                cruiseServer.IntegrationCompleted -= new EventHandler <ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("getting project status");
                psr = cruiseServer.GetProjectStatus(pr1);
                CheckResponse(psr);

                Log("Stopping cruiseServer");
                cruiseServer.Stop();

                Log("waiting for cruiseServer to stop");
                cruiseServer.WaitForExit(pr1);
                Log("cruiseServer stopped");
            }

            Log("Checking the data");
            Assert.AreEqual(2, psr.Projects.Count, "Amount of projects in configfile is not correct." + ccNetConfigFile);

            CCNet.Remote.ProjectStatus ps = null;

            // checking data of project 1
            foreach (var p in psr.Projects)
            {
                if (p.Name == projectName1)
                {
                    ps = p;
                }
            }

            Assert.AreEqual(projectName1, ps.Name);
            Assert.AreEqual(CCNet.Remote.IntegrationStatus.Success, ps.BuildStatus, "wrong build state for project " + projectName1);


            // checking data of project 2
            foreach (var p in psr.Projects)
            {
                if (p.Name == projectName2)
                {
                    ps = p;
                }
            }

            Assert.AreEqual(projectName2, ps.Name);
            Assert.AreEqual(CCNet.Remote.IntegrationStatus.Unknown, ps.BuildStatus, "wrong build state for project " + projectName2);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Check for an update at urlToCheck and download and run it.
        /// </summary>
        /// <param name="urlToCheck"></param>
        public static void CheckForUpdates(string urlToCheck)
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            try
            {
                xmlDoc.Load(urlToCheck);
            }
            catch
            {
                // Not online or problem with XML. Fail silently.
                return;
            }
            string version = xmlDoc.DocumentElement.SelectSingleNode("Version").InnerText;

            if (version != System.Windows.Forms.Application.ProductVersion)
            {
                // Need to update.
                System.Net.WebClient wc = new System.Net.WebClient();
                string filename         = xmlDoc.DocumentElement.SelectSingleNode("Filename").InnerText;
                string path             = System.IO.Path.GetTempPath() + filename;
                if (System.IO.File.Exists(path))
                {
                    try
                    {
                        System.IO.File.Delete(path);
                        System.Windows.Forms.Application.DoEvents();
                    }
                    catch
                    {
                        // Probably already in use. Fail silently.
                        return;
                    }
                }
                try
                {
                    // Download the new installer.
                    wc.DownloadFileAsync(new System.Uri(xmlDoc.DocumentElement.SelectSingleNode("URL").InnerText), path);
                    while (wc.IsBusy)
                    {
                        System.Windows.Forms.Application.DoEvents();
                    }

                    // Create an installer batch file.
                    // Get the path
                    string batchPath = System.IO.Path.GetTempPath() + filename + ".bat";
                    if (System.IO.File.Exists(batchPath))
                    {
                        System.IO.File.Delete(batchPath);
                        System.Windows.Forms.Application.DoEvents();
                    }
                    // Write the batch file.
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(batchPath);
                    sw.WriteLine("@title Updating " + System.Windows.Forms.Application.ProductName);
                    sw.WriteLine("@echo Updating " + System.Windows.Forms.Application.ProductName);
                    sw.WriteLine("@cd \"" + System.IO.Path.GetTempPath() + "\"");
                    // Put in a pause to allow this application to close.
                    sw.WriteLine("@choice /D:Y /T:2 /N");
                    sw.WriteLine("@msiexec /I \"" + filename + "\" /passive");
                    //sw.WriteLine("pause");
                    sw.Close();

                    // Now execute the batch file.
                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    // Turns out we probably want to show the window so the user can get an
                    // idea something is happening.
                    //proc.StartInfo.CreateNoWindow = true;
                    //proc.StartInfo.RedirectStandardOutput = true;
                    //proc.StartInfo.RedirectStandardError = true;
                    proc.StartInfo.FileName        = batchPath;
                    proc.StartInfo.UseShellExecute = false;
                    proc.Start();

                    // And close this application!
                    System.Windows.Forms.Application.Exit();
                    return;
                }
                catch
                {
                    // Failed to download for some reason, fail silently.
                    return;
                }
            }
        }
Ejemplo n.º 53
0
        //**********************************************************************
        /// <summary>
        /// Xml→DataRow変換
        /// </summary>
        /// <param name="pstrXml">Xml</param>
        /// <param name="pRow">DataRow</param>
        /// <returns>true:正常 false:異常</returns>
        //**********************************************************************
        public static bool XmlToDatarow(string pstrXml, ref DataRow pRow)
        {
            string lstrCol = "";
            string lstrTmp = "";

            try
            {
                //--------------------------------------
                // データ初期化
                //--------------------------------------
                InitDatarow(ref pRow);

                //--------------------------------------
                // 引数確認
                //--------------------------------------
                if (pstrXml.Trim() == "")
                {
                    return(false);
                }

                //--------------------------------------
                // Xml
                //--------------------------------------
                System.Xml.XmlDocument lobjXmlDocument;
                System.Xml.XmlNode     lobjXmlNode;
                try
                {
                    lobjXmlDocument = new System.Xml.XmlDocument();
                    lobjXmlDocument.Load(new System.IO.StringReader("<QR>" + pstrXml + "</QR>"));
                    lobjXmlNode = lobjXmlDocument.DocumentElement;
                }
                catch
                {
                    // Xml形式でなければ処理なし
                    return(false);
                }

                //--------------------------------------
                // DataRowのColumn名称でXmlからデータ取得
                //--------------------------------------
                foreach (DataColumn lobjCol in pRow.Table.Columns)
                {
                    // DataRowのColumn名取得
                    lstrCol = lobjCol.ColumnName;
                    // DataRowのColumn名でXml情報取得
                    try
                    {
                        lstrTmp = lobjXmlNode.SelectSingleNode(lstrCol).InnerText;
                    }
                    catch
                    {
                        lstrTmp = "";
                    }
                    // DataRowの型に応じてデータ設定
                    pRow[lstrCol] = TypeConv(lstrTmp, lobjCol.DataType);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 54
0
        public static bool LoadFrom(string path)
        {
            path = System.IO.Path.GetFullPath(path);

            if (!System.IO.File.Exists(path))
            {
                return(false);
            }
            SelectedNode = null;

            FullPath = path;

            var doc = new System.Xml.XmlDocument();

            doc.Load(path);

            if (doc.ChildNodes.Count != 2)
            {
                return(false);
            }
            if (doc.ChildNodes[1].Name != "EffekseerProject")
            {
                return(false);
            }

            if (OnBeforeLoad != null)
            {
                OnBeforeLoad(null, null);
            }

            uint toolVersion = 0;

            if (doc["EffekseerProject"]["ToolVersion"] != null)
            {
                var fileVersion    = doc["EffekseerProject"]["ToolVersion"].GetText();
                var currentVersion = Core.Version;

                toolVersion = ParseVersion(fileVersion);

                if (toolVersion > ParseVersion(currentVersion))
                {
                    switch (Language)
                    {
                    case Effekseer.Language.English:
                        throw new Exception("Version Error : \nThe file is created with a newer version of the tool.\nPlease use the latest version of the tool.");
                        break;

                    case Effekseer.Language.Japanese:
                        throw new Exception("Version Error : \nファイルがより新しいバージョンのツールで作成されています。\n最新バージョンのツールを使用してください。");
                        break;
                    }
                }
            }

            // For compatibility
            {
                // Stripe→Ribbon
                var innerText = doc.InnerXml;
                innerText = innerText.Replace("<Stripe>", "<Ribbon>").Replace("</Stripe>", "</Ribbon>");
                doc       = new System.Xml.XmlDocument();
                doc.LoadXml(innerText);
            }

            // For compatibility
            {
                // GenerationTime
                // GenerationTimeOffset

                Action <System.Xml.XmlNode> replace = null;
                replace = (node) =>
                {
                    if ((node.Name == "GenerationTime" || node.Name == "GenerationTimeOffset") &&
                        node.ChildNodes.Count > 0 &&
                        node.ChildNodes[0] is System.Xml.XmlText)
                    {
                        var name  = node.Name;
                        var value = node.ChildNodes[0].Value;

                        node.RemoveAll();

                        var center = doc.CreateElement("Center");
                        var max    = doc.CreateElement("Max");
                        var min    = doc.CreateElement("Min");

                        center.AppendChild(doc.CreateTextNode(value));
                        max.AppendChild(doc.CreateTextNode(value));
                        min.AppendChild(doc.CreateTextNode(value));

                        node.AppendChild(center);
                        node.AppendChild(max);
                        node.AppendChild(min);
                    }
                    else
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            replace(node.ChildNodes[i]);
                        }
                    }
                };

                replace(doc);
            }

            var root = doc["EffekseerProject"]["Root"];

            if (root == null)
            {
                return(false);
            }

            var behaviorElement = doc["EffekseerProject"]["Behavior"];

            if (behaviorElement != null)
            {
                var o = effectBehavior as object;
                Data.IO.LoadObjectFromElement(behaviorElement as System.Xml.XmlElement, ref o, false);
            }
            else
            {
                effectBehavior = new Data.EffectBehaviorValues();
            }

            var cullingElement = doc["EffekseerProject"]["Culling"];

            if (cullingElement != null)
            {
                var o = culling as object;
                Data.IO.LoadObjectFromElement(cullingElement as System.Xml.XmlElement, ref o, false);
            }
            else
            {
                culling = new Data.EffectCullingValues();
            }

            var globalElement = doc["EffekseerProject"]["Global"];

            if (globalElement != null)
            {
                var o = globalValues as object;
                Data.IO.LoadObjectFromElement(globalElement as System.Xml.XmlElement, ref o, false);
            }
            else
            {
                globalValues = new Data.GlobalValues();
            }

            StartFrame = 0;
            EndFrame   = doc["EffekseerProject"]["EndFrame"].GetTextAsInt();
            StartFrame = doc["EffekseerProject"]["StartFrame"].GetTextAsInt();
            IsLoop     = bool.Parse(doc["EffekseerProject"]["IsLoop"].GetText());
            IsLoop     = true;

            int version = 0;

            if (doc["EffekseerProject"]["Version"] != null)
            {
                version = doc["EffekseerProject"]["Version"].GetTextAsInt();
            }

            var root_node = new Data.NodeRoot() as object;

            Data.IO.LoadObjectFromElement(root as System.Xml.XmlElement, ref root_node, false);

            // For compatibility
            if (version < 3)
            {
                Action <Data.NodeBase> convert = null;
                convert = (n) =>
                {
                    var n_ = n as Data.Node;

                    if (n_ != null)
                    {
                        if (n_.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Sprite)
                        {
                            n_.RendererCommonValues.ColorTexture.SetAbsolutePathDirectly(n_.DrawingValues.Sprite.ColorTexture.AbsolutePath);
                            n_.RendererCommonValues.AlphaBlend.SetValueDirectly(n_.DrawingValues.Sprite.AlphaBlend.Value);
                        }
                        else if (n_.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Ring)
                        {
                            n_.RendererCommonValues.ColorTexture.SetAbsolutePathDirectly(n_.DrawingValues.Ring.ColorTexture.AbsolutePath);
                            n_.RendererCommonValues.AlphaBlend.SetValueDirectly(n_.DrawingValues.Ring.AlphaBlend.Value);
                        }
                        else if (n_.DrawingValues.Type.Value == Data.RendererValues.ParamaterType.Ribbon)
                        {
                            n_.RendererCommonValues.ColorTexture.SetAbsolutePathDirectly(n_.DrawingValues.Ribbon.ColorTexture.AbsolutePath);
                            n_.RendererCommonValues.AlphaBlend.SetValueDirectly(n_.DrawingValues.Ribbon.AlphaBlend.Value);
                        }
                    }

                    for (int i = 0; i < n.Children.Count; i++)
                    {
                        convert(n.Children[i]);
                    }
                };

                convert(root_node as Data.NodeBase);
            }

            Root = root_node as Data.NodeRoot;
            Command.CommandManager.Clear();
            IsChanged = false;

            if (OnAfterLoad != null)
            {
                OnAfterLoad(null, null);
            }

            return(true);
        }
Ejemplo n.º 55
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="PxApp"></param>
        /// <param name="TopList"></param>
        /// <param name="FilterExtent">Optional, if not null it will be used to filter the notes to the current extent</param>
        /// <param name="UseLookupTable">Whether to perform a search / replace of the CUNames in the Design before outputting them</param>
        /// <returns></returns>
        public static string GetConstructionNotes(IMMPxApplication PxApp, IMMPersistentXML ListItem, IEnvelope FilterExtent)
        {
            if (PxApp == null)
            {
                throw new Exception("No Px Application found");
            }
            if (ListItem == null)
            {
                throw new Exception("No item given to generate notes for");
            }

            string XslPath = "";

            try
            {
                XslPath = DesignerUtility.GetPxConfig(PxApp, Constants.PxConfig_ContstructionNotesXslPath);
                if (string.IsNullOrEmpty(XslPath))
                {
                    throw new Exception("Obtained an empty reference to the Construction Notes Stylesheet.  Ask your administrator to verify the Px Configuration.");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to find a Px Configuration for the Construction Notes Stylesheet.  Ask your administrator to verify the Px Configuration.", ex);
            }

            //Our resulting XML must have Work Locations / Gis Units in order to filter it
            System.Xml.XmlDocument modernDocument = null;
            string labelXmlType = DesignerUtility.GetPxConfig(PxApp, Constants.PxConfig_ContstructionNotesXmlSource);

            switch (labelXmlType)
            {
            case "DesignTree":
                modernDocument = GetReportingXml(PxApp, ListItem, LabelXmlType.DesignTree);
                break;

            default:
            case "DesignerXml":
                modernDocument = GetReportingXml(PxApp, ListItem, LabelXmlType.DesignerXml);
                break;

            case "PxXml":
                modernDocument = GetReportingXml(PxApp, ListItem, LabelXmlType.PxXml);
                break;

            case "CostEngine":
                modernDocument = GetReportingXml(PxApp, ListItem, LabelXmlType.CostEngine);
                break;

            case "Custom":
                modernDocument = GetReportingXml(PxApp, ListItem, LabelXmlType.Custom);
                break;
            }

            if (FilterExtent != null)
            {
                #region Fitler the Design Xml

                IRelationalOperator IRO = FilterExtent as IRelationalOperator;

                //Build up a list of Work Locations in the current extent
                List <string> BadWls = new List <string>();
                List <string> BadGus = new List <string>();

                ID8ListItem WlOrCu    = null;
                ID8ListItem GivenItem = ListItem as ID8ListItem;
                if (GivenItem == null)
                {
                    throw new ApplicationException("Selected item is not a valid list item");
                }

                if (GivenItem.ItemType == mmd8ItemType.mmd8itWorkRequest)
                {
                    ((ID8List)GivenItem).Reset();
                    ID8List Design = ((ID8List)GivenItem).Next(false) as ID8List;
                    GivenItem = Design as ID8ListItem;
                    ((ID8List)GivenItem).Reset();
                    WlOrCu = ((ID8List)GivenItem).Next(false);
                }
                else if (GivenItem.ItemType == mmd8ItemType.mmd8itDesign)
                {
                    ((ID8List)GivenItem).Reset();
                    WlOrCu = ((ID8List)GivenItem).Next(false);
                }
                else if (GivenItem.ItemType == mmd8ItemType.mmd8itWorkLocation)
                {
                    WlOrCu = (ID8ListItem)GivenItem;
                }
                else
                {
                    throw new ApplicationException("Construction notes are not supported on the selected item");
                }

                while (WlOrCu != null)
                {
                    if (WlOrCu.ItemType == mmd8ItemType.mmd8itWorkLocation)
                    {
                        if (!HasD8ChildInExtent(IRO, WlOrCu as ID8List))
                        {
                            BadWls.Add(((ID8WorkLocation)WlOrCu).ID);
                        }
                    }
                    else
                    {
                        if (WlOrCu.ItemType == mmd8ItemType.mmitMMGisUnit)
                        {
                            if (!HasD8ChildInExtent(IRO, WlOrCu as ID8List))
                            {
                                BadGus.Add(((IMMGisUnit)WlOrCu).GisUnitID.ToString());
                            }
                        }
                    }

                    WlOrCu = ((ID8List)GivenItem).Next(false);
                }

                string wlquery = "";
                foreach (string wlid in BadWls)
                {
                    if (!string.IsNullOrEmpty(wlid))
                    {
                        wlquery += "//WORKLOCATION[ID='" + wlid + "']|";
                    }
                }
                wlquery = wlquery.TrimEnd("|".ToCharArray());

                string guquery = "";
                foreach (string guid in BadGus)
                {
                    if (!string.IsNullOrEmpty(guid))
                    {
                        guquery += "//GISUNIT[DESIGNER_ID='" + guid + "']|";
                    }
                }
                guquery = guquery.TrimEnd("|".ToCharArray());

                string query = wlquery + "|" + guquery;
                query = query.Trim("|".ToCharArray());

                //Filter the xml document to remove the bad wls
                if (!string.IsNullOrEmpty(query))
                {
                    foreach (System.Xml.XmlNode BadNode in modernDocument.SelectNodes(query))
                    {
                        BadNode.ParentNode.RemoveChild(BadNode);
                    }
                }

                #endregion
            }

            return(TransformXml(modernDocument, XslPath));
        }
Ejemplo n.º 56
0
        private String[,] GetRssData(String channel)
        {
            var xml = "";

            using (var client = new System.Net.WebClient())
            {
                client.Encoding = Encoding.UTF8;
                xml             = client.DownloadString(channel);
            }
            var dom = new System.Xml.XmlDocument();

            dom.LoadXml(xml);

            const string Path = @"G:\xmlfil";

            //const string filePath = @"G:";
            if (Directory.Exists(Path) == false)
            {
                Directory.CreateDirectory(Path);
            }
            var dirs  = Directory.EnumerateDirectories(Path);
            var files = Directory.EnumerateFiles(Path);

            //Directory.Delete(Path);

            var dir = new DirectoryInfo(@"C:\Users\david\Desktop\test2");

            if (dir.Exists == false)
            {
                dir.Create();
            }
            using (var stream = new FileStream(@"G:\xmlfil.xml", FileMode.Create, FileAccess.Write))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(xml);
                }
            }
            //dir.Delete();

            /*            using (var stream = new FileStream(@"G:\xml.xml", FileMode.Open))
             *          {
             *              using (var reader = new StreamReader(stream))
             *              {
             *                  var readXml = reader.ReadToEnd();
             *                  //Assert.AreEqual(xml, readXml);
             *              }
             *          }
             */
            //var f = new feed();

            foreach (System.Xml.XmlNode item in dom.DocumentElement.SelectSingleNode("channel/title"))
            {
                var title = item.InnerText;
                displayPod.Items.Add(title);
            }

            foreach (System.Xml.XmlNode item in dom.DocumentElement.SelectNodes("item/title"))
            {
                var titleName = item.InnerText;
                displayPodCasts.Items.Add(titleName);
            }
            return(rssData);
        }
Ejemplo n.º 57
0
 internal static object NullCheck(System.Xml.XmlDocument value)
 {
     return(value ?? (object)DBNull.Value);
 }
Ejemplo n.º 58
0
 /// <summary>
 /// 获取当前任务周期的配置信息,将序列化的内容填充至 XmlNode 的 InnerText 属性或者 ChildNodes 子节点中。
 /// </summary>
 /// <param name="xmlDoc">创建 XmlNode 时所需使用到的 System.Xml.XmlDocument。</param>
 /// <returns></returns>
 public override System.Xml.XmlNode GetTaskPeriodConfig(System.Xml.XmlDocument xmlDoc)
 {
     System.Xml.XmlNode xnConfig = xmlDoc.CreateElement(this.GetType().Name);
     xnConfig.InnerText = this.TimeNum.ToString();
     return(xnConfig);
 }
Ejemplo n.º 59
0
        /// <summary>
        /// Shows how to perform the following tasks with solutions:
        /// - Create a Publisher
        /// - Retrieve the Default Publisher
        /// - Create a Solution
        /// - Retrieve a Solution
        /// - Add an existing Solution Component
        /// - Remove a Solution Component
        /// - Export or Package a Solution
        /// - Install or Upgrade a solution
        /// - Delete a Solution
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();
                    //<snippetWorkWithSolutions1>


                    //Define a new publisher
                    Publisher _crmSdkPublisher = new Publisher
                    {
                        UniqueName           = "sdksamples",
                        FriendlyName         = "Microsoft CRM SDK Samples",
                        SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx",
                        CustomizationPrefix  = "sample",
                        EMailAddress         = "*****@*****.**",
                        Description          = "This publisher was created with samples from the Microsoft Dynamics CRM SDK"
                    };

                    //Does publisher already exist?
                    QueryExpression querySDKSamplePublisher = new QueryExpression
                    {
                        EntityName = Publisher.EntityLogicalName,
                        ColumnSet  = new ColumnSet("publisherid", "customizationprefix"),
                        Criteria   = new FilterExpression()
                    };

                    querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName);
                    EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher);
                    Publisher        SDKSamplePublisherResults      = null;

                    //If it already exists, use it
                    if (querySDKSamplePublisherResults.Entities.Count > 0)
                    {
                        SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0];
                        _crmSdkPublisherId        = (Guid)SDKSamplePublisherResults.PublisherId;
                        _customizationPrefix      = SDKSamplePublisherResults.CustomizationPrefix;
                    }
                    //If it doesn't exist, create it
                    if (SDKSamplePublisherResults == null)
                    {
                        _crmSdkPublisherId = _serviceProxy.Create(_crmSdkPublisher);
                        Console.WriteLine(String.Format("Created publisher: {0}.", _crmSdkPublisher.FriendlyName));
                        _customizationPrefix = _crmSdkPublisher.CustomizationPrefix;
                    }



                    //</snippetWorkWithSolutions1>

                    //<snippetWorkWithSolutions2>
                    // Retrieve the Default Publisher

                    //The default publisher has a constant GUID value;
                    Guid DefaultPublisherId = new Guid("{d21aab71-79e7-11dd-8874-00188b01e34f}");

                    Publisher DefaultPublisher = (Publisher)_serviceProxy.Retrieve(Publisher.EntityLogicalName, DefaultPublisherId, new ColumnSet(new string[] { "friendlyname" }));

                    EntityReference DefaultPublisherReference = new EntityReference
                    {
                        Id          = DefaultPublisher.Id,
                        LogicalName = Publisher.EntityLogicalName,
                        Name        = DefaultPublisher.FriendlyName
                    };
                    Console.WriteLine("Retrieved the {0}.", DefaultPublisherReference.Name);
                    //</snippetWorkWithSolutions2>

                    //<snippetWorkWithSolutions3>
                    // Create a Solution
                    //Define a solution
                    Solution solution = new Solution
                    {
                        UniqueName   = "samplesolution",
                        FriendlyName = "Sample Solution",
                        PublisherId  = new EntityReference(Publisher.EntityLogicalName, _crmSdkPublisherId),
                        Description  = "This solution was created by the WorkWithSolutions sample code in the Microsoft Dynamics CRM SDK samples.",
                        Version      = "1.0"
                    };

                    //Check whether it already exists
                    QueryExpression queryCheckForSampleSolution = new QueryExpression
                    {
                        EntityName = Solution.EntityLogicalName,
                        ColumnSet  = new ColumnSet(),
                        Criteria   = new FilterExpression()
                    };
                    queryCheckForSampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName);

                    //Create the solution if it does not already exist.
                    EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(queryCheckForSampleSolution);
                    Solution         SampleSolutionResults      = null;
                    if (querySampleSolutionResults.Entities.Count > 0)
                    {
                        SampleSolutionResults      = (Solution)querySampleSolutionResults.Entities[0];
                        _solutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId;
                    }
                    if (SampleSolutionResults == null)
                    {
                        _solutionsSampleSolutionId = _serviceProxy.Create(solution);
                    }
                    //</snippetWorkWithSolutions3>

                    //<snippetWorkWithSolutions4>
                    // Retrieve a solution
                    String          solutionUniqueName  = "samplesolution";
                    QueryExpression querySampleSolution = new QueryExpression
                    {
                        EntityName = Solution.EntityLogicalName,
                        ColumnSet  = new ColumnSet(new string[] { "publisherid", "installedon", "version", "versionnumber", "friendlyname" }),
                        Criteria   = new FilterExpression()
                    };

                    querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solutionUniqueName);
                    Solution SampleSolution = (Solution)_serviceProxy.RetrieveMultiple(querySampleSolution).Entities[0];
                    //</snippetWorkWithSolutions4>

                    //<snippetWorkWithSolutions5>
                    // Add an existing Solution Component
                    //Add the Account entity to the solution
                    RetrieveEntityRequest retrieveForAddAccountRequest = new RetrieveEntityRequest()
                    {
                        LogicalName = Account.EntityLogicalName
                    };
                    RetrieveEntityResponse      retrieveForAddAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForAddAccountRequest);
                    AddSolutionComponentRequest addReq = new AddSolutionComponentRequest()
                    {
                        ComponentType      = (int)componenttype.Entity,
                        ComponentId        = (Guid)retrieveForAddAccountResponse.EntityMetadata.MetadataId,
                        SolutionUniqueName = solution.UniqueName
                    };
                    _serviceProxy.Execute(addReq);
                    //</snippetWorkWithSolutions5>

                    //<snippetWorkWithSolutions6>
                    // Remove a Solution Component
                    //Remove the Account entity from the solution
                    RetrieveEntityRequest retrieveForRemoveAccountRequest = new RetrieveEntityRequest()
                    {
                        LogicalName = Account.EntityLogicalName
                    };
                    RetrieveEntityResponse retrieveForRemoveAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForRemoveAccountRequest);

                    RemoveSolutionComponentRequest removeReq = new RemoveSolutionComponentRequest()
                    {
                        ComponentId        = (Guid)retrieveForRemoveAccountResponse.EntityMetadata.MetadataId,
                        ComponentType      = (int)componenttype.Entity,
                        SolutionUniqueName = solution.UniqueName
                    };
                    _serviceProxy.Execute(removeReq);
                    //</snippetWorkWithSolutions6>

                    //<snippetWorkWithSolutions7>
                    // Export or package a solution
                    //Export an a solution

                    ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
                    exportSolutionRequest.Managed      = false;
                    exportSolutionRequest.SolutionName = solution.UniqueName;

                    ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest);

                    byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
                    string filename  = solution.UniqueName + ".zip";
                    File.WriteAllBytes(outputDir + filename, exportXml);

                    Console.WriteLine("Solution exported to {0}.", outputDir + filename);
                    //</snippetWorkWithSolutions7>

                    //<snippetWorkWithSolutions8>
                    // Install or Upgrade a Solution

                    byte[] fileBytes = File.ReadAllBytes(ManagedSolutionLocation);

                    ImportSolutionRequest impSolReq = new ImportSolutionRequest()
                    {
                        CustomizationFile = fileBytes
                    };

                    _serviceProxy.Execute(impSolReq);

                    Console.WriteLine("Imported Solution from {0}", ManagedSolutionLocation);
                    //</snippetWorkWithSolutions8>


                    //<snippetWorkWithSolutions9>
                    // Monitor import success
                    byte[] fileBytesWithMonitoring = File.ReadAllBytes(ManagedSolutionLocation);

                    ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest()
                    {
                        CustomizationFile = fileBytes,
                        ImportJobId       = Guid.NewGuid()
                    };

                    _serviceProxy.Execute(impSolReqWithMonitoring);
                    Console.WriteLine("Imported Solution with Monitoring from {0}", ManagedSolutionLocation);

                    ImportJob job = (ImportJob)_serviceProxy.Retrieve(ImportJob.EntityLogicalName, impSolReqWithMonitoring.ImportJobId, new ColumnSet(new System.String[] { "data", "solutionname" }));


                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.LoadXml(job.Data);

                    String ImportedSolutionName = doc.SelectSingleNode("//solutionManifest/UniqueName").InnerText;
                    String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value;

                    Console.WriteLine("Report from the ImportJob data");
                    Console.WriteLine("Solution Unique name: {0}", ImportedSolutionName);
                    Console.WriteLine("Solution Import Result: {0}", SolutionImportResult);
                    Console.WriteLine("");

                    // This code displays the results for Global Option sets installed as part of a solution.

                    System.Xml.XmlNodeList optionSets = doc.SelectNodes("//optionSets/optionSet");
                    foreach (System.Xml.XmlNode node in optionSets)
                    {
                        string OptionSetName = node.Attributes["LocalizedName"].Value;
                        string result        = node.FirstChild.Attributes["result"].Value;

                        if (result == "success")
                        {
                            Console.WriteLine("{0} result: {1}", OptionSetName, result);
                        }
                        else
                        {
                            string errorCode = node.FirstChild.Attributes["errorcode"].Value;
                            string errorText = node.FirstChild.Attributes["errortext"].Value;

                            Console.WriteLine("{0} result: {1} Code: {2} Description: {3}", OptionSetName, result, errorCode, errorText);
                        }
                    }

                    //</snippetWorkWithSolutions9>

                    //<snippetWorkWithSolutions10>
                    // Delete a solution

                    QueryExpression queryImportedSolution = new QueryExpression
                    {
                        EntityName = Solution.EntityLogicalName,
                        ColumnSet  = new ColumnSet(new string[] { "solutionid", "friendlyname" }),
                        Criteria   = new FilterExpression()
                    };


                    queryImportedSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, ImportedSolutionName);

                    Solution ImportedSolution = (Solution)_serviceProxy.RetrieveMultiple(queryImportedSolution).Entities[0];

                    _serviceProxy.Delete(Solution.EntityLogicalName, (Guid)ImportedSolution.SolutionId);

                    Console.WriteLine("Deleted the {0} solution.", ImportedSolution.FriendlyName);

                    //</snippetWorkWithSolutions10>



                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Ejemplo n.º 60
0
        private static System.Xml.XmlDocument GetReportingXml(IMMPxApplication PxApp, IMMPersistentXML ListItem, LabelXmlType XmlType)
        {
            if (PxApp == null)
            {
                throw new Exception("No Px Application found");
            }
            if (ListItem == null)
            {
                throw new Exception("No item given to generate notes for");
            }

            /*
             * Stack<ID8ListItem> items = new Stack<ID8ListItem>();
             * ((ID8List)ListItem).Reset();
             * items.Push((ID8ListItem)ListItem);
             *
             * int wlCount = 1;
             * while (items.Count > 0)
             * {
             *      var item = items.Pop();
             *      if (item is ID8TopLevel ||
             *              item is ID8WorkRequest ||
             *              item is ID8Design)
             *      {
             *              ((ID8List)item).Reset();
             *              for (ID8ListItem child = ((ID8List)item).Next(true);
             *                      child != null;
             *                      child = ((ID8List)item).Next(true))
             *                      items.Push(child);
             *      }
             *      else if (item is ID8WorkLocation)
             *      {
             *              ((ID8WorkLocation)item).ID = wlCount.ToString();
             *              wlCount++;
             *      }
             *      else
             *              continue;
             * }
             */
            switch (XmlType)
            {
            case LabelXmlType.DesignTree:
            {
                Miner.Interop.msxml2.IXMLDOMDocument xDoc = new Miner.Interop.msxml2.DOMDocument();
                ListItem.SaveToDOM(mmXMLFormat.mmXMLFDesign, xDoc);

                var newDoc = new System.Xml.XmlDocument();
                newDoc.LoadXml(xDoc.xml);
                return(newDoc);
            }

            default:
            case LabelXmlType.DesignerXml:
            {
                //Hidden packages
                int currentDesign = ((IMMPxApplicationEx)PxApp).CurrentNode.Id;
                return(new System.Xml.XmlDocument()
                    {
                        InnerXml = DesignerUtility.GetClassicDesignXml(currentDesign)
                    });
            }

            case LabelXmlType.PxXml:
            {
                //Hidden packages
                int          currentDesign = ((IMMPxApplicationEx)PxApp).CurrentNode.Id;
                IMMWMSDesign design        = DesignerUtility.GetWmsDesign(PxApp, currentDesign);
                if (design == null)
                {
                    throw new Exception("Unable to load design with id of " + currentDesign);
                }

                return(new System.Xml.XmlDocument()
                    {
                        InnerXml = DesignerUtility.GetClassicPxXml(design, PxApp)
                    });
            }

            case LabelXmlType.CostEngine:
            {
                //get the px config, load it, run it, return it
                string costEngineProgID = DesignerUtility.GetPxConfig(PxApp, "WMSCostEngine");
                if (string.IsNullOrEmpty(costEngineProgID))
                {
                    throw new Exception("Cost Engine Xml Source Defined, but no cost engine is defined");
                }
                Type costEngineType = Type.GetTypeFromProgID(costEngineProgID);
                if (costEngineType == null)
                {
                    throw new Exception("Unable to load type for specified cost engine: " + costEngineProgID);
                }

                var rawType = Activator.CreateInstance(costEngineType);
                if (rawType == null)
                {
                    throw new Exception("Unable to instantiate cost engine type " + costEngineType);
                }

                IMMWMSCostEngine costEngine = rawType as IMMWMSCostEngine;
                if (costEngine == null)
                {
                    throw new Exception("Configured cost engine " + costEngineProgID + " is not of type IMMWMSCostEngine");
                }

                if (!costEngine.Initialize(PxApp))
                {
                    throw new Exception("Failed to initialize cost engine");
                }

                return(new System.Xml.XmlDocument()
                    {
                        InnerXml = costEngine.Calculate(((IMMPxApplicationEx)PxApp).CurrentNode)
                    });
            }

            case LabelXmlType.Custom:
                throw new Exception("No custom xml reporting source defined");

                /*Or you can reference a custom cost / reporting engine
                 * CostingEngine.SimpleCostEngine SCE = new Telvent.Applications.Designer.CostingEngine.SimpleCostEngine();
                 * SCE.Initialize(PxApp);
                 * CalculatedXml = SCE.Calculate(xDoc.xml);
                 */
                break;
            }

            //Fall through
            return(null);
        }