Ejemplo n.º 1
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;
 }
        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;
        }
        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.º 4
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();
        }
        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.º 6
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.º 7
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 );
        }
        /// <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;
        }
        public static EmbeddedConfiguration GetConfigurationFromEmbeddedFile(string logicalConnectionName)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ITPCfSQL.Azure.CLR.Configuration.Connections.xml"))
            {
                doc.Load(s);
            }

            string query = "ConnectionList/Connection[LogicalName='" + logicalConnectionName + "']";

            //Microsoft.SqlServer.Server.SqlContext.Pipe.Send(query);

            System.Xml.XmlNode node = doc.SelectSingleNode(query);

            if (node == null)
                throw new ArgumentException("Cannot find \"" + logicalConnectionName + "\" logical connection. Are you sure you spelled it right?");

            try
            {
                return new EmbeddedConfiguration()
            {
                LogicalName = node.SelectSingleNode("LogicalName").InnerText,
                AccountName = node.SelectSingleNode("AccountName").InnerText,
                SharedKey = node.SelectSingleNode("SharedKey").InnerText,
                UseHTTPS = bool.Parse(node.SelectSingleNode("UseHTTPS").InnerText)
            };
            }
            catch (Exception exce)
            {
                throw new ArgumentException("There is an error in the configuration file. Some node is missing.", exce);
            }
        }
Ejemplo n.º 10
0
        public List<Container> ListContainers(
            string prefix = null,
            bool IncludeMetadata = false,
            int timeoutSeconds = 0,
            Guid? xmsclientrequestId = null)
        {
            List<Container> lContainers = new List<Container>();
            string strNextMarker = null;
            do
            {
                string sRet = Internal.InternalMethods.ListContainers(
                    AccountName, SharedKey, UseHTTPS,
                    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);
                }

                lContainers.AddRange(Container.ParseFromXMLEnumerationResults(this, doc));

                strNextMarker = Container.GetNextMarkerFromXMLEnumerationResults(doc);

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

            return lContainers;
        }
Ejemplo n.º 11
0
        public static void CreateGamesIni(string inputXML,string gamesIniPath)
        {
            //string filename = args[0];
                //Console.WriteLine(filename);
                System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
                xdoc.Load(inputXML);

                var di = new DirectoryInfo(gamesIniPath);
                var fi = new FileInfo(gamesIniPath + "\\games.ini");
                di.Attributes &= FileAttributes.Normal;

                if (File.Exists(fi.FullName))
                    fi.Attributes &= ~FileAttributes.ReadOnly;

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(gamesIniPath + "\\games.ini", true))
                {
                    file.WriteLine("# This file is only used for remapping specific games to other Emulators and/or Systems.");
                    file.WriteLine("# If you don't want your game to use the Default_Emulator, you would set the Emulator key here.");
                    file.WriteLine("# This file can also be used when you have Wheels with games from other Systems.");
                    file.WriteLine("# You would then use the System key to tell HyperLaunch what System to find the emulator settings.");
                    file.WriteLine("");

                }

                foreach (System.Xml.XmlNode node in xdoc.SelectNodes("menu/game"))
                {
                    string GameName = node.SelectSingleNode("@name").InnerText;
                    string sysName = node.SelectSingleNode("System").InnerText;
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(gamesIniPath + "\\games.ini", true))
                    {
                        file.WriteLine("[{0}]", GameName);
                        file.WriteLine(@"System={0}", sysName);
                    }
                }
        }
Ejemplo n.º 12
0
        public static void Init()
        {
            Version = new CVar("smod_version", "0.1");

            // load plugins

            Server.Print(License);
            Server.RegisterCommand("smod", smod);

            Verifier = new Verifier(Directory.GetCurrentDirectory(), Server.GameDirectory);

            try {
                var doc = new System.Xml.XmlDocument();
                doc.Load(Path.Combine(Server.ModDirectory, Path.Combine("cfg", "databases.xml")));
                try {
                    Database = DefaultDatabase.Load(Path.Combine(Server.ModDirectory, "SharpMod.Database.MySql.dll"));
                    Database.Load(doc);
                } catch (Exception e) {
                    Server.LogError("Database Interface failed to load, using default: {0}", e.Message);
                    Database = new DefaultDatabase();
                    Database.Load(doc);
                }
            } catch (Exception e) {
                Server.LogError("Failed to load cfg/databases.xml: {0}", e.Message);
            }

            Message.Init();
            MapCycle.Init();
        }
Ejemplo n.º 13
0
        private void reload_Click(object sender, EventArgs e)
        {
            String firstNum, lastNum;

            // Gets the first 4 and last 4 numbers from the Selectionbox, and saves them to a variable
            firstNum = resolutionSelect.Text.Substring(0, 4);
            lastNum = resolutionSelect.Text.Substring(Math.Max(0, resolutionSelect.Text.Length - 4));

            // Removes any spaces from the above strings.
            firstNum = firstNum.Replace(" ", "");
            lastNum = lastNum.Replace(" ", "");

            // Loads the Application Settings XML file
            System.Xml.XmlDocument appConfigXML = new System.Xml.XmlDocument();
            System.Xml.XmlDocument serConfigXML = new System.Xml.XmlDocument();
            appConfigXML.Load(Game._path + "\\Content\\ApplicationSettings.xml");
            serConfigXML.Load(Game._path + "\\Content\\ServiceSettings.xml");

            // Sets the XML attributes to the current values of the editor
            appConfigXML.SelectSingleNode("//ScreenTitle").InnerText = windowTitleBox.Text;
            appConfigXML.SelectSingleNode("//FullScreen").InnerText = isFullScreen.Text;
            appConfigXML.SelectSingleNode("//ScreenWidth").InnerText = Convert.ToString(firstNum);
            appConfigXML.SelectSingleNode("//ScreenHeight").InnerText = Convert.ToString(lastNum);

            // Saves the Application Settings XML file
            appConfigXML.Save(Game._path + "\\Content\\ApplicationSettings.xml");
            serConfigXML.Save(Game._path + "\\Content\\ServiceSettings.xml");

            MessageBox.Show("Reload Application for changes to take effect");
            System.Diagnostics.Process.Start(Game._path + @"\\Devoxelation.exe");
            Application.Exit();
        }
        public int coverfromxml(MemoryStream xmlStream)
        {
            int answer = 0;
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                xmlStream.Position = 0;
                doc.Load(xmlStream);
                System.Xml.XmlNode nderoot = doc.SelectSingleNode("/ComicInfo/Pages");
                if (nderoot != null)
                {
                    if (nderoot.ChildNodes.Count > 1)
                    { answer = Convert.ToInt16(nderoot.FirstChild.Attributes.GetNamedItem("Image").Value); }
                    answer = MultipleCovers(answer, nderoot);
                }
                else
                {
                    answer = -1;
                }

            }
            catch (Exception ex)
                {
                    Log.Instance.Write("XML Error! ", ex);
                    answer = -1;
                }
            return answer;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// ��ȡ�������
        /// </summary>
        /// <param name="SiteID"></param>
        /// <returns></returns>
        public static string GetSmsCount(string SiteID)
        {
            string UserName = "";
            string Password = "";

            string mToUrl = "";	    //�������õ�url
            string mRtv = "";		//���õķ����ַ���

            string strSMSConfigPath = System.Web.HttpContext.Current.Server.MapPath("/Admin/Config/" + SiteID + "/SiteConfig.config");
            if (System.IO.File.Exists(strSMSConfigPath))
            {
                System.Xml.XmlDocument XDTop = new System.Xml.XmlDocument();
                XDTop.Load(strSMSConfigPath);

                UserName = XDTop.SelectSingleNode("DB/SMSConfig/SMSUserName").InnerText;
                Password = XDTop.SelectSingleNode("DB/SMSConfig/SMSPassword").InnerText;
            }

            // �û�����
            mToUrl = "http://www.139000.com/send/getfee.asp?name=" + UserName + "&pwd=" + Password;

            System.Net.HttpWebResponse rs = (System.Net.HttpWebResponse)System.Net.HttpWebRequest.Create(mToUrl).GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(rs.GetResponseStream(), System.Text.Encoding.Default);
            mRtv = sr.ReadToEnd();

            string[] arr = mRtv.Split(new char[] { '=', '&' });

            return arr[1];
        }
Ejemplo n.º 16
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.º 17
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.º 18
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;
                }
            }
        }
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
                };

            }
        }
Ejemplo n.º 20
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.º 21
0
        /// <summary>
        /// Setup the game properties
        /// </summary>
        /// <param name="contentManager">the XNA content manager to be used</param>
        /// <param name="graphicDeviceManager">the XNA graphic manager to be used</param>
        public GameProperties(Microsoft.Xna.Framework.Content.ContentManager contentManager, Microsoft.Xna.Framework.GraphicsDeviceManager graphicDeviceManager, Microsoft.Xna.Framework.GameWindow window)
        {
            // load game properties
            System.Xml.XmlDocument config = new System.Xml.XmlDocument();
            config.Load(@"Content/config.xml");

            // try resolution
            try
            {
                graphicDeviceManager.PreferredBackBufferWidth = Convert.ToInt32(config.GetElementsByTagName("resolutionX")[0].InnerText);
                graphicDeviceManager.PreferredBackBufferHeight = Convert.ToInt32(config.GetElementsByTagName("resolutionY")[0].InnerText);
                Screen screen = Screen.PrimaryScreen;
                window.Position = new Microsoft.Xna.Framework.Point(screen.Bounds.Width / 2 - graphicDeviceManager.PreferredBackBufferWidth / 2, screen.Bounds.Height / 2 - graphicDeviceManager.PreferredBackBufferHeight / 2);
            }
            catch (Exception)
            {
                graphicDeviceManager.PreferredBackBufferWidth = 1280;
                graphicDeviceManager.PreferredBackBufferHeight = 720;
            }

            // try fullscreen
            try
            {
                int fullscreen = Convert.ToInt32(config.GetElementsByTagName("fullscreen")[0].InnerText);
                if (fullscreen == 1)
                {
                    Screen screen = Screen.PrimaryScreen;
                    window.IsBorderless = true;
                    window.Position = new Microsoft.Xna.Framework.Point(screen.Bounds.X, screen.Bounds.Y);
                    graphicDeviceManager.PreferredBackBufferWidth = screen.Bounds.Width;
                    graphicDeviceManager.PreferredBackBufferHeight = screen.Bounds.Height;
                    this.isFullscreen = true;
                }
                else
                {
                    this.isFullscreen = false;
                }
            }
            catch (Exception) { }

            graphicDeviceManager.ApplyChanges();

            // try language settings
            try
            {
                this.SelectedLanguage = config.GetElementsByTagName("language")[0].InnerText;
            }
            catch(Exception){ }

            this.currentGameState = GameState.LoadMenu;
            this.input = new InputHandler();

            this.contentManager = new Helper.ContentManager(contentManager);
            this.spriteBatch = new Microsoft.Xna.Framework.Graphics.SpriteBatch(graphicDeviceManager.GraphicsDevice);
            this.graphicDeviceManager = graphicDeviceManager;
            this.gameWindow = window;

            System.IO.BinaryReader Reader = new System.IO.BinaryReader(System.IO.File.Open(@"Content\Shader\main_shader.mgfxo", System.IO.FileMode.Open));
            this.baseShader = new Microsoft.Xna.Framework.Graphics.Effect(this.graphicDeviceManager.GraphicsDevice, Reader.ReadBytes((int)Reader.BaseStream.Length));
        }
Ejemplo n.º 22
0
        private static void SetNode(string cpath)
        {   
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(cpath);
            Console.WriteLine("Adding to machine.config path: {0}", cpath);

            foreach (DataProvider dp in dataproviders)
            {
                System.Xml.XmlNode node = doc.SelectSingleNode("configuration/system.data/DbProviderFactories/add[@invariant=\"" + dp.invariant + "\"]");
                if (node == null)
                {
                    System.Xml.XmlNode root = doc.SelectSingleNode("configuration/system.data/DbProviderFactories");
                    node = doc.CreateElement("add");
                    System.Xml.XmlAttribute at = doc.CreateAttribute("name");
                    node.Attributes.Append(at);
                    at = doc.CreateAttribute("invariant");
                    node.Attributes.Append(at);
                    at = doc.CreateAttribute("description");
                    node.Attributes.Append(at);
                    at = doc.CreateAttribute("type");
                    node.Attributes.Append(at);
                    root.AppendChild(node);
                }
                node.Attributes["name"].Value = dp.name;
                node.Attributes["invariant"].Value = dp.invariant;
                node.Attributes["description"].Value = dp.description;
                node.Attributes["type"].Value = dp.type;
                Console.WriteLine("Added Data Provider node in machine.config.");
            }            

            doc.Save(cpath);
            Console.WriteLine("machine.config saved: {0}", cpath);
        }
Ejemplo n.º 23
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;
        }
Ejemplo n.º 24
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());
 }
Ejemplo n.º 25
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.º 26
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." );
        }
        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;
        }
        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.º 29
0
        public static string GetSetting(string path, string key)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(path);

            System.Xml.XmlNode node = doc.SelectSingleNode("settings/" + key);
            return node.InnerText;
        }
Ejemplo n.º 30
0
 public static int GetSessionTimeOutFromWebConfig()
 {
     System.Xml.XmlDocument x = new System.Xml.XmlDocument();
     x.Load(AppDomain.CurrentDomain.BaseDirectory + "web.config");
     System.Xml.XmlNode node = x.SelectSingleNode("/configuration/system.web/authentication/forms");
     int time_out = int.Parse(node.Attributes["timeout"].Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
     return time_out;
 }
Ejemplo n.º 31
0
        public static void DoWork()
        {
            try {
                FileInfo     t            = new FileInfo(Path.Combine(BackupFotos.outputPath, "missing.txt"));
                StreamWriter missingFiles = t.CreateText();
                missingFiles.Write("----[ " + DateTime.Now.ToString() + " ] ----" + Environment.NewLine);
                missingFiles.Flush();

                System.IO.FileStream   xml       = new System.IO.FileStream(xmlFile, FileMode.Open);
                ArrayList              galleries = new ArrayList();
                Hashtable              pics      = new Hashtable();
                System.Xml.XmlDocument doc       = new System.Xml.XmlDocument();
                MainForm.Instance.setStatus("Loading XML");
                doc.Load(xml);

                System.Xml.XmlNode picsContainer    = doc.GetElementsByTagName("pics")[0];
                System.Xml.XmlNode galleryContainer = doc.GetElementsByTagName("galleries")[0];
                if (picsContainer == null || galleryContainer == null)
                {
                    // throw exception
                }
                MainForm.Instance.setStatus("Starting Parsing XML");
                for (int x = 0; x < galleryContainer.ChildNodes.Count; x++)
                {
                    Gallery gallery = new Gallery(galleryContainer.ChildNodes[x]);
                    galleries.Add(gallery);
                }
                MainForm.Instance.setStatus("Done Fetching Galls");
                for (int x = 0; x < picsContainer.ChildNodes.Count; x++)
                {
                    Picture pic = new Picture(picsContainer.ChildNodes[x]);
                    pics.Add(pic.id, pic);
                }
                MainForm.Instance.setStatus("Done Fetching Pics");
                try {
                    Directory.CreateDirectory(BackupFotos.outputPath);
                }
                catch (System.IO.IOException ex) {
                    // Don't care really, its likely we can't create the directory we are using anyways.
                }
                foreach (Gallery gal in galleries)
                {
                    try {
                        string galname = gal.Name;
                        foreach (char invalidChar in Path.GetInvalidPathChars())
                        {
                            galname.Replace(invalidChar, '_');
                        }
                        galname.Replace(':', '_');
                        galname = System.Text.RegularExpressions.Regex.Replace(galname, "[^A-Za-z0-9_\\-' \\.\\@]+", "_");
                        string path = Path.Combine(BackupFotos.outputPath, galname);


                        MainForm.Instance.setStatus("Now Writing " + gal.Name);
                        Directory.CreateDirectory(path);
                        int count = 0;
                        foreach (int id in gal.pictures)
                        {
                            MainForm.Instance.setProgress(count, gal.pictures.Count);
                            Picture p        = (Picture)pics[id];
                            string  filename = p.getFilename(BackupFotos.prefixAmount);
                            MainForm.Instance.setStatus("Now Writing " + gal.Name + ": " + filename);
                            System.Drawing.Image i = p.getImage();
                            if (i == null)
                            {
                                missingFiles.Write(gal.Name + " - Missing File - " + p.id + " - " + p.url.ToString() + Environment.NewLine);
                                missingFiles.Flush();
                                continue;
                            }
                            i.Save(path + Path.DirectorySeparatorChar + filename);
                            p.cleanImage();
                            count++;
                        }
                        MainForm.Instance.setStatus("Now Writing " + gal.Name + " - Done");
                        MainForm.Instance.hideProgress();
                    }
                    catch (System.Threading.ThreadAbortException ex) {
                    }
                    catch (System.Exception e) {
                        /* FIXME: this needs to be non c# specific */
                        System.Windows.Forms.MessageBox.Show(e.ToString());
                    }
                }
                MainForm.Instance.setStatus("Done all galleries");
                MainForm.Instance.done();
                xml.Close();
                missingFiles.Close();
            }
            catch (System.Threading.ThreadAbortException ex) {
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 加载所有的tag
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public SqlTagProvider Load(Stream stream, string filename = null)
        {
            var doc = new System.Xml.XmlDocument();

            doc.Load(stream);
            var @namespaces = doc["namespace"];

            if (@namespaces == null)
            {
                return(this);
            }

            var idele       = namespaces.Attributes.GetNamedItem("id");
            var indentedele = namespaces.Attributes.GetNamedItem("indented");
            var id          = idele == null ? "" : idele.Value;
            var indented    = indentedele == null ? true : indentedele.Value.AsBool();

            var next = @namespaces.FirstChild;

            while (next != null)
            {
                if (next.NodeType == System.Xml.XmlNodeType.Comment)
                {
                    next = next.NextSibling;
                    continue;
                }

                var name      = next.Name;
                var nextIdele = next.Attributes.GetNamedItem("id");
                if (nextIdele == null)
                {
                    throw new Never.Exceptions.KeyNotExistedException("can not find the id atrribute in this {0} file", filename);
                }

                var nextId = nextIdele.Value;
                if (nextId.IsNullOrEmpty())
                {
                    throw new Never.Exceptions.DataFormatException("can not find the id atrribute in this {0} file", filename);
                }

                if (this.sortedSet.ContainsKey(nextId))
                {
                    throw new DataFormatException("the {0} is duplicated", nextId);
                }

                var sqlTag = new SqlTag();
                sqlTag.Id                  = nextId;
                sqlTag.NameSpace           = id;
                sqlTag.IndentedOnNameSpace = indented;
                if (!LoadCommandName(next, sqlTag))
                {
                    next = next.NextSibling;
                    break;
                }
                sqlTag.Node            = next;
                this.sortedSet[nextId] = sqlTag;
                next = next.NextSibling;
            }

            return(this);
        }
Ejemplo n.º 33
0
        public static void ExecOneRemote(SourceCode.Job cfgj, string[] ExecArgs, bool verbose, bool verbosereplication)
        {
            if (verbose)
            {
                Console.WriteLine("[{0}]        [Remote: {2}]", System.DateTime.Now.ToString(), System.DateTime.Now.Millisecond, cfgj.NarrativeName);
            }

            string logname = Surrogate.SafeTextPath(cfgj.NarrativeName) + "_" + Guid.NewGuid().ToString() + ".j" + sjid + "_log.txt";

            //System.Threading.Thread.Sleep(8000);

            /*if (cfgj.IOSettings.DFS_IOs == null || cfgj.IOSettings.DFS_IOs.Length == 0)
             * {
             *  Console.Error.WriteLine("One or more IOSettings/DFS_IO needed in configuration for 'remote'");
             *  return;
             * }*/

            // Could provide BlockID here, which is just the n-th DFS_IO entry.
            //cfgj.Remote

            dfs dc = LoadDfsConfig();

            string[] slaves = dc.Slaves.SlaveList.Split(',', ';');
            if (dc.Slaves.SlaveList.Length == 0 || slaves.Length < 1)
            {
                throw new Exception("SlaveList expected in " + dfs.DFSXMLNAME);
            }
            if (dc.Replication > 1)
            {
                string[] slavesbefore = slaves;
                slaves = ExcludeUnhealthySlaveMachines(slaves, true).ToArray();
                if (slavesbefore.Length - slaves.Length >= dc.Replication)
                {
                    throw new Exception("Not enough healthy machines to run job (hit replication count)");
                }
            }

            if (cfgj.IOSettings.DFS_IO_Multis != null)
            {
                cfgj.ExpandDFSIOMultis(slaves.Length, MySpace.DataMining.DistributedObjects.MemoryUtils.NumberOfProcessors);
            }

            Dictionary <string, int> slaveIDs = new Dictionary <string, int>();

            for (int si = 0; si < slaves.Length; si++)
            {
                slaveIDs.Add(slaves[si].ToUpper(), si);
            }

            bool aborting = false;

            try
            {
                List <RemoteBlockInfo> blocks = new List <RemoteBlockInfo>(cfgj.IOSettings.DFS_IOs.Length);
                if (verbose)
                {
                    Console.WriteLine("{0} processes on {1} machines:", cfgj.IOSettings.DFS_IOs.Length, slaves.Length);
                }

                List <string> outputdfsdirs = new List <string>(slaves.Length);
                {
                    for (int i = 0; i < slaves.Length; i++)
                    {
                        try
                        {
                            outputdfsdirs.Add(NetworkPathForHost(slaves[i]));
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine("    {0}", e.Message);
                        }
                    }
                }

                string slaveconfigxml = "";
                {
                    System.Xml.XmlDocument pdoc = new System.Xml.XmlDocument();
                    {
                        System.IO.MemoryStream ms = new System.IO.MemoryStream();
                        System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(dfs));
                        xs.Serialize(ms, dc);
                        ms.Seek(0, System.IO.SeekOrigin.Begin);
                        pdoc.Load(ms);
                    }
                    string xml = pdoc.DocumentElement.SelectSingleNode("./slave").OuterXml;
                    //System.Threading.Thread.Sleep(8000);
                    slaveconfigxml = xml;
                }
                {
                    // Temporary:
                    for (int si = 0; si < slaves.Length; si++)
                    {
                        System.Threading.Mutex m = new System.Threading.Mutex(false, "AEL_SC_" + slaves[si]);
                        try
                        {
                            m.WaitOne();
                        }
                        catch (System.Threading.AbandonedMutexException)
                        {
                        }
                        try
                        {
                            System.IO.File.WriteAllText(NetworkPathForHost(slaves[si]) + @"\slaveconfig.j" + sjid + ".xml", slaveconfigxml);
                        }
                        catch
                        {
                        }
                        finally
                        {
                            m.ReleaseMutex();
                            m.Close();
                        }
                    }
                }

                int        nextslave           = (new Random(DateTime.Now.Millisecond / 2 + System.Diagnostics.Process.GetCurrentProcess().Id / 2)).Next() % slaves.Length;
                int        hosttypes           = 0;
                List <int> outputrecordlengths = new List <int>();
                List <int> inputrecordlengths  = new List <int>();
                for (int BlockID = 0; BlockID < cfgj.IOSettings.DFS_IOs.Length; BlockID++)
                {
                    int             slaveHostID = 0;
                    RemoteBlockInfo bi          = new RemoteBlockInfo();
                    bi.sampledist = dc.DataNodeBaseSize / dc.DataNodeSamples;
                    bi.BlockID    = BlockID;
                    bi.blockcount = cfgj.IOSettings.DFS_IOs.Length;
                    if (string.IsNullOrEmpty(cfgj.IOSettings.DFS_IOs[BlockID].Host))
                    {
                        if (0 != hosttypes && 1 != hosttypes)
                        {
                            throw new Exception("DFS_IO/Host tag must be specified for all or none");
                        }
                        hosttypes       = 1;
                        bi.SlaveHost    = slaves[nextslave];
                        slaveHostID     = nextslave;
                        bi.explicithost = false;
                    }
                    else
                    {
                        if (0 != hosttypes && 2 != hosttypes)
                        {
                            throw new Exception("DFS_IO/Host tag must be specified for all or none");
                        }
                        hosttypes       = 2;
                        bi.SlaveHost    = cfgj.IOSettings.DFS_IOs[BlockID].Host;
                        slaveHostID     = slaveIDs[bi.SlaveHost.ToUpper()];
                        bi.explicithost = true;
                    }
                    bi.ExecArgs = ExecArgs;
                    if (++nextslave >= slaves.Length)
                    {
                        nextslave = 0;
                    }

                    bi.logname            = logname;
                    bi.outputdfsdirs      = outputdfsdirs;
                    bi.slaves             = slaves;
                    bi.baseoutputfilesize = dc.DataNodeBaseSize;
                    bi.cfgj      = cfgj;
                    bi.DFSWriter = cfgj.IOSettings.DFS_IOs[BlockID].DFSWriter.Trim();
                    bi.Meta      = cfgj.IOSettings.DFS_IOs[BlockID].Meta;

                    List <string> dfswriters = new List <string>();
                    if (bi.DFSWriter.Length > 0)
                    {
                        string[] writers = bi.DFSWriter.Split(';');
                        for (int wi = 0; wi < writers.Length; wi++)
                        {
                            string thiswriter = writers[wi].Trim();
                            if (thiswriter.Length == 0)
                            {
                                continue;
                            }
                            int ic     = thiswriter.IndexOf('@');
                            int reclen = -1;
                            if (-1 != ic)
                            {
                                try
                                {
                                    reclen     = Surrogate.GetRecordSize(thiswriter.Substring(ic + 1));
                                    thiswriter = thiswriter.Substring(0, ic);
                                }
                                catch (FormatException e)
                                {
                                    Console.Error.WriteLine("Error: remote output record length error: {0} ({1})", thiswriter, e.Message);
                                    SetFailure();
                                    return;
                                }
                                catch (OverflowException e)
                                {
                                    Console.Error.WriteLine("Error: remote output record length error: {0} ({1})", thiswriter, e.Message);
                                    SetFailure();
                                    return;
                                }
                            }
                            string outfn = thiswriter;
                            if (outfn.StartsWith(@"dfs://", StringComparison.OrdinalIgnoreCase))
                            {
                                outfn = outfn.Substring(6);
                            }
                            string reason = "";
                            if (dfs.IsBadFilename(outfn, out reason))
                            {
                                Console.Error.WriteLine("Invalid output file: {0}", reason);
                                return;
                            }
                            if (null != DfsFindAny(dc, outfn))
                            {
                                Console.Error.WriteLine("Error:  output file already exists in DFS: {0}", outfn);
                                return;
                            }
                            dfswriters.Add(thiswriter);
                            outputrecordlengths.Add(reclen);
                        }
                    }
                    else
                    {
                        dfswriters.Add("");
                        outputrecordlengths.Add(-1);
                    }
                    bi.DFSWriters              = dfswriters;
                    bi.verbose                 = verbose;
                    bi.rem                     = new MySpace.DataMining.DistributedObjects5.Remote(cfgj.NarrativeName + "_remote");
                    bi.rem.CookRetries         = dc.slave.CookRetries;
                    bi.rem.CookTimeout         = dc.slave.CookTimeout;
                    bi.rem.DfsSampleDistance   = bi.sampledist;
                    bi.rem.CompressFileOutput  = dc.slave.CompressDfsChunks;
                    bi.rem.LocalCompile        = true;
                    bi.rem.OutputStartingPoint = slaveHostID;
                    bi.rem.CompilerOptions     = cfgj.IOSettings.CompilerOptions;
                    bi.rem.CompilerVersion     = cfgj.IOSettings.CompilerVersion;
                    if (cfgj.AssemblyReferencesCount > 0)
                    {
                        cfgj.AddAssemblyReferences(bi.rem.CompilerAssemblyReferences, Surrogate.NetworkPathForHost(dc.Slaves.GetFirstSlave()));
                    }
                    if (cfgj.OpenCVExtension != null)
                    {
                        bi.rem.AddOpenCVExtension();
                    }
                    if (cfgj.MemCache != null)
                    {
                        bi.rem.AddMemCacheExtension();
                    }
                    if (cfgj.Unsafe != null)
                    {
                        bi.rem.AddUnsafe();
                    }
                    {
                        List <dfs.DfsFile.FileNode> nodes = new List <dfs.DfsFile.FileNode>();
                        List <string>  mapfileswithnodes  = null;
                        List <int>     nodesoffsets       = null;
                        IList <string> mapfiles           = SplitInputPaths(dc, cfgj.IOSettings.DFS_IOs[BlockID].DFSReader);
                        if (mapfiles.Count > 0)
                        {
                            mapfileswithnodes = new List <string>(mapfiles.Count);
                            nodesoffsets      = new List <int>(mapfiles.Count);
                        }
                        for (int i = 0; i < mapfiles.Count; i++)
                        {
                            string dp       = mapfiles[i].Trim();
                            int    inreclen = -1;
                            if (0 != dp.Length) // Allow empty entry where input isn't wanted.
                            {
                                if (dp.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase))
                                {
                                    dp = dp.Substring(6);
                                }

                                {
                                    int ic = dp.IndexOf('@');
                                    if (-1 != ic)
                                    {
                                        try
                                        {
                                            inreclen = Surrogate.GetRecordSize(dp.Substring(ic + 1));
                                            dp       = dp.Substring(0, ic);
                                        }
                                        catch (FormatException e)
                                        {
                                            Console.Error.WriteLine("Error: remote input record length error: {0} ({1})", dp, e.Message);
                                            SetFailure();
                                            return;
                                        }
                                        catch (OverflowException e)
                                        {
                                            Console.Error.WriteLine("Error: remote input record length error: {0} ({1})", dp, e.Message);
                                            SetFailure();
                                            return;
                                        }
                                    }
                                }
                                dfs.DfsFile df;
                                if (inreclen > 0 || inreclen == -2)
                                {
                                    df = DfsFind(dc, dp, DfsFileTypes.BINARY_RECT);
                                    if (null != df && inreclen != df.RecordLength)
                                    {
                                        Console.Error.WriteLine("Error: remote input file does not have expected record length of {0}: {1}@{2}", inreclen, dp, df.RecordLength);
                                        SetFailure();
                                        return;
                                    }
                                }
                                else
                                {
                                    df = DfsFind(dc, dp);
                                }
                                if (null == df)
                                {
                                    //throw new Exception("Remote input file not found in DFS: " + dp);
                                    Console.Error.WriteLine("Remote input file not found in DFS: {0}", dp);
                                    return;
                                }
                                if (df.Nodes.Count > 0)
                                {
                                    mapfileswithnodes.Add(dp);
                                    nodesoffsets.Add(nodes.Count);
                                    inputrecordlengths.Add(inreclen);
                                    nodes.AddRange(df.Nodes);
                                }
                            }
                        }
                        bi.dfsinputpaths = new List <string>(nodes.Count);
                        //MapNodesToNetworkPaths(nodes, bi.dfsinputpaths);
                        dfs.MapNodesToNetworkStarPaths(nodes, bi.dfsinputpaths);
                        bi.dfsinputfilenames    = mapfileswithnodes;
                        bi.dfsinputnodesoffsets = nodesoffsets;
                    }

                    blocks.Add(bi);

                    bi.thread      = new System.Threading.Thread(new System.Threading.ThreadStart(bi.threadproc));
                    bi.thread.Name = "RemoteJobBlock" + bi.BlockID;
                }
                MySpace.DataMining.DistributedObjects.StaticGlobals.DSpace_InputRecordLength  = inputrecordlengths.Count > 0 ? inputrecordlengths[0] : -1;
                MySpace.DataMining.DistributedObjects.StaticGlobals.DSpace_OutputRecordLength = outputrecordlengths.Count > 0 ? outputrecordlengths[0] : -1;
                // Need to start threads separately due to StaticGlobals being updated.
                for (int BlockID = 0; BlockID < cfgj.IOSettings.DFS_IOs.Length; BlockID++)
                {
                    RemoteBlockInfo bi = blocks[BlockID];
                    bi.rem.InputRecordLength   = MySpace.DataMining.DistributedObjects.StaticGlobals.DSpace_InputRecordLength;
                    bi.rem.InputRecordLengths  = inputrecordlengths;
                    bi.rem.OutputRecordLength  = MySpace.DataMining.DistributedObjects.StaticGlobals.DSpace_OutputRecordLength;
                    bi.rem.OutputRecordLengths = outputrecordlengths;
                    AELight_StartTraceThread(bi.thread);
                }

                for (int BlockID = 0; BlockID < blocks.Count; BlockID++)
                {
                    AELight_JoinTraceThread(blocks[BlockID].thread);
                    blocks[BlockID].rem.Close();

                    if (blocks[BlockID].blockfail)
                    {
                        Console.Error.WriteLine("BlockID {0} on host '{1}' did not complete successfully", BlockID, (blocks[BlockID].SlaveHost != null) ? blocks[BlockID].SlaveHost : "<null>");
                        continue;
                    }
                }

                List <string> dfsnames            = new List <string>();
                List <string> dfsnamesreplicating = new List <string>();
                // Reload DFS config to make sure changes since starting get rolled in, and make sure the output file wasn't created in that time...
                using (LockDfsMutex()) // Needed: change between load & save should be atomic.
                {
                    dc = LoadDfsConfig();
                    for (int BlockID = 0; BlockID < blocks.Count; BlockID++)
                    {
                        if (blocks[BlockID].blockfail)
                        {
                            continue;
                        }
                        {
                            bool anyoutput          = false;
                            bool nonemptyoutputpath = false;
                            for (int oi = 0; oi < blocks[BlockID].DFSWriters.Count; oi++)
                            {
                                string dfswriter = blocks[BlockID].DFSWriters[oi];

                                if (string.IsNullOrEmpty(dfswriter))
                                {
                                    if (blocks[BlockID].outputdfsnodeses[oi].Count > 0)
                                    {
                                        Console.Error.WriteLine("Output data detected with no DFSWriter specified");
                                    }
                                }
                                else
                                {
                                    {
                                        if (null != DfsFind(dc, dfswriter))
                                        {
                                            Console.Error.WriteLine("Error:  output file was created during job: {0}", dfswriter);
                                            continue;
                                        }

                                        string dfspath = dfswriter;

                                        {
                                            nonemptyoutputpath = true;
                                            dfs.DfsFile df = new dfs.DfsFile();
                                            if (blocks[BlockID].rem.OutputRecordLengths[oi] > 0)
                                            {
                                                df.XFileType = DfsFileTypes.BINARY_RECT + "@" + blocks[BlockID].rem.OutputRecordLengths[oi].ToString();
                                            }
                                            else if (blocks[BlockID].rem.OutputRecordLengths[oi] == -2)
                                            {
                                                df.XFileType = DfsFileTypes.BINARY_RECT + "@?";
                                            }
                                            df.Nodes = new List <dfs.DfsFile.FileNode>();
                                            df.Size  = -1; // Preset
                                            if (dfspath.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase))
                                            {
                                                dfspath = dfspath.Substring(6);
                                            }
                                            string dfspathreplicating = ".$" + dfspath + ".$replicating-" + Guid.NewGuid().ToString();
                                            if (null != dc.FindAny(dfspathreplicating))
                                            {
                                                Console.Error.WriteLine("Error: file exists: file put into DFS from another location during job: " + dfspathreplicating);
                                                SetFailure();
                                                return;
                                            }
                                            dfsnames.Add(dfspath);
                                            dfsnamesreplicating.Add(dfspathreplicating);
                                            df.Name = dfspathreplicating;
                                            bool anybad    = false;
                                            long totalsize = 0;
                                            {
                                                int i = BlockID;
                                                for (int j = 0; j < blocks[i].outputdfsnodeses[oi].Count; j++)
                                                {
                                                    dfs.DfsFile.FileNode fn = new dfs.DfsFile.FileNode();
                                                    fn.Host = blocks[i].slaves[(blocks[i].rem.OutputStartingPoint + j) % blocks[i].slaves.Count];
                                                    fn.Name = blocks[i].outputdfsnodeses[oi][j];
                                                    df.Nodes.Add(fn);
                                                    fn.Length   = -1; // Preset
                                                    fn.Position = -1; // Preset
                                                    if (anybad)
                                                    {
                                                        continue;
                                                    }
                                                    fn.Length   = blocks[i].outputsizeses[oi][j];
                                                    fn.Position = totalsize; // Position must be set before totalsize updated!
                                                    if (blocks[i].outputdfsnodeses[oi].Count != blocks[i].outputsizeses[oi].Count)
                                                    {
                                                        anybad = true;
                                                        continue;
                                                    }
                                                    totalsize += blocks[i].outputsizeses[oi][j];
                                                }
                                            }
                                            if (!anybad)
                                            {
                                                df.Size = totalsize;
                                            }
                                            if (totalsize != 0)
                                            {
                                                anyoutput = true;
                                            }
                                            // Always add the file to DFS, even if blank!
                                            dc.Files.Add(df);
                                        }
                                    }
                                }
                            }
                            if (!anyoutput && verbose && nonemptyoutputpath)
                            {
                                Console.Write(" (no DFS output) ");
                                ConsoleFlush();
                            }
                        }
                    }

                    UpdateDfsXml(dc);
                }

                ReplicationPhase(verbosereplication, blocks.Count, slaves, dfsnamesreplicating);

                using (LockDfsMutex())    // Needed: change between load & save should be atomic.
                {
                    dc = LoadDfsConfig(); // Reload in case of change or user modifications.
                    for (int nfile = 0; nfile < dfsnames.Count; nfile++)
                    {
                        string dfspath            = dfsnames[nfile];
                        string dfspathreplicating = dfsnamesreplicating[nfile];
                        {
                            dfs.DfsFile dfu = dc.FindAny(dfspathreplicating);
                            if (null != dfu)
                            {
                                if (null != DfsFindAny(dc, dfspath))
                                {
                                    Console.Error.WriteLine("Error: file exists: file put into DFS from another location during job");
                                    SetFailure();
                                    continue;
                                }
                                dfu.Name = dfspath;
                            }
                        }
                    }
                    UpdateDfsXml(dc);
                }

                if (verbose)
                {
                    Console.WriteLine(); // Line after output chars.
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                aborting = true;
            }
            finally
            {
                {
                    for (int si = 0; si < slaves.Length; si++)
                    {
                        System.Threading.Mutex m = new System.Threading.Mutex(false, "AEL_SC_" + slaves[si]);
                        try
                        {
                            m.WaitOne();
                        }
                        catch (System.Threading.AbandonedMutexException)
                        {
                        }
                        try
                        {
                            System.IO.File.Delete(NetworkPathForHost(slaves[si]) + @"\slaveconfig.j" + sjid + ".xml");
                        }
                        catch
                        {
                        }
                        finally
                        {
                            m.ReleaseMutex();
                            m.Close();
                        }
                    }
                }

                if (!aborting)
                {
                    CheckUserLogs(slaves, logname);
                }
            }

            if (verbose)
            {
                Console.WriteLine();
                Console.WriteLine("[{0}]        Done", System.DateTime.Now.ToString(), System.DateTime.Now.Millisecond);
                for (int i = 0; i < cfgj.IOSettings.DFS_IOs.Length; i++)
                {
                    Console.WriteLine("Output:   {0}", cfgj.IOSettings.DFS_IOs[i].DFSWriter);
                }
            }
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            //设定服务器IP地址
            IPAddress ip           = IPAddress.Parse("127.0.0.1");
            Socket    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 9002)); //配置服务器IP与端口
                Console.WriteLine("连接服务器成功");
            }
            catch
            {
                Console.WriteLine("连接服务器失败,请按回车键退出!");
                return;
            }



            byte[] socket_Baotou = new byte[4];//包头码
            socket_Baotou[0] = 0xE2;
            socket_Baotou[1] = 0x5C;
            socket_Baotou[2] = 0x4B;
            socket_Baotou[3] = 0x89;

            //计算文件长度
            //static int GetFileSize(string sFullName)
            //{
            //    long lSize = 0;
            //    if (File.Exists(sFullName))
            //        lSize = new FileInfo(sFullName).Length;

            //    return (int)lSize;
            //}

            //long xml_size = GetFileSize(@"C:\Users\wangyuanping\Desktop\C#\my\XMLInfoGather.xml");
            //计算文件大小
            xml_file xml_path = new xml_file();//XMLInfoGather  XMLInfoWLJKRet   XMLControlCommand  XMLControlFeedback

            string path = xml_path.XMLControlCommand();

            //string path = @"C:\Users\wangyuanping\Desktop\XMLInfoGather.xml";


            Console.WriteLine(xml_path);



            // @"C:\Users\wangyuanping\Desktop\XMLInfoGather.xml";//文件大小
            //int xml_size = GetFileSize(path);
            FileInfo fi   = new FileInfo(path);
            long     size = fi.Length;

            //int xml_size = (int)size;


            System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); //新建对象
            doc.Load(path);                                            //XML文件路径
            string content = doc.InnerXml;

            Console.WriteLine(content.Length);
            int xml_size = System.Text.Encoding.Default.GetBytes(content.ToCharArray()).Length;

            //Console.WriteLine(content);//把xml文件


            Console.WriteLine("xml_size 字符串长度为{0}字节", xml_size);
Ejemplo n.º 35
0
        /// <summary>
        /// 获得配置文件
        /// </summary>
        /// <returns></returns>
        public static int GetSetting(out string err)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            try
            {
                doc.Load(System.Windows.Forms.Application.StartupPath + @"\" + "url.xml");
            }
            catch (Exception ex)
            {
                err = ("装载url失败!\n" + ex.Message);
                return(-1);
            }
            System.Xml.XmlNode node;
            #region 改成读一个地址列表,这样可以实现双机效果  {A5B6BD9E-68A1-45f5-BFE2-7EF0604AAAED}
            bool isUseUrlList = false;
            try
            {
                //校验用的node
                System.Xml.XmlNode nodeForCheck;
                nodeForCheck = doc.SelectSingleNode("//root/dir");
                if (nodeForCheck == null)
                {
                    isUseUrlList = false;
                }
                else
                {
                    isUseUrlList = true;
                }
            }
            catch (Exception ex)
            {
                err          = ex.Message;
                isUseUrlList = false;
            }
            #endregion
            if (isUseUrlList == false)
            {
                #region 原有读单一路径的代码,为了兼容保留
                node = doc.SelectSingleNode("//dir");

                if (node == null)
                {
                    err = ("url中找dir结点出错!");
                    return(-1);
                }

                SystemPath = node.InnerText;

                string serverSettingFileName = "Profile.xml"; //服务器文件名

                try
                {
                    doc.Load(SystemPath + serverSettingFileName);
                }
                catch (Exception ex)
                {
                    err = ("装载Profile.xml失败!\n" + ex.Message);
                }
                #endregion
                #region 改成读一个地址列表,这样可以实现双机效果 {A5B6BD9E-68A1-45f5-BFE2-7EF0604AAAED}
            }
            else
            {
                System.Xml.XmlNodeList xnl = doc.SelectNodes("//root/dir");
                if (xnl == null || xnl.Count == 0)
                {
                    err = ("url中找dir结点出错!");
                    return(-1);
                }

                int xnIdx = 0;
                foreach (System.Xml.XmlNode xn in xnl)
                {
                    SystemPath = xn.InnerText;

                    string serverSettingFileName = "HisProfile.xml"; //服务器文件名

                    try
                    {
                        doc.Load(SystemPath + serverSettingFileName);
                        break;
                    }
                    catch (Exception ex)
                    {
                        if (xnIdx == xnl.Count - 1)
                        {
                            err = ("装载HisProfile.xml失败!\n" + ex.Message);
                            return(-1);
                        }
                        else
                        {
                            xnIdx++;
                            continue;
                        }
                    }
                }
            }
            #endregion
            node = doc.SelectSingleNode("/设置/数据库设置");

            if (node == null)
            {
                err = ("没有找到数据库设置!");
                return(-1);
            }

            string strDataSource = node.Attributes[0].Value;

            //判断连接串是否加密{2480BEE8-92D0-484e-8D7E-2E24CC41C0C1}
            node = doc.SelectSingleNode("/设置/加密");
            if (node == null)
            {
                err = ("没有找到是否加密信息!");
                return(-1);
            }
            string strCrypto = node.Attributes[0].Value;
            if (strCrypto.Trim().Equals("1"))
            {
                //{D515E09B-E299-47e0-BF19-EDFDB6E4C775}
                //strDataSource = Neusoft.HisDecrypt.Decrypt(strDataSource);
                strDataSource = Neusoft.HisCrypto.DESCryptoService.DESDecrypt(strDataSource, DESKey);
            }
            //END

            #region 数据库类型
            node = doc.SelectSingleNode("/设置/数据库类别");
            if (node != null)
            {
                DBType = GetDBType(node.Attributes[0].Value);//数据库类型判断.//{08F955BE-6313-47cc-AB3A-14897F4147B8}
            }


            #endregion
            DataSouceString = strDataSource;

            node = doc.SelectSingleNode("/设置/设置");

            if (node == null)
            {
                err = ("没有找到SQL设置!");
                return(-1);
            }



            node = doc.SelectSingleNode("/设置/管理员");


            if (node == null)
            {
                err = ("没有找到管理员密码!");
                return(-1);
            }
            //{D515E09B-E299-47e0-BF19-EDFDB6E4C775}
            //ManagerPWD = Neusoft.HisDecrypt.Decrypt(node.Attributes[0].Value);
            ManagerPWD = Neusoft.HisCrypto.DESCryptoService.DESDecrypt(node.Attributes[0].Value, DESKey);

            node = doc.SelectSingleNode("/设置/正式库");
            if (node != null)
            {
                if (node.Attributes[0].Value == "0")
                {
                    IsTestDB = true;
                }
                else
                {
                    IsTestDB = false;
                }
            }
            node = doc.SelectSingleNode("/设置/服务器");
            if (node != null)
            {
                MaxConnection = FrameWork.Function.NConvert.ToInt32(node.Attributes[0].Value);

                try
                {
                    TimeOutSecond = FrameWork.Function.NConvert.ToInt32(node.Attributes[1].Value);
                }
                catch { }

                if (TimeOutSecond < 6 && TimeOutSecond > 0)
                {
                    TimeOutSecond = 6;//最小时间间隔
                }
            }
            //add start
            #region  层监控设置
            node = doc.SelectSingleNode("/设置/三层监控");
            if (node != null)
            {
                if (node.Attributes.Count > 0)
                {
                    if (node.Attributes[0].Value == "0")//0代表使用三层监控
                    {
                        IsSocketUsed = true;
                    }
                    else
                    {
                        IsSocketUsed = false;
                    }
                }
            }
            #endregion
            //add end

            err = "";


            return(0);
        }
Ejemplo n.º 36
0
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            panel1.Visible = true;
            panel2.Visible = false;

            if (e.Error != null)
            {
                MessageBox.Show(this, "An error occured: " + e.Error.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (e.Cancelled || e.Error != null)
            {
                checkedListBox1.Items.Clear();
                button2.Enabled = false;
                return;
            }

            Dictionary <string, bool> overrideDefault = new Dictionary <string, bool>(System.Environment.OSVersion.Platform == PlatformID.MacOSX || System.Environment.OSVersion.Platform == PlatformID.Unix ? StringComparer.InvariantCulture : StringComparer.InvariantCultureIgnoreCase);
            string configfile    = null;
            bool   updateDefault = true;

            try
            {
                configfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "UpdateVersionNumber.config");
                if (System.IO.File.Exists(configfile))
                {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load(configfile);

                    System.Xml.XmlNode root = doc["root"];
                    if (root.Attributes["update_as_default"] != null)
                    {
                        updateDefault = bool.Parse(root.Attributes["update_as_default"].Value);
                    }

                    foreach (System.Xml.XmlNode file in root.SelectNodes("file"))
                    {
                        string filename = file.InnerText;
                        if (!System.IO.Path.IsPathRooted(filename))
                        {
                            filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), filename);
                        }

                        overrideDefault[filename] = bool.Parse(file.Attributes["update"].Value);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, string.Format("An error occured while reading config file \"{0}\": {1}", configfile, ex.Message), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            button2.Enabled = true;
            List <DisplayItem> files = (List <DisplayItem>)e.Result;

            checkedListBox1.Items.Clear();
            Version vmax = new Version();

            foreach (DisplayItem d in files)
            {
                checkedListBox1.Items.Add(d, overrideDefault.ContainsKey(d.File) ? overrideDefault[d.File] : updateDefault);
                vmax = d.Version > vmax ? d.Version : vmax;
            }

            textBox1.Text = vmax.ToString();
        }
Ejemplo n.º 37
0
        public List <IFileEntry> List()
        {
            List <IFileEntry> files     = new List <IFileEntry>();
            string            extraUrl  = "?format=xml&limit=" + ITEM_LIST_LIMIT.ToString();
            string            markerUrl = "";

            bool repeat;

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

                HttpWebRequest req = CreateRequest("", extraUrl + markerUrl);

                try
                {
                    Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);
                    using (HttpWebResponse resp = (HttpWebResponse)areq.GetResponse())
                        using (System.IO.Stream s = areq.GetResponseStream())
                            doc.Load(s);
                }
                catch (WebException wex)
                {
                    if (markerUrl == "") //Only check on first itteration
                    {
                        if (wex.Response is HttpWebResponse && ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
                        {
                            throw new FolderMissingException(wex);
                        }
                    }

                    //Other error, just re-throw
                    throw;
                }

                System.Xml.XmlNodeList lst = doc.SelectNodes("container/object");

                //Perhaps the folder does not exist?
                //The response should be 404 from the server, but it is not :(
                if (lst.Count == 0 && markerUrl == "") //Only on first itteration
                {
                    try { CreateFolder(); }
                    catch { } //Ignore
                }

                string lastItemName = "";
                foreach (System.Xml.XmlNode n in lst)
                {
                    string   name = n["name"].InnerText;
                    long     size;
                    DateTime mod;

                    if (!long.TryParse(n["bytes"].InnerText, out size))
                    {
                        size = -1;
                    }
                    if (!DateTime.TryParse(n["last_modified"].InnerText, out mod))
                    {
                        mod = new DateTime();
                    }

                    lastItemName = name;
                    files.Add(new FileEntry(name, size, mod, mod));
                }

                repeat = lst.Count == ITEM_LIST_LIMIT;

                if (repeat)
                {
                    markerUrl = "&marker=" + System.Web.HttpUtility.UrlEncode(lastItemName);
                }
            } while (repeat);

            return(files);
        }
Ejemplo n.º 38
0
        public async Task PutAsync(string remotename, System.IO.Stream stream, CancellationToken cancelToken)
        {
            // Some challenges with uploading to Jottacloud:
            // - Jottacloud supports use of a custom header where we can tell the server the MD5 hash of the file
            //   we are uploading, and then it will verify the content of our request against it. But the HTTP
            //   status code we get back indicates success even if there is a mismatch, so we must dig into the
            //   XML response to see if we were able to correctly upload the new content or not. Another issue
            //   is that if the stream is not seek-able we have a challenge pre-calculating MD5 hash on it before
            //   writing it out on the HTTP request stream. And even if the stream is seek-able it may be throttled.
            //   One way to avoid using the throttled stream for calculating the MD5 is to try to get the
            //   underlying stream from the "m_basestream" field, with fall-back to a temporary file.
            // - We can instead chose to upload the data without setting the MD5 hash header. The server will
            //   calculate the MD5 on its side and return it in the response back to use. We can then compare it
            //   with the MD5 hash of the stream (using a MD5CalculatingStream), and if there is a mismatch we can
            //   request the server to remove the file again and throw an exception. But there is a requirement that
            //   we specify the file size in a custom header. And if the stream is not seek-able we are not able
            //   to use stream.Length, so we are back at square one.
            Duplicati.Library.Utility.TempFile tmpFile = null;
            var baseStream = stream;

            while (baseStream is Duplicati.Library.Utility.OverrideableStream)
            {
                baseStream = typeof(Duplicati.Library.Utility.OverrideableStream).GetField("m_basestream", System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(baseStream) as System.IO.Stream;
            }
            if (baseStream == null)
            {
                throw new Exception(string.Format("Unable to unwrap stream from: {0}", stream.GetType()));
            }
            string md5Hash;

            if (baseStream.CanSeek)
            {
                var originalPosition = baseStream.Position;
                using (var md5 = System.Security.Cryptography.MD5.Create())
                    md5Hash = Library.Utility.Utility.ByteArrayAsHexString(md5.ComputeHash(baseStream));
                baseStream.Position = originalPosition;
            }
            else
            {
                // No seeking possible, use a temp file
                tmpFile = new Duplicati.Library.Utility.TempFile();
                using (var os = System.IO.File.OpenWrite(tmpFile))
                    using (var md5 = new Utility.MD5CalculatingStream(baseStream))
                    {
                        await Utility.Utility.CopyStreamAsync(md5, os, true, cancelToken, m_copybuffer);

                        md5Hash = md5.GetFinalHashString();
                    }
                stream = System.IO.File.OpenRead(tmpFile);
            }
            try
            {
                // Create request, with query parameter, and a few custom headers.
                // NB: If we wanted to we could send the same POST request as below but without the file contents
                // and with "cphash=[md5Hash]" as the only query parameter. Then we will get an HTTP 200 (OK) response
                // if an identical file already exists, and we can skip uploading the new file. We will get
                // HTTP 404 (Not Found) if file does not exists or it exists with a different hash, in which
                // case we must send a new request to upload the new content.
                var fileSize = stream.Length;
                var req      = CreateRequest(System.Net.WebRequestMethods.Http.Post, remotename, "umode=nomultipart", true);
                req.Headers.Add("JMd5", md5Hash);              // Not required, but it will make the server verify the content and mark the file as corrupt if there is a mismatch.
                req.Headers.Add("JSize", fileSize.ToString()); // Required, and used to mark file as incomplete if we upload something  be the total size of the original file!
                // File time stamp headers: Since we are working with a stream here we do not know the local file's timestamps,
                // and then we can just omit the JCreated and JModified and let the server automatically set the current time.
                //req.Headers.Add("JCreated", timeCreated);
                //req.Headers.Add("JModified", timeModified);
                req.ContentType   = "application/octet-stream";
                req.ContentLength = fileSize;

                // Write post data request
                var areq = new Utility.AsyncHttpRequest(req);
                using (var rs = areq.GetRequestStream())
                    await Utility.Utility.CopyStreamAsync(stream, rs, true, cancelToken, m_copybuffer);
                // Send request, and check response
                using (var resp = (System.Net.HttpWebResponse)areq.GetResponse())
                {
                    if (resp.StatusCode != System.Net.HttpStatusCode.Created)
                    {
                        throw new System.Net.WebException(Strings.Jottacloud.FileUploadError, null, System.Net.WebExceptionStatus.ProtocolError, resp);
                    }

                    // Request seems to be successful, but we must verify the response XML content to be sure that the file
                    // was correctly uploaded: The server will verify the JSize header and mark the file as incomplete if
                    // there was mismatch, and it will verify the JMd5 header and mark the file as corrupt if there was a hash
                    // mismatch. The returned XML contains a file element, and if upload was error free it contains a single
                    // child element "currentRevision", which has a "state" child element with the string "COMPLETED".
                    // If there was a problem we should have a "latestRevision" child element, and this will have state with
                    // value "INCOMPLETE" or "CORRUPT". If the file was new or had no previous complete versions the latestRevision
                    // will be the only child, but if not there may also be a "currentRevision" representing the previous
                    // complete version - and then we need to detect the case where our upload failed but there was an existing
                    // complete version!
                    using (var rs = areq.GetResponseStream())
                    {
                        var doc = new System.Xml.XmlDocument();
                        try { doc.Load(rs); }
                        catch (System.Xml.XmlException)
                        {
                            throw new System.Net.WebException(Strings.Jottacloud.FileUploadError, System.Net.WebExceptionStatus.ProtocolError);
                        }
                        bool uploadCompletedSuccessfully = false;
                        var  xFile = doc["file"];
                        if (xFile != null)
                        {
                            var xRevState = xFile.SelectSingleNode("latestRevision");
                            if (xRevState == null)
                            {
                                xRevState = xFile.SelectSingleNode("currentRevision/state");
                                if (xRevState != null)
                                {
                                    uploadCompletedSuccessfully = xRevState.InnerText == "COMPLETED"; // Success: There is no "latestRevision", only a "currentRevision" (and it specifies the file is complete, but I think it always will).
                                }
                            }
                        }
                        if (!uploadCompletedSuccessfully) // Report error (and we just let the incomplete/corrupt file revision stay on the server..)
                        {
                            throw new System.Net.WebException(Strings.Jottacloud.FileUploadError, System.Net.WebExceptionStatus.ProtocolError);
                        }
                    }
                }
            }
            finally
            {
                try
                {
                    if (tmpFile != null)
                    {
                        tmpFile.Dispose();
                    }
                }
                catch { }
            }
        }
Ejemplo n.º 39
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string res = "";


            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(this.Request.InputStream);
                System.Xml.XmlNodeList nodelist = doc.SelectNodes("//xml");//匹配所有xml节点

                //errordetail = doc.InnerXml;
                if (nodelist.Count > 0)
                {
                    System.Xml.XmlNode msgNode = nodelist[0];
                    if (msgNode != null)
                    {
                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                        //请在这里加上商户的业务逻辑程序代码


                        //——请根据您的业务逻辑来编写程序(以下代码仅作参考)——

                        //交易状态
                        string result = msgNode.SelectSingleNode("return_code").InnerText;
                        if (result == "SUCCESS")
                        {
                            //判断该笔订单是否在商户网站中已经做过处理
                            //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                            //如果有做过处理,不执行商户的业务程序

                            //商户订单号
                            string out_trade_no = msgNode.SelectSingleNode("out_trade_no").InnerText;

                            //微信交易号
                            string trade_no = msgNode.SelectSingleNode("transaction_id").InnerText;

                            lock (lockWechatPayObj)
                            {
                                //查询支付订单是否支付
                                string strwhere = " serialNumber='" + out_trade_no + "' and paystatus=1 ";

                                List <System.Model.Member_Charge_Withdraw> mcwlist = _bll.mcwbll.GetModelList(strwhere);

                                if (mcwlist.Count == 1)
                                {
                                    System.Model.Member_Charge_Withdraw mcw = mcwlist[0];

                                    mcw.paydate        = System.DateTime.Now.ToString();
                                    mcw.paystatus      = 2;
                                    mcw.paytype        = 2;//微信
                                    mcw.statusname     = "已支付";
                                    mcw.typename       = "微信";
                                    mcw.tpSerialNumber = trade_no;
                                    _bll.mcwbll.Update(mcw);

                                    //订单付款
                                    if (mcw.types == 1)
                                    {
                                        strwhere = " serialNumber='" + out_trade_no + "'  ";

                                        List <System.Model.order_info> oilist = _bll.oibll.GetModelList(strwhere);

                                        if (oilist.Count == 1)
                                        {
                                            System.Model.order_info oi = oilist[0];
                                            oi.statuses = 2;
                                            _bll.oibll.Update(oi);
                                            //锁定设备
                                            System.Model.facility_port ports = _bll.fpbll.GetModel(oi.port);
                                            ports.isEmploy = 1;
                                            _bll.fpbll.Update(ports);
                                            //通知设备开始充电
                                            System.Model.facility fa = _bll.fbll.GetModel(oi.facility);
                                            open.opens(fa.identitycode, ports.identitycode, oi.customid, out_trade_no);
                                        }
                                        else
                                        {
                                        }
                                    }
                                    //充值

                                    //
                                }
                                else
                                {
                                    //订单未找到或者已支付
                                }
                            }
                        }
                        else
                        {
                        }
                        //——请根据您的业务逻辑来编写程序(以上代码仅作参考)——

                        /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    }
                    else//验证失败
                    {
                    }
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
            }
            Response.Write(res);
        }
Ejemplo n.º 40
0
    private static System.Collections.Generic.HashSet <string> ParsePluginsXML(string platform,
                                                                               System.Collections.Generic.List <string> in_pluginFiles)
    {
        var newDlls = new System.Collections.Generic.HashSet <string>();

        foreach (var pluginFile in in_pluginFiles)
        {
            if (!System.IO.File.Exists(pluginFile))
            {
                continue;
            }

            try
            {
                var doc = new System.Xml.XmlDocument();
                doc.Load(pluginFile);
                var Navigator      = doc.CreateNavigator();
                var pluginInfoNode = Navigator.SelectSingleNode("//PluginInfo");
                var boolMotion     = pluginInfoNode.GetAttribute("Motion", "");

                var it = Navigator.Select("//Plugin");

                if (boolMotion == "true")
                {
                    newDlls.Add("AkMotion");
                }

                foreach (System.Xml.XPath.XPathNavigator node in it)
                {
                    var pid = uint.Parse(node.GetAttribute("ID", ""));
                    if (pid == 0)
                    {
                        continue;
                    }

                    var dll = string.Empty;

                    if (platform == "Switch")
                    {
                        if ((PluginID)pid == PluginID.WwiseMeter)
                        {
                            dll = "AkMeter";
                        }
                    }
                    else if (builtInPluginIDs.Contains((PluginID)pid))
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(dll))
                    {
                        dll = node.GetAttribute("DLL", "");
                    }

                    newDlls.Add(dll);
                }
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError("WwiseUnity: " + pluginFile + " could not be parsed. " + ex.Message);
            }
        }

        return(newDlls);
    }
        }//fin InitForm

        public new void FormEvent(String FormUID, ref SAPbouiCOM.ItemEvent pVal, ref Boolean BubbleEvent)
        {
            //SAPbouiCOM.DataTable oDataTable;
            //inherited FormEvent(FormUID,var pVal,var BubbleEvent);
            String Local;

            SAPbouiCOM.CheckBox oCheckBox;
            base.FormEvent(FormUID, ref pVal, ref BubbleEvent);


            try
            {
                if ((pVal.EventType == BoEventTypes.et_ITEM_PRESSED) && (pVal.BeforeAction == true))
                {
                    if ((pVal.ItemUID == "1") && ((oForm.Mode == BoFormMode.fm_ADD_MODE) || (oForm.Mode == BoFormMode.fm_UPDATE_MODE)))
                    {
                        s = "1";
                        oDBDSHeader.SetValue("Code", 0, s);
                        if (1 != FSBOApp.MessageBox("¿ Desea actualizar los parametros ?", 1, "Ok", "Cancelar", ""))
                        {
                            BubbleEvent = false;
                        }
                        else
                        {
                            BubbleEvent = false;

                            if (oForm.SupportedModes == 1)
                            {
                                s = "1";
                            }
                            else
                            {
                                s = "3";
                            }

                            if (AddDatos(s))
                            {
                                FSBOApp.StatusBar.SetText("Datos actualizados satisfactoriamente", BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
                                oForm.Mode = BoFormMode.fm_OK_MODE;
                                //Remover menu y colocar los nuevos segun parametros


                                System.Xml.XmlDocument oXmlDoc = null;
                                oXmlDoc = new System.Xml.XmlDocument();
                                oXmlDoc.Load(System.IO.Path.GetDirectoryName(TMultiFunctions.ParamStr(0)) + "\\Menus\\RemoveMenuPE.xml");

                                string sXML = oXmlDoc.InnerXml.ToString();
                                FSBOApp.LoadBatchActions(ref sXML);

                                oXmlDoc.Load(System.IO.Path.GetDirectoryName(TMultiFunctions.ParamStr(0)) + "\\Menus\\Menu.xml");

                                sXML = oXmlDoc.InnerXml.ToString();
                                FSBOApp.LoadBatchActions(ref sXML);
                            }
                        }
                    }
                }

                if ((pVal.EventType == BoEventTypes.et_ITEM_PRESSED) && (!pVal.BeforeAction))
                {
                    if (pVal.ItemUID == "btnProcFE")
                    {
                        CargarProcedimientos();
                    }
                }
            }
            catch (Exception e)
            {
                if (FCmpny.InTransaction)
                {
                    FCmpny.EndTransaction(BoWfTransOpt.wf_RollBack);
                }
                FSBOApp.StatusBar.SetText(e.Message + " ** Trace: " + e.StackTrace, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Error);
                OutLog("FormEvent: " + e.Message + " ** Trace: " + e.StackTrace);
            }
        }//fin FormEvent
Ejemplo n.º 42
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.º 43
0
    public static bool Populate()
    {
        if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode || UnityEditor.EditorApplication.isCompiling)
        {
            return(false);
        }

        try
        {
            // Try getting the SoundbanksInfo.xml file for Windows or Mac first, then try to find any other available platform.
            var logWarnings = AkBasePathGetter.LogWarnings;
            AkBasePathGetter.LogWarnings = false;
            var FullSoundbankPath = AkBasePathGetter.GetPlatformBasePath();
            AkBasePathGetter.LogWarnings = logWarnings;

            var filename = System.IO.Path.Combine(FullSoundbankPath, "SoundbanksInfo.xml");
            if (!System.IO.File.Exists(filename))
            {
                FullSoundbankPath = System.IO.Path.Combine(UnityEngine.Application.streamingAssetsPath,
                                                           WwiseSetupWizard.Settings.SoundbankPath);

                if (!System.IO.Directory.Exists(FullSoundbankPath))
                {
                    return(false);
                }

                var foundFiles =
                    System.IO.Directory.GetFiles(FullSoundbankPath, "SoundbanksInfo.xml", System.IO.SearchOption.AllDirectories);

                if (foundFiles.Length == 0)
                {
                    return(false);
                }

                filename = foundFiles[0];
            }

            var time = System.IO.File.GetLastWriteTime(filename);
            if (time <= s_LastParsed)
            {
                return(false);
            }

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

            var bChanged   = false;
            var soundBanks = doc.GetElementsByTagName("SoundBanks");
            for (var i = 0; i < soundBanks.Count; i++)
            {
                var soundBank = soundBanks[i].SelectNodes("SoundBank");
                for (var j = 0; j < soundBank.Count; j++)
                {
                    bChanged = SerialiseSoundBank(soundBank[j]) || bChanged;
                }
            }

            return(bChanged);
        }
        catch
        {
            return(false);
        }
    }
Ejemplo n.º 44
0
        //新增构造函数
        public Form_SalesOrder()
        {
            InitializeComponent();

            this.invoicer.Text      = Pharmacy.AppClient.Common.AppClientContext.CurrentUser.Employee.Name;
            this.lblCreateDate.Text = DateTime.Now.Date.ToLongDateString();

            #region 列表处理
            this.dataGridView1.RowPostPaint += (s, e) => DataGridViewOperator.SetRowNumber(this.dataGridView1, e);
            this.dataGridView1.CellClick    += dataGridView1_CellClick;

            this.dataGridView1.CellMouseDown += (s, e) =>       //选定列表中的药品id,给右键菜单使用
            {
                if (this.dataGridView1.Rows.Count <= 0)
                {
                    return;
                }
                var c = this.dataGridView1.CurrentRow.DataBoundItem as SalesOrderDetailModel;
                this.BaseRightMenu.DrugId = c.DrugInfoId;
            };

            this.BaseRightMenu = new UI.Forms.BaseForm.BasicInfoRightMenu(this.dataGridView1); //右键支持
            this.BaseRightMenu.InsertDrugBasicInfo();                                          //加入药品基本信息查询功能

            this.BaseRightMenu.InserMenu("删除该品种", () =>
            {
                if (this.dataGridView1.Rows.Count <= 0)
                {
                    return;
                }
                var c = MessageBox.Show("确定需要删除该品种吗", "提示", MessageBoxButtons.OKCancel);
                if (c == System.Windows.Forms.DialogResult.Cancel)
                {
                    return;
                }
                this.DeleteDrug();
            });
            #endregion

            #region  择客户单位
            this.textBox1.Focus();
            this.textBox1.KeyDown += (s, e) =>
            {
                if (e.KeyCode != Keys.Return)
                {
                    return;
                }
                using (Common.FormPurchaseSelector frm = new Common.FormPurchaseSelector(this.textBox1.Text.Trim()))
                {
                    var re = frm.ShowDialog();
                    if (re == System.Windows.Forms.DialogResult.OK)
                    {
                        this.CurrentPurchaseUnit  = frm.Result;
                        this.txtPurchaseName.Text = this.CurrentPurchaseUnit.Name;

                        this.BaseRightMenu.InsertPurchaseUnitBasicInfo();           //加入右键查询该客户的基本信息查询界面

                        #region 当前客户单位的采购员
                        var c = this.PharmacyDatabaseService.GetPurchaseUnitBuyersByPurchaseUnitId(this.CurrentPurchaseUnit.Id, out msg).OrderBy(r => r.Name).ToList();

                        c.Add(new PurchaseUnitBuyer {
                            Id   = Guid.Empty,
                            Name = "请选择"
                        });
                        this.cmbPurchaseUnitBuyer.DisplayMember = "Name";
                        this.cmbPurchaseUnitBuyer.ValueMember   = "Id";
                        this.cmbPurchaseUnitBuyer.DataSource    = c;
                        if (c.Count > 0)
                        {
                            this.cmbPurchaseUnitBuyer.SelectedIndex = 0;
                            this.CurrentPurchaseUnitBuyer           = c.First();
                        }
                        #endregion
                    }
                }
            };
            #endregion

            #region 客户采购员选择
            this.cmbPurchaseUnitBuyer.SelectedIndexChanged += (s, e) =>
            {
                this.CurrentPurchaseUnitBuyer = this.cmbPurchaseUnitBuyer.SelectedItem as PurchaseUnitBuyer;
            };
            #endregion

            #region 提货方式
            var pickupGoodTypeList = EnumToListHelper.ConverEnumToList(typeof(PickUpGoodType));
            this.cmbPickUpGoods.DisplayMember = "Name";
            this.cmbPickUpGoods.ValueMember   = "Id";
            this.cmbPickUpGoods.DataSource    = pickupGoodTypeList;
            this.cmbPickUpGoods.SelectedValue = (int)this.CurrentPickUpGoodType;
            #endregion

            #region 品种类型选择下拉列表
            var drugTypeList = EnumToListHelper.ConverEnumToList(typeof(SalesDrugType));
            this.comboBox1.DisplayMember         = "Name";
            this.comboBox1.ValueMember           = "Id";
            this.comboBox1.DataSource            = drugTypeList;
            this.comboBox1.SelectedIndex         = 0;
            this.comboBox1.SelectedIndexChanged += (s, e) =>
            {
                this.CurrentSalesDrugType       = (SalesDrugType)this.comboBox1.SelectedIndex;
                this.toolStripStatusLabel2.Text = ((MyLibs.EnumTypeList) this.comboBox1.SelectedItem).Name;
            };

            #endregion

            #region 销售人员名单绑定列表
            System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
            xmlDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "BugsBox.Pharmacy.AppClient.SalePriceType.xml");
            System.Xml.XmlNodeList xmlNode = xmlDocument.SelectNodes("/SalePriceType/priceType");

            xmlNode = xmlDocument.SelectNodes("/SalePriceType/salerRoleName");
            string salerRoleName = xmlNode[0].Attributes[0].Value.ToString();
            var    SalerNames    = this.PharmacyDatabaseService.GetUserByPosition(salerRoleName, string.Empty, string.Empty).OrderBy(r => r.Employee.Name).ToList();//根据角色获取用户
            var    UE            = (from i in SalerNames
                                    select new SalerNames
            {
                Id = i.Id,
                EName = i.Employee.Name
            }).ToList();
            //插入一条“请选择”
            UE.Insert(0, new SalerNames
            {
                Id    = Guid.Empty,
                EName = "请选择销售员"
            });

            this.cmbSalesMan.ValueMember   = "Id";
            this.cmbSalesMan.DisplayMember = "EName";
            this.cmbSalesMan.DataSource    = UE;
            this.cmbSalesMan.SelectedIndex = 0;
            #endregion
        }
Ejemplo n.º 45
0
        public bool Build(string exeFilename, params IMapItem[] items)
        {
            var location = GetLocation();

            CopyTemplateToTempFolder(location);

            var project     = new System.Xml.XmlDocument();
            var projectPath = Path.Combine(TempDir, "JoystickMerger.Feeder", "JoystickMerger.Feeder.csproj");

            project.Load(projectPath);
            foreach (System.Xml.XmlNode node in project.DocumentElement)
            {
                if (node.Name == "PropertyGroup" /*&& node.GetAttribute("Condition") == "'$(Configuration)|$(Platform)' == 'Release|x64'"*/)
                {
                    foreach (System.Xml.XmlNode propNode in node.ChildNodes)
                    {
                        if (propNode.Name == "OutputPath")
                        {
                            propNode.InnerText = Path.GetDirectoryName(exeFilename);
                        }
                        else if (propNode.Name == "AssemblyName")
                        {
                            propNode.InnerText = Path.GetFileNameWithoutExtension(exeFilename);
                        }
                    }
                }
            }
            project.Save(projectPath);

            var feederPath = Path.Combine(TempDir, "JoystickMerger.Feeder", "JoystickMerger.xml");


            var info = new CompileInfo();

            foreach (var item in items)
            {
                item.Initialize(info);
            }
            info.EndInitialization();

            using (var file = File.CreateText(System.IO.Path.Combine(TempDir, "JoystickMerger.Feeder", "GameDevPoller.Generated.cs")))
            {
                file.WriteLine("using System;");
                file.WriteLine("using System.Collections.Generic;");
                file.WriteLine("using System.Linq;");
                file.WriteLine("using System.Text;");
                file.WriteLine("using SharpDX;");
                file.WriteLine("using SharpDX.DirectInput;");
                file.WriteLine("using System.Windows.Forms;");
                file.WriteLine("using vJoyInterfaceWrap;");
                file.WriteLine();
                file.WriteLine("// This file is generated with JoystickMerger.Generator. Do not edit.");
                file.WriteLine("namespace JoystickMerger.Feeder");
                file.WriteLine("{");
                file.WriteLine("    partial class GameDevPoller");
                file.WriteLine("    {");
                file.WriteLine("        // vJoy device number.");
                file.WriteLine("        const uint id = 1;");

                foreach (var item in items)
                {
                    item.Declaration(info, file);
                }
                file.WriteLine();

                ValidateVJoyConfiguration(info, file);

                foreach (var item in items)
                {
                    item.PreFeed(info, file);
                }
                file.WriteLine("        private void Feed()");
                file.WriteLine("        {");
                foreach (var item in items)
                {
                    item.Feed(info, file);
                }
                file.WriteLine("        }");
                file.WriteLine();

                foreach (var item in items)
                {
                    item.PostFeed(info, file);
                }

                file.WriteLine("    }");
                file.WriteLine("}");
            }


            return(RunCompiler());
        }
Ejemplo n.º 46
0
        private IEnumerable <IFileEntry> ListWithouExceptionCatch()
        {
            var req = CreateRequest("");

            req.Method = "PROPFIND";
            req.Headers.Add("Depth", "1");
            req.ContentType   = "text/xml";
            req.ContentLength = PROPFIND_BODY.Length;

            var areq = new Utility.AsyncHttpRequest(req);

            using (System.IO.Stream s = areq.GetRequestStream())
                s.Write(PROPFIND_BODY, 0, PROPFIND_BODY.Length);

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

            using (var resp = (System.Net.HttpWebResponse)areq.GetResponse())
            {
                int code = (int)resp.StatusCode;
                if (code < 200 || code >= 300) //For some reason Mono does not throw this automatically
                {
                    throw new System.Net.WebException(resp.StatusDescription, null, System.Net.WebExceptionStatus.ProtocolError, resp);
                }

                if (!string.IsNullOrEmpty(m_debugPropfindFile))
                {
                    using (var rs = areq.GetResponseStream())
                        using (var fs = new System.IO.FileStream(m_debugPropfindFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
                            Utility.Utility.CopyStream(rs, fs, false, m_copybuffer);

                    doc.Load(m_debugPropfindFile);
                }
                else
                {
                    using (var rs = areq.GetResponseStream())
                        doc.Load(rs);
                }
            }

            System.Xml.XmlNamespaceManager nm = new System.Xml.XmlNamespaceManager(doc.NameTable);
            nm.AddNamespace("D", "DAV:");

            List <IFileEntry> files = new List <IFileEntry>();

            m_filenamelist = new List <string>();

            foreach (System.Xml.XmlNode n in doc.SelectNodes("D:multistatus/D:response/D:href", nm))
            {
                //IIS uses %20 for spaces and %2B for +
                //Apache uses %20 for spaces and + for +
                string name = Library.Utility.Uri.UrlDecode(n.InnerText.Replace("+", "%2B"));

                string cmp_path;

                //TODO: This list is getting ridiculous, should change to regexps

                if (name.StartsWith(m_url, StringComparison.Ordinal))
                {
                    cmp_path = m_url;
                }
                else if (name.StartsWith(m_rawurl, StringComparison.Ordinal))
                {
                    cmp_path = m_rawurl;
                }
                else if (name.StartsWith(m_rawurlPort, StringComparison.Ordinal))
                {
                    cmp_path = m_rawurlPort;
                }
                else if (name.StartsWith(m_path, StringComparison.Ordinal))
                {
                    cmp_path = m_path;
                }
                else if (name.StartsWith("/" + m_path, StringComparison.Ordinal))
                {
                    cmp_path = "/" + m_path;
                }
                else if (name.StartsWith(m_sanitizedUrl, StringComparison.Ordinal))
                {
                    cmp_path = m_sanitizedUrl;
                }
                else if (name.StartsWith(m_reverseProtocolUrl, StringComparison.Ordinal))
                {
                    cmp_path = m_reverseProtocolUrl;
                }
                else
                {
                    continue;
                }

                if (name.Length <= cmp_path.Length)
                {
                    continue;
                }

                name = name.Substring(cmp_path.Length);

                long     size         = -1;
                DateTime lastAccess   = new DateTime();
                DateTime lastModified = new DateTime();
                bool     isCollection = false;

                System.Xml.XmlNode stat = n.ParentNode.SelectSingleNode("D:propstat/D:prop", nm);
                if (stat != null)
                {
                    System.Xml.XmlNode s = stat.SelectSingleNode("D:getcontentlength", nm);
                    if (s != null)
                    {
                        size = long.Parse(s.InnerText);
                    }
                    s = stat.SelectSingleNode("D:getlastmodified", nm);
                    if (s != null)
                    {
                        try
                        {
                            //Not important if this succeeds
                            lastAccess = lastModified = DateTime.Parse(s.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                        }
                        catch { }
                    }

                    s = stat.SelectSingleNode("D:iscollection", nm);
                    if (s != null)
                    {
                        isCollection = s.InnerText.Trim() == "1";
                    }
                    else
                    {
                        isCollection = (stat.SelectSingleNode("D:resourcetype/D:collection", nm) != null);
                    }
                }

                FileEntry fe = new FileEntry(name, size, lastAccess, lastModified);
                fe.IsFolder = isCollection;
                m_filenamelist.Add(name);
                yield return(fe);
            }
        }
Ejemplo n.º 47
0
        public GameBoard(string pGameBoardFile, Player[] pPlayers)
        {
            System.Xml.XmlDocument xmlfile = new System.Xml.XmlDocument();

            eActionType contextAction;

            Version fileVersion = new Version("0.0");

            FreeParkingOwner = BANK;
            FreeJailOwner    = BANK;

            xmlfile.Load(System.Environment.ExpandEnvironmentVariables(pGameBoardFile));

            if (!Version.TryParse(xmlfile.SelectSingleNode("monopoly").Attributes["version"]?.InnerText, out fileVersion))
            {
                fileVersion = new Version("0.0");
            }

            if (fileVersion.Minor < 6)
            {
                throw new NotSupportedException("Gameboard Version to low");
            }

            Settings = new Settings(xmlfile.SelectSingleNode("monopoly"));

            foreach (System.Xml.XmlNode xmlfield in xmlfile.SelectNodes("monopoly/fields/*"))
            {
                ushort contextCash;
                string contextName;
                contextName = xmlfield.Attributes.GetNamedItem("name")?.InnerText;

                ushort.TryParse(xmlfield.Attributes.GetNamedItem("cash")?.InnerText, out contextCash);

                switch (xmlfield.Name.ToLower())
                {
                case "start":
                {
                    FieldCol.Add(contextName, new Fields.Startfield(contextCash, contextName));
                    break;
                }

                case "house":
                {
                    FieldCol.Add(contextName, new Fields.HouseField(xmlfield, Settings));
                    break;
                }

                case "chance":
                {
                    var           actionText = xmlfield.Attributes.GetNamedItem("action")?.InnerText.Split(',');
                    eActionType[] actions    = new eActionType[actionText.Length - 1 + 1];
                    for (int i = 0; i < actionText.Length; i++)
                    {
                        if (!(Enum.TryParse(actionText[i], out actions[i])))
                        {
                            System.Diagnostics.Debug.WriteLine($"field {contextName} has unknown action {xmlfield.Attributes.GetNamedItem("action")?.InnerText}");
                        }
                    }

                    FieldCol.Add(contextName, new Fields.ChanceField(contextName, actions[0], contextCash));
                    break;
                }

                case "station":
                {
                    FieldCol.Add(contextName, new Fields.StationField(contextName, contextCash));
                    break;
                }

                case "jail":
                {
                    if (!Enum.TryParse(xmlfield.Attributes.GetNamedItem("action")?.InnerText, out contextAction))
                    {
                        System.Diagnostics.Debug.WriteLine($"field {contextName} has unknown action {xmlfield.Attributes.GetNamedItem("action")?.InnerText}");
                    }
                    FieldCol.Add(contextName, new Fields.JailField(contextName, contextAction));
                    break;
                }

                default:
                {
                    FieldCol.Add(contextName, new Fields.ChanceField(contextName, eActionType.None, 0));
                    throw new NotSupportedException($"Fieldtype {nameof(xmlfield.Name)}={xmlfield.Name} not supported");
                }
                }
            }

            if (Settings.UseWundertuete)
            {
                Wundertuete = new Entity("Wundertuete", System.Drawing.Color.White);
            }

            PlayerRank = pPlayers;
            Statistics = new StatisticsClass(this);
        }
Ejemplo n.º 48
0
        // Given a token and routing information, complete the transaction
        // by transferring the funds and debiting the account
        public EFTConfirmation TransferFunds(string token, EFTRoutingInfo routingInfo)
        {
            // Parse out amount and transactionID from token
            // Convert token string to bytes[] to create MemoryStream
            System.Text.ASCIIEncoding a  = new System.Text.ASCIIEncoding();
            System.IO.MemoryStream    ms = new System.IO.MemoryStream(a.GetBytes(token));

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

            //Get transactionID, acctID and amount
            System.Xml.XmlNode node = doc.SelectSingleNode("eft/transactionID");
            if (node == null)
            {
                throw new Exception("Invalid token.");
            }

            string s       = node.InnerText;
            Guid   transID = new Guid(s);

            node = doc.SelectSingleNode("eft/acct");
            if (node == null)
            {
                throw new Exception("Invalid token.");
            }

            int acctID = Int32.Parse(node.InnerText);

            node = doc.SelectSingleNode("eft/amt");
            if (node == null)
            {
                throw new Exception("Invalid token.");
            }

            decimal amt = Decimal.Parse(node.InnerText);

            System.Data.SqlClient.SqlDataAdapter adapter;
            System.Data.SqlClient.SqlCommand     cmd;
            System.Data.SqlClient.SqlConnection  conn;
            string connString = (string)ConfigurationSettings.AppSettings["connectStringWoodgrove"];

            conn    = new System.Data.SqlClient.SqlConnection();
            adapter = new System.Data.SqlClient.SqlDataAdapter();
            cmd     = new System.Data.SqlClient.SqlCommand();

            //
            // cmd
            //
            // _EFTComplete(@acctID as int, @amt as money, @EFTTransactionID as uniqueidentifier, @confirmID as nvarchar(50) output)
            cmd.CommandText = "_EFTComplete";
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Connection  = conn;
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@RETURN_VALUE", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.ReturnValue, true, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@acctID", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, true, ((System.Byte)(10)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, acctID));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@amt", System.Data.SqlDbType.Money, 8, System.Data.ParameterDirection.Input, true, ((System.Byte)(0)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, amt));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@EFTTransactionID", System.Data.SqlDbType.UniqueIdentifier, 16, System.Data.ParameterDirection.Input, true, ((System.Byte)(0)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, transID));
            cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@confirmID", System.Data.SqlDbType.NVarChar, 50, System.Data.ParameterDirection.Output, true, ((System.Byte)(0)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));

            //
            // conn
            //
            conn.ConnectionString = connString;

            try
            {
                // Open connection, execute, close connection
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();

                EFTConfirmation eftConfirm = new EFTConfirmation();
                eftConfirm.confirmationNumber = cmd.Parameters["@confirmID"].Value.ToString();
                eftConfirm.amt           = amt;
                eftConfirm.transactionID = transID.ToString();
                Context.Trace.Write(string.Format("TransferFunds Acct:{0} Amt:{1}", acctID, amt));
                return(eftConfirm);
            }
            catch (Exception se)
            {
                Trace.WriteLine(se.Message);
                throw new SoapException(se.Message, null);
            }
        }
Ejemplo n.º 49
0
    private static System.Collections.Generic.HashSet <AkPluginInfo> ParsePluginsXML(string platform,
                                                                                     System.Collections.Generic.List <string> in_pluginFiles)
    {
        var newPlugins = new System.Collections.Generic.HashSet <AkPluginInfo>();

        foreach (var pluginFile in in_pluginFiles)
        {
            if (!System.IO.File.Exists(pluginFile))
            {
                continue;
            }

            try
            {
                var doc = new System.Xml.XmlDocument();
                doc.Load(pluginFile);
                var Navigator      = doc.CreateNavigator();
                var pluginInfoNode = Navigator.SelectSingleNode("//PluginInfo");
                var boolMotion     = pluginInfoNode.GetAttribute("Motion", "");

                var it = Navigator.Select("//Plugin");

                if (boolMotion == "true")
                {
                    AkPluginInfo motionPluginInfo = new AkPluginInfo();
                    motionPluginInfo.DllName = "AkMotion";
                    newPlugins.Add(motionPluginInfo);
                }

                foreach (System.Xml.XPath.XPathNavigator node in it)
                {
                    var rawPluginID = uint.Parse(node.GetAttribute("ID", ""));
                    if (rawPluginID == 0)
                    {
                        continue;
                    }

                    PluginID pluginID = (PluginID)rawPluginID;

                    if (alwaysSkipPluginsIDs.Contains(pluginID))
                    {
                        continue;
                    }

                    var dll = string.Empty;

                    if (platform == "Switch")
                    {
                        if (pluginID == PluginID.AkMeter)
                        {
                            dll = "AkMeter";
                        }
                    }
                    else if (builtInPluginIDs.Contains(pluginID))
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(dll))
                    {
                        dll = node.GetAttribute("DLL", "");
                    }

                    AkPluginInfo newPluginInfo = new AkPluginInfo();
                    newPluginInfo.PluginID = rawPluginID;
                    newPluginInfo.DllName  = dll;

                    if (!PluginIDToStaticLibName.TryGetValue(pluginID, out newPluginInfo.StaticLibName))
                    {
                        newPluginInfo.StaticLibName = dll;
                    }

                    newPlugins.Add(newPluginInfo);
                }
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError("WwiseUnity: " + pluginFile + " could not be parsed. " + ex.Message);
            }
        }

        return(newPlugins);
    }
Ejemplo n.º 50
0
        /// <summary>
        /// This method splits a k2 project in to multiple files.  One for each artifac.  The artifacts must be flagged as included in the original project, else they are omitted
        /// </summary>
        /// <param name="k2DeploymentFolder">The current temporary location of the files</param>
        /// <param name="k2ProjectFilePath">The current path to the original file to use</param>
        /// <returns></returns>
        private Dictionary <string, string> CreateProjectForEachProjectArtifact(string k2DeploymentFolder, string k2ProjectFilePath)
        {
            //stores a key value pair,  The key will be the name of the artifact and the value is the path to its k2project.
            Dictionary <string, string> dictFileNames = new Dictionary <string, string>();

            //stores the list of folders in the solution
            List <String> folders = new List <string>();
            //stores the list of artifacts in the solution.  The artifacts must be "included"
            List <String> k2Artifacts = new List <string>();

            //stores the list of un-necessary nodes "ItemGroup" that need to be removed.  For this solution we only need 2, one for the folders and one for the artifacts.
            List <System.Xml.XmlNode> oldNodes = new List <System.Xml.XmlNode>();

            //use xml to create each file.
            //Load the original file for manipulation
            System.Xml.XmlDocument origK2ProjXML = new System.Xml.XmlDocument();
            origK2ProjXML.Load(k2ProjectFilePath);


            //counter to track the number of ItemGroup nodes encountered
            int countItemGroups = 1;

            //loop through all of the notes in the Project document
            foreach (System.Xml.XmlNode child in origK2ProjXML.FirstChild.ChildNodes)
            {
                //especifically we are looking for the ItemGroup node.
                if (child.Name == "ItemGroup")
                {
                    if (countItemGroups > 2)
                    {
                        //we only need two
                        //add it to the list of oldNodes that will be removed.
                        oldNodes.Add(child);
                    }

                    //We need to get the list of folders and process that have been included by default
                    FillFolderAndProcessList(child, ref folders, ref k2Artifacts);
                    countItemGroups += 1;
                }
            }

            //remove any ItemGroup reference above the ones that are necessary
            foreach (System.Xml.XmlNode oldNode in oldNodes)
            {
                origK2ProjXML.FirstChild.RemoveChild(oldNode);
            }

            //For each k2Artifact included in the original project, we need to create its own project file.
            foreach (string artifact in k2Artifacts)
            {
                //this will be the new file name for this solution
                string fileName = string.Empty;
                //Get a cleansed name to be use as a subfolder later on.
                //Todo:Not sure if artifacts w/ the same name will cause problems
                string artifactName = GetProjectNameFromArtifactName(artifact);

                //Generate new ItemGroup Nodes, with the setting that we need.
                System.Xml.XmlElement foldersItemGroupNode  = CreateItemGroupFolderNode(folders, origK2ProjXML);
                System.Xml.XmlElement artifactItemGroupNode = CreateItemGroupContentNode(artifact, origK2ProjXML);

                //again, we have to count the ItemGroup nodes.
                //I couldn't get this to work otherwise. Creating a new document create other sideaffects.  Mainly each node is saved with an empty xmlns (namespace), which MSBuild did not like
                int itemCount = 1;

                //for each of the 2 nodes in the project file - reset the inner xml to the values we need.
                //Todo: look in to storing these nodes in a list in previous steps, then reset them here and just do a replace child node.
                foreach (System.Xml.XmlNode child in origK2ProjXML.FirstChild.ChildNodes)
                {
                    //especifically we are looking for the ItemGroup node.
                    if (child.Name == "ItemGroup")
                    {
                        if (itemCount == 1)
                        {
                            child.InnerXml = foldersItemGroupNode.InnerXml;
                        }
                        else
                        {
                            child.InnerXml = artifactItemGroupNode.InnerXml;
                        }
                        itemCount += 1;
                    }
                }

                //create a new file name for this artifact.
                fileName = k2DeploymentFolder + @"\" + artifactName + ".k2proj";

                //Save the project
                origK2ProjXML.Save(fileName);

                //track the name of the artifact and its corresponding project file
                dictFileNames.Add(artifactName, fileName);
            }

            return(dictFileNames);
        }
Ejemplo n.º 51
0
        private void HistoryForm_Load(object sender, EventArgs e)
        {
            this.Text   = "Tidigare fakturor";
            label2.Text = "Summa";
            label3.Text = "Netto: ";
            label4.Text = "Moms: ";
            label5.Text = "Brutto: ";

            listViewFakturor.View = View.Details;

            listViewFakturor.Width    = 800;
            listViewFakturor.Location = new System.Drawing.Point(10, 10);

            // Declare and construct the ColumnHeader objects.
            ColumnHeader header1, header2, header3, header4, header5, header6;

            header1 = new ColumnHeader();
            header2 = new ColumnHeader();
            header3 = new ColumnHeader();
            header4 = new ColumnHeader();
            header5 = new ColumnHeader();
            header6 = new ColumnHeader();

            // Set the text, alignment and width for each column header.
            header1.Text      = "ID";
            header1.TextAlign = HorizontalAlignment.Right;
            header1.Width     = 100;

            header2.TextAlign = HorizontalAlignment.Left;
            header2.Text      = "Datum";
            header2.Width     = 100;

            header3.TextAlign = HorizontalAlignment.Left;
            header3.Text      = "Kund";
            header3.Width     = 100;

            header4.TextAlign = HorizontalAlignment.Left;
            header4.Text      = "Netto";
            header4.Width     = 150;

            header5.TextAlign = HorizontalAlignment.Left;
            header5.Text      = "Moms";
            header5.Width     = 150;

            header6.TextAlign = HorizontalAlignment.Left;
            header6.Text      = "Brutto";
            header6.Width     = 150;


            listViewFakturor.Columns.Clear();
            // Add the headers to the ListView control.
            listViewFakturor.Columns.Add(header1);
            listViewFakturor.Columns.Add(header2);
            listViewFakturor.Columns.Add(header3);
            listViewFakturor.Columns.Add(header4);
            listViewFakturor.Columns.Add(header5);
            listViewFakturor.Columns.Add(header6);

            string path = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\data\fakturor.xml";

            listViewFakturor.Items.Clear();
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(path);
            System.Xml.XmlNodeList elemList = doc.GetElementsByTagName("faktura");

            if (elemList != null)
            {
                int tempi = 0;
                for (int i = 0; i < elemList.Count; i++)
                {
                    string attrVal  = elemList[i].Attributes["ID"].Value;
                    string attrVal2 = elemList[i].Attributes["Date"].Value;
                    string attrVal3 = elemList[i].Attributes["Kund"].Value;
                    string attrVal4 = elemList[i].Attributes["Netto"].Value;
                    string attrVal5 = elemList[i].Attributes["Moms"].Value;
                    string attrVal6 = elemList[i].Attributes["Brutto"].Value;

                    listViewFakturor.Items.Add(attrVal);
                    listViewFakturor.Items[i].SubItems.Add(attrVal2);
                    listViewFakturor.Items[i].SubItems.Add(attrVal3);
                    listViewFakturor.Items[i].SubItems.Add(attrVal4);
                    listViewFakturor.Items[i].SubItems.Add(attrVal5);
                    listViewFakturor.Items[i].SubItems.Add(attrVal6);
                    tempi = i;
                    // MessageBox.Show(attrVal);
                }


                decimal gtotal1 = 0;
                decimal gtotal2 = 0;
                decimal gtotal3 = 0;
                foreach (ListViewItem lstItem in listViewFakturor.Items)
                {
                    gtotal1 += decimal.Parse(lstItem.SubItems[3].Text);
                    gtotal2 += decimal.Parse(lstItem.SubItems[4].Text);
                    gtotal3 += decimal.Parse(lstItem.SubItems[5].Text);
                }

                label3.Text += gtotal1.ToString("0,0.00") + " kr";
                label4.Text += gtotal2.ToString("0,0.00") + " kr";
                label5.Text += gtotal3.ToString("0,0.00") + " kr";
            }
        }
Ejemplo n.º 52
0
    public static bool Populate()
    {
        if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode || UnityEditor.EditorApplication.isCompiling)
        {
            return(false);
        }

        try
        {
            // Try getting the SoundbanksInfo.xml file for Windows or Mac first, then try to find any other available platform.
            var logWarnings = AkBasePathGetter.LogWarnings;
            AkBasePathGetter.LogWarnings = false;
            var FullSoundbankPath = AkBasePathGetter.GetPlatformBasePath();
            AkBasePathGetter.LogWarnings = logWarnings;

            var filename = System.IO.Path.Combine(FullSoundbankPath, "SoundbanksInfo.xml");
            if (!System.IO.File.Exists(filename))
            {
                FullSoundbankPath = System.IO.Path.Combine(UnityEngine.Application.streamingAssetsPath, AkWwiseEditorSettings.Instance.SoundbankPath);

                if (!System.IO.Directory.Exists(FullSoundbankPath))
                {
                    UnityEngine.Debug.Log("WwiseUnity: Could not open SoundbanksInfo.xml, generated SoundBanks path does not exist: " + FullSoundbankPath);
                    return(false);
                }

                var foundFiles = System.IO.Directory.GetFiles(FullSoundbankPath, "SoundbanksInfo.xml", System.IO.SearchOption.AllDirectories);
                if (foundFiles.Length == 0)
                {
                    UnityEngine.Debug.Log("WwiseUnity: Could not find SoundbanksInfo.xml in directory: " + FullSoundbankPath);
                    return(false);
                }
                filename = foundFiles[0];
            }

            var time = System.IO.File.GetLastWriteTime(filename);
            if (time <= s_LastParsed)
            {
                UnityEngine.Debug.Log("WwiseUnity: Skipping parsing of SoundbanksInfo.xml because it has not changed.");
                return(false);
            }

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

            var bChanged   = false;
            var soundBanks = doc.GetElementsByTagName("SoundBanks");
            for (var i = 0; i < soundBanks.Count; i++)
            {
                var soundBank = soundBanks[i].SelectNodes("SoundBank");
                for (var j = 0; j < soundBank.Count; j++)
                {
                    bChanged = SerialiseSoundBank(soundBank[j]) || bChanged;
                }
            }

            return(bChanged);
        }
        catch (System.Exception e)
        {
            UnityEngine.Debug.Log("WwiseUnity: Exception occured while parsing SoundbanksInfo.xml: " + e.ToString());
            return(false);
        }
    }
Ejemplo n.º 53
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 (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 (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.º 54
0
 ///<summary>
 ///
 ///</summary>
 protected virtual void FetchXML(System.String XmlFile)
 {
     System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument();
     XmlDoc.Load(XmlFile);
     this.FetchXML(XmlDoc);
 }
Ejemplo n.º 55
0
        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        public override int DeleteProfiles(string[] usernames)
        {
            if (usernames == null || usernames.Length < 1)
            {
                return(0);
            }

            int  numProfilesDeleted = 0;
            bool beginTranCalled    = false;

            try {
                SqlConnection conn = null;
                try {
                    if (String.IsNullOrEmpty(this._sqlConnectionString) || this._sqlConnectionString == "foo")
                    {
                        //Create the XmlDocument.
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                        doc.Load(HttpContext.Current.Server.MapPath("/web.config"));

                        //Display all the book titles.
                        System.Xml.XmlNodeList elemList = doc.GetElementsByTagName("connectionStrings");
                        this._sqlConnectionString = elemList[0].ChildNodes[0].Attributes["connectionString"].Value;
                    }


                    conn = new SqlConnection(_sqlConnectionString);
                    conn.Open();

                    SqlCommand cmd;
                    int        numUsersRemaing = usernames.Length;
                    while (numUsersRemaing > 0)
                    {
                        cmd = new SqlCommand(String.Empty, conn);
                        cmd.Parameters.AddWithValue("@UserName0", usernames[usernames.Length - numUsersRemaing]);
                        StringBuilder allUsers = new StringBuilder("@UserName0");
                        numUsersRemaing--;

                        int userIndex = 1;
                        for (int iter = usernames.Length - numUsersRemaing; iter < usernames.Length; iter++)
                        {
                            // REVIEW: Should we check length of command string instead of parameter lengths?
                            if (allUsers.Length + usernames[iter].Length + 3 >= 4000)
                            {
                                break;
                            }
                            string userNameParam = "@UserName" + userIndex;
                            allUsers.Append(",");
                            allUsers.Append(userNameParam);
                            cmd.Parameters.AddWithValue(userNameParam, usernames[iter]);
                            numUsersRemaing--;
                            ++userIndex;
                        }

                        // We don't need to start a transaction if we can finish this in one sql command
                        if (!beginTranCalled && numUsersRemaing > 0)
                        {
                            SqlCommand beginCmd = new SqlCommand("BEGIN TRANSACTION", conn);
                            beginCmd.ExecuteNonQuery();
                            beginTranCalled = true;
                        }


                        cmd.CommandText     = "DELETE FROM " + _table + " WHERE UserId IN ( SELECT u.UserId FROM vw_aspnet_Users u WHERE u.ApplicationId = '" + AppId + "' AND u.UserName IN (" + allUsers.ToString() + "))";
                        cmd.CommandTimeout  = CommandTimeout;
                        numProfilesDeleted += cmd.ExecuteNonQuery();
                    }

                    if (beginTranCalled)
                    {
                        cmd = new SqlCommand("COMMIT TRANSACTION", conn);
                        cmd.ExecuteNonQuery();
                        beginTranCalled = false;
                    }
                }
                catch {
                    if (beginTranCalled)
                    {
                        SqlCommand cmd = new SqlCommand("ROLLBACK TRANSACTION", conn);
                        cmd.ExecuteNonQuery();
                        beginTranCalled = false;
                    }
                    throw;
                }
                finally {
                    if (conn != null)
                    {
                        conn.Close();
                        conn = null;
                    }
                }
            }
            catch {
                throw;
            }
            return(numProfilesDeleted);
        }
Ejemplo n.º 56
0
        public List <IFileEntry> List()
        {
            var doc = new System.Xml.XmlDocument();

            try
            {
                // Send request and load XML response.
                var req  = CreateRequest(System.Net.WebRequestMethods.Http.Get, "", "", false);
                var areq = new Utility.AsyncHttpRequest(req);
                using (var resp = (System.Net.HttpWebResponse)areq.GetResponse())
                    using (var rs = areq.GetResponseStream())
                        doc.Load(rs);
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    throw new FolderMissingException(wex);
                }
                throw;
            }
            // Handle XML response. Since we in the constructor demand a folder below the mount point we know the root
            // element must be a "folder", else it could also have been a "mountPoint" (which has a very similar structure).
            // We must check for "deleted" attribute, because files/folders which has it is deleted (attribute contains the timestamp of deletion)
            // so we treat them as non-existant here.
            List <IFileEntry> files = new List <IFileEntry>();
            var xRoot = doc.DocumentElement;

            if (xRoot.Attributes["deleted"] != null)
            {
                throw new FolderMissingException();
            }
            foreach (System.Xml.XmlNode xFolder in xRoot.SelectNodes("folders/folder[not(@deleted)]"))
            {
                // Subfolders are only listed with name. We can get a timestamp by sending a request for each folder, but that is probably not necessary?
                FileEntry fe = new FileEntry(xFolder.Attributes["name"].Value);
                fe.IsFolder = true;
                files.Add(fe);
            }
            foreach (System.Xml.XmlNode xFile in xRoot.SelectNodes("files/file[not(@deleted)]"))
            {
                string name = xFile.Attributes["name"].Value;
                // Normal files have an "currentRevision", which represent the most recent successfully upload
                // (could also checked that currentRevision/state is "COMPLETED", but should not be necessary).
                // There might also be a newer "latestRevision" coming from an incomplete or corrupt upload,
                // but we ignore that here and use the information about the last valid version.
                System.Xml.XmlNode xRevision = xFile.SelectSingleNode("currentRevision");
                if (xRevision != null)
                {
                    System.Xml.XmlNode xNode = xRevision.SelectSingleNode("state");
                    if (xNode.InnerText == "COMPLETED") // Think "currentRevision" always is a complete version, but just to be on the safe side..
                    {
                        xNode = xRevision.SelectSingleNode("size");
                        long size;
                        if (xNode == null || !long.TryParse(xNode.InnerText, out size))
                        {
                            size = -1;
                        }
                        DateTime lastModified;
                        xNode = xRevision.SelectSingleNode("modified"); // There is created, modified and updated time stamps, but not last accessed.
                        if (xNode == null || !DateTime.TryParseExact(xNode.InnerText, JFS_DATE_FORMAT, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out lastModified))
                        {
                            lastModified = new DateTime();
                        }
                        FileEntry fe = new FileEntry(name, size, lastModified, lastModified);
                        files.Add(fe);
                    }
                }
            }
            return(files);
        }
Ejemplo n.º 57
0
        public twmKDS_EXPXML()
        {
            try
            {
                //Draw the form
                String sFileName = string.Format("{0}.xml", this.GetType().Name);
                bool   bSuccess  = true;
                if (System.IO.File.Exists(Environment.CurrentDirectory + "\\" + sFileName))
                {
                    System.Xml.XmlDocument oXml = new System.Xml.XmlDocument();
                    oXml.Load(Environment.CurrentDirectory + "\\" + sFileName);
                    String sXml = eCommon.ModifySize(oXml.InnerXml);
                    try
                    {
                        eCommon.SBO_Application.LoadBatchActions(ref sXml);
                    }
                    catch
                    {
                        bSuccess = false;
                    }
                }
                else
                {
                    String ResourceName = string.Format("{0}.Src.Resource.{1}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name, sFileName);

                    String sXml = eCommon.ModifySize(eCommon.GetXMLResource(ResourceName));
                    try
                    {
                        eCommon.SBO_Application.LoadBatchActions(ref sXml);
                    }
                    catch {
                        bSuccess = false;
                    }
                }

                if (bSuccess)
                {
                    _oForm = eCommon.SBO_Application.Forms.ActiveForm;
                    if (_oForm.TypeEx.StartsWith("-"))
                    {
                        //a UDF form is opened. Close it.
                        String UDFFormUID    = _oForm.UniqueID;
                        String ParentFormUID = eCommon.GetParentFormUID(_oForm);
                        _oForm.Close();

                        _oForm = eCommon.SBO_Application.Forms.ActiveForm;
                        if (_oForm.UniqueID != ParentFormUID)
                        {
                            _oForm = eCommon.SBO_Application.Forms.Item(ParentFormUID);
                        }
                    }
                    _oForm.EnableMenu("6913", false);

                    GetItemReferences();
                    // Initform can be use if you want to fill anything or color anything
                    InitForm();
                    if (!SBOAddon.oOpenForms.Contains(_oForm.UniqueID))
                    {
                        SBOAddon.oOpenForms.Add(_oForm.UniqueID, this);
                    }

                    _oForm.Visible = true;
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 58
0
    // For a list of platform targets, gather all the required folder names for the generated soundbanks. The goal is to know the list of required
    // folder names for a list of platforms. The size of the returned array is not guaranteed to be the safe size at the targets array since
    // a single platform is no guaranteed to output a single soundbank folder.
    public static bool GetWwiseSoundBankDestinationFoldersByUnityPlatform(UnityEditor.BuildTarget target,
                                                                          string WwiseProjectPath, out string[] paths, out string[] platformNames)
    {
        paths         = null;
        platformNames = null;

        try
        {
            if (WwiseProjectPath.Length == 0)
            {
                return(false);
            }

            var doc = new System.Xml.XmlDocument();
            doc.Load(WwiseProjectPath);
            var configNavigator = doc.CreateNavigator();

            var pathsList         = new System.Collections.Generic.List <string>();
            var platformNamesList = new System.Collections.Generic.List <string>();

            if (platformMapping.ContainsKey(target))
            {
                var referencePlatforms = platformMapping[target];

                // For each valid reference platform name for the provided Unity platform enum, list all the valid platform names
                // defined in the Wwise project XML, and for each of those accumulate the sound bank folders. In the end,
                // resultList will contain a list of soundbank folders that are generated for the provided unity platform enum.

                foreach (var reference in referencePlatforms)
                {
                    var expression =
                        System.Xml.XPath.XPathExpression.Compile(string.Format("//Platforms/Platform[@ReferencePlatform='{0}']",
                                                                               reference));
                    var nodes = configNavigator.Select(expression);

                    while (nodes.MoveNext())
                    {
                        var platform = nodes.Current.GetAttribute("Name", "");

                        // If the sound bank path information was located either in the user configuration or the project configuration, acquire the paths
                        // for the provided platform.
                        string sbPath = null;
                        if (s_ProjectBankPaths.TryGetValue(platform, out sbPath))
                        {
#if UNITY_EDITOR_OSX
                            sbPath = sbPath.Replace('\\', System.IO.Path.DirectorySeparatorChar);
#endif
                            pathsList.Add(sbPath);
                            platformNamesList.Add(platform);
                        }
                    }
                }
            }

            if (pathsList.Count != 0)
            {
                paths         = pathsList.ToArray();
                platformNames = platformNamesList.ToArray();
                return(true);
            }
        }
        catch (System.Exception e)
        {
            UnityEngine.Debug.LogException(e);
        }

        return(false);
    }
Ejemplo n.º 59
0
 public void FileTest_LinkXml()
 {
     System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
     xDoc.Load("ConfigurationTestSettings.xml");
 }
Ejemplo n.º 60
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);
        }
        catch (System.Exception)
        {
            return(false);
        }

        return(true);
    }