Ejemplo n.º 1
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.º 2
0
        static void Main(string[] args)
        {
            var postdata = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName>"+
                "<![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime>"+
                "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Stone]]></Content></xml> ";
            if (!string.IsNullOrWhiteSpace(postdata))
            {
                System.Xml.XmlDocument postObj = new System.Xml.XmlDocument();
                postObj.LoadXml(postdata);
                var FromUserNameList = postObj.GetElementsByTagName("FromUserName");
                string FromUserName = string.Empty;
                for (int i = 0; i < FromUserNameList.Count; i++)
                {
                    if (FromUserNameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
                    {
                        FromUserName = FromUserNameList[i].ChildNodes[0].Value;
                    }
                }
                var toUsernameList = postObj.GetElementsByTagName("ToUserName");
                string ToUserName = string.Empty;
                for (int i = 0; i < toUsernameList.Count; i++)
                {
                    if (toUsernameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
                    {
                        ToUserName = toUsernameList[i].ChildNodes[0].Value;
                    }
                }
                var keywordList = postObj.GetElementsByTagName("Content");
                string Content = string.Empty;
                for (int i = 0; i < keywordList.Count; i++)
                {
                    if (keywordList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
                    {
                        Content = keywordList[i].ChildNodes[0].Value;
                    }
                }
                var time = DateTime.Now;
                var textpl = "<xml><ToUserName><![CDATA[" + ToUserName + "]]></ToUserName>" +
                    "<FromUserName><![CDATA[" + FromUserName + "]]></FromUserName>" +
                    "<CreateTime>" + time + "</CreateTime><MsgType><![CDATA[text]]></MsgType>" +
                    "<Content><![CDATA[Welcome to wechat world!"+Content+"]]></Content><FuncFlag>0</FuncFlag></xml> ";
                Console.WriteLine(textpl);
            }

            var codelist = new List<string>() { "faketoken", "bbb", "12345678" };
            Console.WriteLine(GetSha1(codelist));
            Console.ReadLine();
        }
        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();
        }
        protected void loadXml()
        {
            var xml = new System.Xml.XmlDocument();
            var fs = new System.IO.FileStream("wardrive.xml", System.IO.FileMode.Open);
            xml.Load(fs);
            allSamples = new List<Sample>();
            WPA2Samples = new List<Sample>();
            WEPSamples = new List<Sample>();
            WPASamples = new List<Sample>();
            OpenSamples = new List<Sample>();
            string[] stringSeparators = new string[] { "<br/>" };
            string[] descrSplit;
     
            var list = xml.GetElementsByTagName("Placemark");
            for (var i = 0; i < list.Count; i++)
            {
                var tempSample = new Sample();
                var descr = xml.GetElementsByTagName("description")[i].InnerText;

                descrSplit = descr.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                tempSample.ssid = Regex.Replace(descrSplit[0], @"<[^>]+>|&nbsp;", "").Trim();
                tempSample.ssid = tempSample.ssid.Replace("SSID: ", "");
                tempSample.bssid = Regex.Replace(descrSplit[1], @"<[^>]+>|&nbsp;", "").Trim();
                tempSample.bssid = tempSample.bssid.Replace("BSSID: ", "");
                tempSample.crypt = Regex.Replace(descrSplit[2], @"<[^>]+>|&nbsp;", "").Trim();
                tempSample.crypt = tempSample.crypt.Replace("Crypt: ", "");
                if (tempSample.crypt == "WPA2") { WPA2Samples.Add(tempSample); }
                else if (tempSample.crypt == "WpaPsk") { WPASamples.Add(tempSample); }
                else if (tempSample.crypt == "Wep") { WEPSamples.Add(tempSample); }
                else if (tempSample.crypt == "Open") { OpenSamples.Add(tempSample); }
                tempSample.channel = Regex.Replace(descrSplit[3], @"<[^>]+>|&nbsp;", "").Trim();
                tempSample.channel = tempSample.channel.Replace("Channel: ", "");
                tempSample.level = Regex.Replace(descrSplit[4], @"<[^>]+>|&nbsp;", "").Trim();
                tempSample.level = tempSample.level.Replace("Level: ", "");
                tempSample.lastupdate = Regex.Replace(descrSplit[5], @"<[^>]+>|&nbsp;", "").Trim();
                tempSample.lastupdate = tempSample.lastupdate.Replace("Last Update: ", "");
                tempSample.style = xml.GetElementsByTagName("styleUrl")[i].InnerText;
                tempSample.coord = xml.GetElementsByTagName("coordinates")[i].InnerText;
                allSamples.Add(tempSample);
            }
            textBlock1.Text = ""+list.Count+" samples";
            textBlock1.Text += "\nWPA2: " + WPA2Samples.Count + " samples ("+WPA2Samples.Count/(list.Count/100)+"%)";
            textBlock1.Text += "\nWPA: " + WPASamples.Count + " samples (" + WPASamples.Count / (list.Count / 100) + "%)";
            textBlock1.Text += "\nWEP: " + WEPSamples.Count + " samples (" + WEPSamples.Count / (list.Count / 100) + "%)";
            textBlock1.Text += "\nOpen: " + OpenSamples.Count + " samples (" + OpenSamples.Count / (list.Count / 100) + "%)";
            fs.Close();
        }
Ejemplo n.º 6
0
		public StreamInfo GetVideoMedatada()
		{
			StreamInfo sinfo = new StreamInfo();

			sinfo.Author = GetCanonicalUrl();
			sinfo.Title = GetCanonicalUrl();

			if (localInitData.Config.GetBoolean(ConfigurationConstants.ApiInternetAccess,
				true, false))
			{
				try
				{
					// pobieramy informacje o video
					string yt_url = GetCanonicalUrl();
					string oembed = "http://www.youtube.com/oembed";

					{
						var qstr = HttpUtility.ParseQueryString(string.Empty);
						qstr["url"] = yt_url;
						qstr["format"] = "xml";

						oembed += "?" + qstr.ToString();
					}

					WebRequest wr = WebRequest.Create(oembed);
					WebResponse wre = wr.GetResponse();
					Stream data = wre.GetResponseStream();

					System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
					xmldoc.Load(data);
					data.Close();

					sinfo.Author = xmldoc.GetElementsByTagName("author_name")[0].InnerText;
					sinfo.Title = xmldoc.GetElementsByTagName("title")[0].InnerText;
					sinfo.CanonicalUrl = GetCanonicalUrl();
				}
				catch (Exception)
				{
					sinfo.Author = "Unknown author";
					sinfo.Title = "Unknown title";
					sinfo.CanonicalUrl = GetCanonicalUrl();
				}
			}

			return sinfo;
		}
Ejemplo n.º 7
0
        void Subscribers(Stats stats)
        {
            if (!Security.IsAuthorizedTo(BlogEngine.Core.Rights.AccessAdminPages))
                throw new System.UnauthorizedAccessException();

            string filename = System.IO.Path.Combine(Blog.CurrentInstance.StorageLocation, "newsletter.xml");
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(System.Web.Hosting.HostingEnvironment.MapPath(filename));
            System.Xml.XmlNodeList list = doc.GetElementsByTagName("email");
            stats.SubscribersCount += (list.Count).ToString();
        }
Ejemplo n.º 8
0
 /// <summary>
 /// 读取Config参数
 /// </summary>
 public static string ReadConfig(string name, string key)
 {
     System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
     xd.Load(HttpContext.Current.Server.MapPath(name + ".config"));
     System.Xml.XmlNodeList xnl = xd.GetElementsByTagName(key);
     if (xnl.Count == 0)
         return "";
     else
     {
         System.Xml.XmlNode mNode = xnl[0];
         return mNode.InnerText;
     }
 }
Ejemplo n.º 9
0
        public IList<Template> GetTemplates()
        {
            IList<Template> list = new List<Template>();
            Directory.GetDirectories(WebPathManager.TemplateUrl).ToList().ForEach(s =>
            {
                string dir = string.Format("{0}{1}\\", WebPathManager.TemplateUrl, s);
                var xml = new System.Xml.XmlDocument();
                xml.LoadXml(string.Format("{0}config.xml", dir));
                var node = xml.GetElementsByTagName("template")[0];
                list.Add(new Template { Name = node.Attributes["name"].Value, Url = dir, ContentUrl = node.Attributes["contentfolder"].Value, TempImage = this.GetTempImage(dir, s) });
            });

            return list;
        }
Ejemplo n.º 10
0
 /// <summary>
 /// 保存Config参数
 /// </summary>
 public static void UpdateConfig(string name, string nKey, string nValue)
 {
     if (ReadConfig(name, nKey) != "")
     {
         System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument();
         XmlDoc.Load(HttpContext.Current.Server.MapPath(name + ".config"));
         System.Xml.XmlNodeList elemList = XmlDoc.GetElementsByTagName(nKey);
         System.Xml.XmlNode mNode = elemList[0];
         mNode.InnerText = nValue;
         System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(name + ".config")));
         xw.Formatting = System.Xml.Formatting.Indented;
         XmlDoc.WriteTo(xw);
         xw.Close();
     }
 }
Ejemplo n.º 11
0
 public IDictionary<string, string> GetSummariesFromText(string text)
 {
     var xml = new System.Xml.XmlDocument();
     xml.LoadXml(text);
     var members = xml.GetElementsByTagName("members");
     var member = members.Item(0).ChildNodes;
     Dictionary<string,string> doc = new Dictionary<string, string>();
     foreach (System.Xml.XmlNode m in member)
     {
         var attr = m.Attributes;
         var name = attr.GetNamedItem("name");
         var nodes = m.ChildNodes.Cast<System.Xml.XmlNode>();
         var summary = nodes.FirstOrDefault(x=>x.Name.Equals("summary"));
         if (null!=summary)
             doc.Add(name.InnerText,summary.InnerText.Trim());
     }
     return doc;
 }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            WeatherService.GlobalWeather obj = new WeatherService.GlobalWeather();

            string city = "Chattanooga";
            string country = "United States";

            System.Xml.XmlDocument xdox = new System.Xml.XmlDocument();
            xdox.LoadXml(obj.GetWeather(city, country));
            System.Xml.XmlNodeList nodeList = xdox.GetElementsByTagName("CurrentWeather");
            foreach (System.Xml.XmlNode node in nodeList)
            {
                foreach (System.Xml.XmlNode childNode in node)
                {
                    Console.WriteLine(childNode.ChildNodes.Item(0).InnerText.Trim());
                }
            }
        }
Ejemplo n.º 13
0
        private static WebSettingItem InitDefaultConfig()
        {
            WebSettingItem _default;

            System.Xml.XmlDocument _document = new System.Xml.XmlDocument();
            //<SiteUrl>self</SiteUrl>
            _document.LoadXml(@"<WebSettingCollection>
                                    <WebSetting>
                                        <Compatible>False</Compatible>
                                        <Theme>default</Theme>
                                        <Encoding>UTF-8</Encoding>
                                        <SessionOutTime>30</SessionOutTime>
                                        <EncryptKey>THISISXYFRAMEENCRYPTKEY</EncryptKey>
                                        <EncryptIV>VITPYRCNEEMARYXSISIHT</EncryptIV>
                                        <XySessionId>XyFrameSessionId</XySessionId>
                                        <DebugMode>False</DebugMode>
                                    </WebSetting>
                                </WebSettingCollection>");
            System.Xml.XmlNode _node = _document.GetElementsByTagName("WebSetting")[0];
            _default = new WebSettingItem(_node);
            _default.Init(_node);
            return(_default);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Detects if a message is a delivery failure notification.
        /// This method uses the default signatures containing in an internal ressource file.
        /// </summary>
        /// <remarks>
        /// Signature files are XML files formatted as follows :
        ///
        /// &lt;?xml version='1.0'?&gt;
        /// &lt;signatures&gt;
        ///		&lt;signature from=&quot;postmaster&quot; subject=&quot;Undeliverable Mail&quot; body=&quot;Unknown user&quot; search=&quot;&quot; />
        ///		...
        /// &lt;/signatures&gt;
        /// </remarks>
        /// <returns>A BounceStatus object containing the level of revelance and if 100% identified, the erroneous email address.</returns>
        public BounceResult GetBounceStatus(string signaturesFilePath)
        {
            string ressource = string.IsNullOrEmpty(signaturesFilePath) ? Header.GetResource("ActiveUp.Net.Common.bouncedSignatures.xml") : System.IO.File.OpenText(signaturesFilePath).ReadToEnd();
            var    doc       = new System.Xml.XmlDocument();

            doc.LoadXml(ressource);
            var result = new BounceResult();

            foreach (System.Xml.XmlElement el in doc.GetElementsByTagName("signature"))
            {
                if (this.From.Merged.IndexOf(el.GetElementsByTagName("from")[0].InnerText) != -1)
                {
                    result.Level++;
                }

                if (this.Subject != null && this.Subject.IndexOf(el.GetElementsByTagName("subject")[0].InnerText) != -1)
                {
                    result.Level++;
                }
            }

            return(result);
        }
Ejemplo n.º 15
0
        public static string ExtractExceptionMessageFromXml(string XmlDoc)
        {
            try
            {
                string retVal = string.Empty;

                //Create an XMLDocument and Load the XML String
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(XmlDoc);
                System.Xml.XmlNodeList nodeList = doc.GetElementsByTagName("message");
                for (int i = 0; i < nodeList.Count; i++)
                {
                    retVal = retVal + nodeList[i].InnerXml;
                }

                return(retVal);
            }
            catch
            {
                //Just return the original string
                return(XmlDoc);
            }
        }
Ejemplo n.º 16
0
        void btnAboutVmukti_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                cnvUploadGeneral.Visibility = Visibility.Collapsed;
                cnvUploadMod.Visibility     = Visibility.Collapsed;
                cnvPBX.Visibility           = Visibility.Collapsed;
                cnvHelp.Visibility          = Visibility.Collapsed;
                cnvProfile.Visibility       = Visibility.Collapsed;
                cnvSkin.Visibility          = Visibility.Collapsed;
                cnvVMuktiVersion.Visibility = Visibility.Collapsed;
                cnvAboutVmukti.Visibility   = Visibility.Visible;

                btnAboutVmukti.IsChecked   = true;
                btnSkin.IsChecked          = false;
                btnProfile.IsChecked       = false;
                btnGeneral.IsChecked       = false;
                btnAddMod.IsChecked        = false;
                btnPBX.IsChecked           = false;
                btnHelp.IsChecked          = false;
                btnVMuktiVersion.IsChecked = false;



                System.Xml.XmlDocument ConfDoc = new System.Xml.XmlDocument();
                ConfDoc.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlceds35.dll");
                if (ConfDoc != null)
                {
                    System.Xml.XmlNodeList xmlNodes = null;
                    xmlNodes = ConfDoc.GetElementsByTagName("CurrentVersion");
                    tblVersionNumbre.Text = DecodeBase64String(xmlNodes[0].Attributes["Value"].Value.ToString());
                }
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 17
0
        private static void LoadSettings(System.Xml.XmlDocument xmlDocument, Models.Project project)
        {
            foreach (System.Xml.XmlNode node in xmlDocument.GetElementsByTagName("Settings"))
            {
                string ApplicationIcon           = node.Attributes["ApplicationIcon"].Value;
                string AssemblyKeyContainerName  = node.Attributes["AssemblyKeyContainerName"].Value;
                string AssemblyName              = node.Attributes["AssemblyName"].Value;
                string AssemblyOriginatorKeyFile = node.Attributes["AssemblyOriginatorKeyFile"].Value;
                string DefaultClientScript       = node.Attributes["DefaultClientScript"].Value;
                string DefaultHTMLPageLayout     = node.Attributes["DefaultHTMLPageLayout"].Value;
                string DefaultTargetSchema       = node.Attributes["DefaultTargetSchema"].Value;
                string DelaySign         = node.Attributes["DelaySign"].Value;
                string OutputType        = node.Attributes["OutputType"].Value;
                string PreBuildEvent     = node.Attributes["PreBuildEvent"].Value;
                string PostBuildEvent    = node.Attributes["PostBuildEvent"].Value;
                string RootNamespace     = node.Attributes["RootNamespace"].Value;
                string RunPostBuildEvent = node.Attributes["RunPostBuildEvent"].Value;
                string StartupObject     = node.Attributes["StartupObject"].Value;

                Models.Settings settings = new Models.Settings();
                settings.ApplicationIcon           = ApplicationIcon;
                settings.AssemblyKeyContainerName  = AssemblyKeyContainerName;
                settings.AssemblyName              = AssemblyName;
                settings.AssemblyOriginatorKeyFile = AssemblyOriginatorKeyFile;
                settings.DefaultClientScript       = DefaultClientScript;
                settings.DefaultHTMLPageLayout     = DefaultHTMLPageLayout;
                settings.DefaultTargetSchema       = DefaultTargetSchema;
                settings.DelaySign         = DelaySign;
                settings.OutputType        = OutputType;
                settings.PreBuildEvent     = PreBuildEvent;
                settings.PostBuildEvent    = PostBuildEvent;
                settings.RootNamespace     = RootNamespace;
                settings.RunPostBuildEvent = RunPostBuildEvent;
                settings.StartupObject     = StartupObject;
                project.Settings           = settings;
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 从配置文件加载配置
        /// </summary>
        /// <param name="fileName">配置文件名</param>
        public virtual void LoadConfig(String fileName)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            try
            {
                doc.Load(fileName);

                System.Xml.XmlNodeList list = doc.GetElementsByTagName("Item");

                System.Xml.XmlAttribute itemName = null;

                foreach (System.Xml.XmlNode node in list)
                {
                    try
                    {
                        itemName = node.Attributes["Name"];
                        System.Xml.XmlAttribute value = node.Attributes["Value"];
                        if (itemName == null || value == null)
                        {
                            continue;
                        }

                        PropertyInfo pi = GetType().GetProperty(itemName.Value);
                        pi.SetValue(this, Convert(value.Value, pi.PropertyType), null);
                    }
                    catch (Exception e1)
                    {
                        WriteLog(String.Format("Load Item={0} fail, errmsg:{1}",
                                               itemName.Value, e1.Message));
                    }
                }
            }
            catch (Exception e)
            {
                WriteLog(String.Format("Load config fail, errmsg:{0}", e.Message));
            }
        }
Ejemplo n.º 19
0
 private string GetASP_NETaccountName()
 {
     try
     {
         System.Xml.XmlDocument machineConfig = new System.Xml.XmlDocument();
         string runtimePath = RuntimeEnvironment.GetRuntimeDirectory();
         string configPath  = Path.Combine(runtimePath, @"CONFIG\machine.config");
         machineConfig.Load(configPath);
         System.Xml.XmlNodeList elemList = machineConfig.GetElementsByTagName("processModel");
         for (int i = 0; i < elemList.Count; i++)
         {
             System.Xml.XmlAttributeCollection attributes        = elemList[i].Attributes;
             System.Xml.XmlAttribute           userNameAttribute = attributes["userName"];
             if (userNameAttribute != null)
             {
                 string userName = userNameAttribute.InnerText;
                 if (userName == "machine")
                 {
                     return("ASPNET");
                 }
                 else if (userName == "SYSTEM")
                 {
                     return(null);
                 }
                 else
                 {
                     return(userName);
                 }
             }
         }
     }
     catch
     {
         // swallow all exceptions here
     }
     return("ASPNET");
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Multiplication of XAML
 /// </summary>
 /// <param name="filename">XAML filename</param>
 /// <param name="scale">Multiplication scale</param>
 public static void Multiply(string filename, double scale)
 {
     char[] sep = " ".ToCharArray();
     char[] sep1 = ",".ToCharArray();
     System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
     doc.Load(filename);
     System.Xml.XmlNodeList nl = doc.GetElementsByTagName("MeshGeometry3D");
     foreach (System.Xml.XmlElement e in nl)
     {
         string s = "";
         string pos = e.GetAttribute("Positions");
         string[] pp = pos.Split(sep);
         foreach (string spp in pp)
         {
             if (spp.Length == 0)
             {
                 continue;
             }
             string[] ppp = spp.Split(sep1);
             int i = 0;
             foreach (string sppp in ppp)
             {
                 s += ((Double.Parse(sppp.Replace(".", ",")) * scale) + "").Replace(",", ".");
                 if (i < 2)
                 {
                     s += ",";
                 }
                 ++i;
             }
             s += " ";
         }
         e.SetAttribute("Positions", s);
     }
     System.IO.File.Delete(filename);
     doc.Save(filename);
 }
Ejemplo n.º 21
0
        public static string getXMLConfigVersion(string xmlconfigstring)
        {
            string r = "";

            try
            {
                System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
                xdoc.LoadXml(xmlconfigstring);
                System.Xml.XmlNodeList nodes = xdoc.GetElementsByTagName("CONFIGVERSION");
                if (nodes.Count > 0)
                {
                    try
                    {
                        r = nodes[0].Attributes["value"].Value;
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                statlog.log("loadConfigfile, parse config: " + ex.Message);
            }
            return(r);
        }
Ejemplo n.º 22
0
        private void LoadFolders()
        {
            // Clear items first
            lvPublishedFolders.Items.Clear();

            System.Xml.XmlDocument objXmlDocument = new System.Xml.XmlDocument();
            // Load XML
            objXmlDocument.Load(@".\Data\PublishedFolders.xml");
            // Get all Folders Tag
            System.Xml.XmlNodeList objXmlNodeList = objXmlDocument.GetElementsByTagName("Folder");

            // Iterate
            foreach (System.Xml.XmlNode item in objXmlNodeList)
            {
                string Name = item.Attributes["Name"].Value;
                string Status = item.Attributes["Status"].Value;
                string Path = item.Attributes["Path"].Value;

                // Create a Item for ListItem
                ListViewItem objListViewItem = new ListViewItem(new string[] {Name,Status,Path});
                objListViewItem.Selected = true;
                lvPublishedFolders.Items.Add(objListViewItem);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 接收到客户发来的视频消息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="doc"></param>
        private void _OnVideoMessage(HttpContext context, System.Xml.XmlDocument doc)
        {
//            < xml >
//  < ToUserName >< ![CDATA[toUser]] ></ ToUserName >
//  < FromUserName >< ![CDATA[fromUser]] ></ FromUserName >
//  < CreateTime > 1357290913 </ CreateTime >
//  < MsgType >< ![CDATA[video]] ></ MsgType >
//  < MediaId >< ![CDATA[media_id]] ></ MediaId >
//  < ThumbMediaId >< ![CDATA[thumb_media_id]] ></ ThumbMediaId >
//  < MsgId > 1234567890123456 </ MsgId >
//</ xml >

            string toUserName   = doc.GetElementsByTagName("ToUserName")[0].InnerText;
            string fromUserName = doc.GetElementsByTagName("FromUserName")[0].InnerText;
            string createTime   = doc.GetElementsByTagName("CreateTime")[0].InnerText;

            string mediaId      = doc.GetElementsByTagName("MediaId")[0].InnerText;
            string ThumbMediaId = doc.GetElementsByTagName("ThumbMediaId")[0].InnerText;
            string msgId        = doc.GetElementsByTagName("MsgId")[0].InnerText;

            RequestVideo rqText = new RequestVideo();

            rqText.ToUserName   = toUserName;
            rqText.FromUserName = fromUserName;
            rqText.CreateTime   = new DateTime(long.Parse(createTime));

            rqText.ThumbMediaId = ThumbMediaId;
            rqText.MediaId      = mediaId;
            rqText.MsgId        = msgId;

            rqText.MsgId = msgId;

            ResponseMessage rpMsg = OnVideoMessage(rqText);

            SendResponseMessage(context, rpMsg, rqText);
        }
Ejemplo n.º 24
0
        internal List <WsusServer> LoadServerSettings()
        {
            Logger.EnteringMethod();
            ServerList.Clear();
            cmbBxServerList.Items.Clear();

            if (System.IO.File.Exists("Options.xml"))
            {
                System.Xml.XmlDocument document = new System.Xml.XmlDocument();
                document.Load("Options.xml");
                System.Xml.XmlNodeList nodeList = document.GetElementsByTagName("Server");
                foreach (System.Xml.XmlNode node in nodeList)
                {
                    if (node.HasChildNodes)
                    {
                        WsusServer serverWsus = new WsusServer();
                        foreach (System.Xml.XmlNode childNode in node.ChildNodes)
                        {
                            switch (childNode.Name)
                            {
                            case "Name":
                                serverWsus.Name = childNode.InnerText;
                                Logger.Write("Name : " + serverWsus.Name);
                                break;

                            case "IsLocal":
                                bool isLocal;
                                if (bool.TryParse(childNode.InnerText, out isLocal))
                                {
                                    serverWsus.IsLocal = isLocal;
                                    Logger.Write("IsLocal : " + serverWsus.IsLocal.ToString());
                                }
                                break;

                            case "Port":
                                int port;
                                if (int.TryParse(childNode.InnerText, out port))
                                {
                                    serverWsus.Port = port;
                                    Logger.Write("Port : " + serverWsus.Port.ToString());
                                }
                                break;

                            case "UseSSL":
                                bool useSSL;
                                if (bool.TryParse(childNode.InnerText, out useSSL))
                                {
                                    serverWsus.UseSSL = useSSL;
                                    Logger.Write("UseSSL : " + serverWsus.UseSSL.ToString());
                                }
                                break;

                            case "IgnoreCertErrors":
                                bool ignoreCertErrors;
                                if (bool.TryParse(childNode.InnerText, out ignoreCertErrors))
                                {
                                    serverWsus.IgnoreCertificateErrors = ignoreCertErrors;
                                    Logger.Write("ignoreCertErrors : " + serverWsus.IgnoreCertificateErrors.ToString());
                                }
                                break;

                            case "DeadLineDaysSpan":
                                int day;
                                if (int.TryParse(childNode.InnerText, out day))
                                {
                                    serverWsus.DeadLineDaysSpan = day;
                                }
                                break;

                            case "DeadLineHour":
                                int hour;
                                if (int.TryParse(childNode.InnerText, out hour))
                                {
                                    serverWsus.DeadLineHour = hour;
                                }
                                break;

                            case "DeadLineMinute":
                                int minute;
                                if (int.TryParse(childNode.InnerText, out minute))
                                {
                                    serverWsus.DeadLineMinute = minute;
                                }
                                break;

                            case "MetaGroup":
                                serverWsus.MetaGroups.Add(GetMetaGroupFromXml(childNode));
                                break;

                            case "VisibleInWsusConsole":
                                string option = "Never";
                                option = childNode.InnerText;
                                if (option == "Never")
                                {
                                    serverWsus.VisibleInWsusConsole = MakeVisibleInWsusPolicy.Never;
                                }
                                if (option == "Always")
                                {
                                    serverWsus.VisibleInWsusConsole = MakeVisibleInWsusPolicy.Always;
                                }
                                if (option == "LetMeChoose")
                                {
                                    serverWsus.VisibleInWsusConsole = MakeVisibleInWsusPolicy.LetMeChoose;
                                }
                                break;

                            default:
                                break;
                            }
                        }
                        if (serverWsus.IsValid())
                        {
                            Logger.Write("Adding server : " + serverWsus.Name);
                            ServerList.Add(serverWsus);
                            cmbBxServerList.Items.Add(serverWsus);
                        }
                    }
                }
            }
            if (ServerList.Count == 0)
            {
                Logger.Write("Server count = 0");

                if (IsWsusInstalledOnLocalMachine())
                {
                    Logger.Write("Local Machine is Wsus.");
                    WsusServer serverWsus = new WsusServer();
                    serverWsus.Name                 = GetLocalMachineName();
                    serverWsus.IsLocal              = true;
                    serverWsus.Port                 = 80;
                    serverWsus.UseSSL               = false;
                    serverWsus.DeadLineDaysSpan     = 0;
                    serverWsus.DeadLineHour         = 0;
                    serverWsus.DeadLineMinute       = 0;
                    serverWsus.VisibleInWsusConsole = MakeVisibleInWsusPolicy.Never;

                    ServerList.Add(serverWsus);
                    cmbBxServerList.Items.Add(serverWsus);
                    SaveSettings(ServerList);
                    MessageBox.Show(resMan.GetString("AddAutomaticallyThisServer"));
                }
                else
                {
                    Logger.Write("No server are configured. Showing UI.");
                    if (this.Visible == false)
                    {
                        this.ShowDialog();
                    }
                }
            }

            Logger.Write("Returning " + ServerList.Count + " Servers.");
            return(ServerList);
        }
Ejemplo n.º 25
0
		private Result ParseServerResult( string ServerResult )
		{
			System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
			System.Xml.XmlNode ack;
			Result result = new Result();
			xDoc.LoadXml(ServerResult);
			ack = xDoc.GetElementsByTagName("ack")[0];
			result.ErrorCode = int.Parse(ack.Attributes["errorcode"].Value);
			result.ErrorMessage = ack.InnerText;
			result.Success = (result.ErrorCode == 0);
			return result;
		}
Ejemplo n.º 26
0
        public Function(CodeGenerateSystem.Base.ConstructionParams smParam)
            : base(smParam)
        {
            InitializeComponent();

            var splits = CSParam.ConstructParam.Split('|');

            var include = splits[0];

            if (include.Contains(":"))
            {
                include = EngineNS.CEngine.Instance.FileManager._GetRelativePathFromAbsPath(include, EngineNS.CEngine.Instance.FileManager.Bin);
            }
            include = include.Replace("\\", "/");
            if (include.Contains("bin/"))
            {
                var nIdx = include.IndexOf("bin/");
                include = include.Substring(nIdx + 4);
            }

            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(splits[1]);

            mStrFuncName = xmlDoc.DocumentElement.GetAttribute("Name");
            NodeName     = mStrFuncName;
            var tempElements = xmlDoc.GetElementsByTagName("Param");

            if (tempElements.Count > 0)
            {
                var cpInfos = new List <CodeGenerateSystem.Base.CustomPropertyInfo>();

                var paramInElm = tempElements[0];
                int nIdx       = 0;
                foreach (System.Xml.XmlElement node in paramInElm.ChildNodes)
                {
                    var typeStr = node.GetAttribute("Type");
                    var nameStr = node.GetAttribute("Name");
                    var strAttr = node.GetAttribute("Attribute");

                    switch (strAttr)
                    {
                    case "out":
                    case "return":
                        break;

                    default:
                    {
                        var cpInfo = CodeGenerateSystem.Base.CustomPropertyInfo.GetFromParamInfo(Program.GetTypeFromValueType(typeStr), nameStr, new Attribute[] { new EngineNS.Rtti.MetaDataAttribute() });
                        if (cpInfo != null)
                        {
                            cpInfos.Add(cpInfo);
                        }
                    }
                    break;
                    }

                    AddLink(nIdx, typeStr, nameStr, strAttr);
                    nIdx++;
                }

                mTemplateClassInstance = CodeGenerateSystem.Base.PropertyClassGenerator.CreateClassInstanceFromCustomPropertys(cpInfos, this, $"{this.GetType().FullName}.PropertyClass_{mStrFuncName}", false);
                foreach (var property in mTemplateClassInstance.GetType().GetProperties())
                {
                    property.SetValue(mTemplateClassInstance, CodeGenerateSystem.Program.GetDefaultValueFromType(property.PropertyType));
                }
                if (HostNodesContainer != null && HostNodesContainer.HostControl != null)
                {
                    mTemplateClassInstance.EnableUndoRedo(HostNodesContainer.HostControl.UndoRedoKey, mStrFuncName);
                }
            }

            this.UpdateLayout();
        }
        //метод для отслежки клиента
        private void button4_Click(object sender, EventArgs e)
        {
            if (comboBox1234.Text == String.Empty)
            {
                MessageBox.Show("Выберите клиента чтобы отследить!");
            }
            else
            {
                //Очищаем таблицу перед загрузкой данных.
                dtRouter.Rows.Clear();

                //Создаем список способов перемещения.
                List <string> mode = new List <string>();
                //Автомобильные маршруты по улично-дорожной сети.
                mode.Add("driving");
                //Пешеходные маршруты по прогулочным дорожкам и тротуарам.
                mode.Add("walking");
                //Велосипедные маршруты по велосипедным дорожкам и предпочитаемым улицам.
                mode.Add("bicycling");
                //Маршруты общественного транспорта.
                mode.Add("transit");

                //Фрмируем запрос к API маршрутов Google.
                string url = string.Format(
                    "http://maps.googleapis.com/maps/api/directions/xml?origin={0},&destination={1}&sensor=false&language=ru&mode={2}",
                    Uri.EscapeDataString(textBox1.Text), Uri.EscapeDataString(textBox2.Text), Uri.EscapeDataString(mode[comboBox1.SelectedIndex]));

                //Выполняем запрос к универсальному коду ресурса (URI).
                System.Net.HttpWebRequest request =
                    (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                //Получаем ответ от интернет-ресурса.
                System.Net.WebResponse response =
                    request.GetResponse();

                //Экземпляр класса System.IO.Stream
                //для чтения данных из интернет-ресурса.
                System.IO.Stream dataStream =
                    response.GetResponseStream();

                //Инициализируем новый экземпляр класса
                //System.IO.StreamReader для указанного потока.
                System.IO.StreamReader sreader =
                    new System.IO.StreamReader(dataStream);

                //Считываем поток от текущего положения до конца.
                string responsereader = sreader.ReadToEnd();

                //Закрываем поток ответа.
                response.Close();

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

                xmldoc.LoadXml(responsereader);

                if (xmldoc.GetElementsByTagName("status")[0].ChildNodes[0].InnerText == "OK")
                {
                    System.Xml.XmlNodeList nodes =
                        xmldoc.SelectNodes("//leg//step");

                    //Формируем строку для добавления в таблицу.
                    object[] dr;
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        //Указываем что массив будет состоять из
                        //восьми значений.
                        dr = new object[8];
                        //Номер шага.
                        dr[0] = i;
                        //Получение координат начала отрезка.
                        dr[1] = xmldoc.SelectNodes("//start_location").Item(i).SelectNodes("lat").Item(0).InnerText.ToString();
                        dr[2] = xmldoc.SelectNodes("//start_location").Item(i).SelectNodes("lng").Item(0).InnerText.ToString();
                        //Получение координат конца отрезка.
                        dr[3] = xmldoc.SelectNodes("//end_location").Item(i).SelectNodes("lat").Item(0).InnerText.ToString();
                        dr[4] = xmldoc.SelectNodes("//end_location").Item(i).SelectNodes("lng").Item(0).InnerText.ToString();
                        //Получение времени необходимого для прохождения этого отрезка.
                        dr[5] = xmldoc.SelectNodes("//duration").Item(i).SelectNodes("text").Item(0).InnerText.ToString();
                        //Получение расстояния, охватываемое этим отрезком.
                        dr[6] = xmldoc.SelectNodes("//distance").Item(i).SelectNodes("text").Item(0).InnerText.ToString();
                        //Получение инструкций для этого шага, представленные в виде текстовой строки HTML.
                        dr[7] = HtmlToPlainText(xmldoc.SelectNodes("//html_instructions").Item(i).InnerText.ToString());
                        //Добавление шага в таблицу.
                        dtRouter.Rows.Add(dr);
                    }

                    //Выводим в текстовое поле адрес начала пути.
                    textBox1.Text = xmldoc.SelectNodes("//leg//start_address").Item(0).InnerText.ToString();
                    //Выводим в текстовое поле адрес конца пути.
                    textBox2.Text = xmldoc.SelectNodes("//leg//end_address").Item(0).InnerText.ToString();
                    //Выводим в текстовое поле время в пути.
                    textBox3.Text = xmldoc.GetElementsByTagName("duration")[nodes.Count].ChildNodes[1].InnerText;
                    //Выводим в текстовое поле расстояние от начальной до конечной точки.
                    textBox4.Text = xmldoc.GetElementsByTagName("distance")[nodes.Count].ChildNodes[1].InnerText;

                    //Переменные для хранения координат начала и конца пути.
                    double latStart = 0.0;
                    double lngStart = 0.0;
                    double latEnd   = 0.0;
                    double lngEnd   = 0.0;

                    //Получение координат начала пути.
                    latStart = System.Xml.XmlConvert.ToDouble(xmldoc.GetElementsByTagName("start_location")[nodes.Count].ChildNodes[0].InnerText);
                    lngStart = System.Xml.XmlConvert.ToDouble(xmldoc.GetElementsByTagName("start_location")[nodes.Count].ChildNodes[1].InnerText);
                    //Получение координат конечной точки.
                    latEnd = System.Xml.XmlConvert.ToDouble(xmldoc.GetElementsByTagName("end_location")[nodes.Count].ChildNodes[0].InnerText);
                    lngEnd = System.Xml.XmlConvert.ToDouble(xmldoc.GetElementsByTagName("end_location")[nodes.Count].ChildNodes[1].InnerText);

                    //Выводим в текстовое поле координаты начала пути.
                    textBox5.Text = latStart + ";" + lngStart;
                    //Выводим в текстовое поле координаты конечной точки.
                    textBox6.Text = latEnd + ";" + lngEnd;

                    //Устанавливаем заполненную таблицу в качестве источника.
                    dataGridView1.DataSource = dtRouter;

                    //Устанавливаем позицию карты на начало пути.
                    gMapControl1.Position = new GMap.NET.PointLatLng(latStart, lngStart);

                    //Создаем новый список маркеров, с указанием компонента
                    //в котором они будут использоваться и названием списка.
                    GMap.NET.WindowsForms.GMapOverlay markersOverlay =
                        new GMap.NET.WindowsForms.GMapOverlay(gMapControl1, "marker");

                    //Инициализация нового ЗЕЛЕНОГО маркера, с указанием координат начала пути.
                    GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen markerG =
                        new GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen(
                            new GMap.NET.PointLatLng(latStart, lngStart));
                    markerG.ToolTip =
                        new GMap.NET.WindowsForms.ToolTips.GMapRoundedToolTip(markerG);

                    //Указываем, что подсказку маркера, необходимо отображать всегда.
                    markerG.ToolTipMode = GMap.NET.WindowsForms.MarkerTooltipMode.Always;

                    //Формируем подсказку для маркера.
                    string[] wordsG      = textBox1.Text.Split(',');
                    string   dataMarkerG = string.Empty;
                    foreach (string word in wordsG)
                    {
                        dataMarkerG += word + ";\n";
                    }

                    //Устанавливаем текст подсказки маркера.
                    markerG.ToolTipText = dataMarkerG;

                    //Инициализация нового Красного маркера, с указанием координат конца пути.
                    GMap.NET.WindowsForms.Markers.GMapMarkerGoogleRed markerR =
                        new GMap.NET.WindowsForms.Markers.GMapMarkerGoogleRed(
                            new GMap.NET.PointLatLng(latEnd, lngEnd));
                    markerG.ToolTip =
                        new GMap.NET.WindowsForms.ToolTips.GMapRoundedToolTip(markerG);

                    //Указываем, что подсказку маркера, необходимо отображать всегда.
                    markerR.ToolTipMode = GMap.NET.WindowsForms.MarkerTooltipMode.Always;

                    //Формируем подсказку для маркера.
                    string[] wordsR      = textBox2.Text.Split(',');
                    string   dataMarkerR = string.Empty;
                    foreach (string word in wordsR)
                    {
                        dataMarkerR += word + ";\n";
                    }

                    //Текст подсказки маркера.
                    markerR.ToolTipText = dataMarkerR;

                    //Добавляем маркеры в список маркеров.
                    markersOverlay.Markers.Add(markerG);
                    markersOverlay.Markers.Add(markerR);

                    //Очищаем список маркеров компонента.
                    gMapControl1.Overlays.Clear();

                    //Создаем список контрольных точек для прокладки маршрута.
                    List <GMap.NET.PointLatLng> list = new List <GMap.NET.PointLatLng>();

                    //Проходимся по определенным столбцам для получения
                    //координат контрольных точек маршрута и занесением их
                    //в список координат.
                    for (int i = 0; i < dtRouter.Rows.Count; i++)
                    {
                        double dbStartLat = double.Parse(dtRouter.Rows[i].ItemArray[1].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                        double dbStartLng = double.Parse(dtRouter.Rows[i].ItemArray[2].ToString(), System.Globalization.CultureInfo.InvariantCulture);

                        list.Add(new GMap.NET.PointLatLng(dbStartLat, dbStartLng));

                        double dbEndLat = double.Parse(dtRouter.Rows[i].ItemArray[3].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                        double dbEndLng = double.Parse(dtRouter.Rows[i].ItemArray[4].ToString(), System.Globalization.CultureInfo.InvariantCulture);

                        list.Add(new GMap.NET.PointLatLng(dbEndLat, dbEndLng));
                    }

                    //Очищаем все маршруты.
                    markersOverlay.Routes.Clear();

                    //Создаем маршрут на основе списка контрольных точек.
                    GMap.NET.WindowsForms.GMapRoute r = new GMap.NET.WindowsForms.GMapRoute(list, "Route");

                    //Указываем, что данный маршрут должен отображаться.
                    r.IsVisible = true;

                    //Устанавливаем цвет маршрута.
                    r.Stroke.Color = Color.DarkGreen;

                    //Добавляем маршрут.
                    markersOverlay.Routes.Add(r);

                    //Добавляем в компонент, список маркеров и маршрутов.
                    gMapControl1.Overlays.Add(markersOverlay);

                    //Указываем, что при загрузке карты будет использоваться
                    //9ти кратное приближение.
                    gMapControl1.Zoom = 9;

                    //Обновляем карту.
                    gMapControl1.Refresh();
                }
            }
        }
Ejemplo n.º 28
0
        private void MySearchCallback(IAsyncResult result)
        {
            // Create an EventHandler delegate.
            UpdateSearchButtonHandler updateSearch = new UpdateSearchButtonHandler(UpdateSearchButtonEvent);

            // Invoke the delegate on the UI thread.
            this.Invoke(updateSearch, new object[] { new BoolArgs(true) });
            RequestState rs = (RequestState)result.AsyncState;

            try {
                // Get the WebRequest from RequestState.
                WebRequest req = rs.Request;

                // Call EndGetResponse, which produces the WebResponse object
                //  that came from the request issued above.
                WebResponse resp = req.EndGetResponse(result);

                //  Start reading data from the response stream.
                System.IO.Stream responseStream = resp.GetResponseStream();

                // Store the response stream in RequestState to read
                // the stream asynchronously.
                rs.ResponseStream = responseStream;
                xmlReader         = new System.Xml.XmlTextReader(responseStream);
                xmlDoc            = new System.Xml.XmlDocument();
                xmlDoc.Load(xmlReader);
                xmlReader.Close();
                resp.Close();
                req = null;
            } catch (WebException we) {
                rs.Request.Abort();
                rs.Request = null;
                toolStripStatusLabel1.Text = "Search failed.";
                MessageBox.Show(we.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (currentResultPage < totalResultPages)
                {
                    moreButton.Show();
                }

                return;
            }

            int nResults = Convert.ToInt32(xmlDoc.GetElementsByTagName("numResults")[0].InnerText);

            if (nResults > 0)
            {
                totalResultPages           = nResults / 20 + 1;
                toolStripStatusLabel1.Text = "Items found: " + nResults;
                toolStripStatusLabel2.Text = "Showing page " + currentResultPage.ToString() + " of " + totalResultPages.ToString();
            }
            else
            {
                MessageBox.Show("Your query didn't return any results from Infoseek.\nTry some other search term or regular Infoseek\nwildcards like '*', '?', '^'", "No match", MessageBoxButtons.OK, MessageBoxIcon.Information);
                toolStripStatusLabel1.Text = "Ready";
                toolStripStatusLabel2.Text = "";
                return;
            }
            System.Xml.XmlNodeList memberNodes = xmlDoc.SelectNodes("//result");
            foreach (System.Xml.XmlNode node in memberNodes)
            {
                InfoseekResult ir        = new InfoseekResult();
                ProgramTitle   progTitle = new ProgramTitle();
                ir.InfoseekID  = node.SelectSingleNode("id").InnerText;
                ir.ProgramName = node.SelectSingleNode("title").InnerText;
                ir.Year        = node.SelectSingleNode("year").InnerText;
                ir.Publisher   = node.SelectSingleNode("publisher").InnerText;
                ir.ProgramType = node.SelectSingleNode("type").InnerText;
                ir.Language    = node.SelectSingleNode("language").InnerText;
                ir.Score       = node.SelectSingleNode("score").InnerText;
                ir.PicInlayURL = node.SelectSingleNode("picInlay").InnerText;
                infoList.Add(ir);
                progTitle.Title = ir.ProgramName;
                // ProgramTitleList.Add(progTitle);
                AddItemToListBox(infoListBox, infoList.Count - 1, ir.ProgramName,
                                 ir.PicInlayURL, ir.Publisher, ir.ProgramType,
                                 ir.Year, ir.Language, ir.Score);
            }
        }
Ejemplo n.º 29
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.º 30
0
        void LoadPhoneNumberFormat()
        {
            Dictionary<string,string> formats = new Dictionary<string,string>();
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load("PhoneNumberFormat.xml");
            System.Xml.XmlNodeList regions = doc.GetElementsByTagName("Region");

            formats.Add("無", "");
            foreach (System.Xml.XmlNode region in regions)
                formats.Add(region.Attributes["name"].Value, region.FirstChild.InnerText);

            BindingSource binding = new BindingSource(formats, null);
            cbbPhoneFormat.DataSource = binding;

            cbbPhoneFormat.DisplayMember = "Key";
            cbbPhoneFormat.ValueMember = "Value";

            mtxtTel.DataBindings.Add("Mask", binding, "Value");
            mtxtFax.DataBindings.Add("Mask", binding, "Value");
        }
Ejemplo n.º 31
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.º 32
0
            /// <summary>
            /// gets realtime data from public transport in city vilnius of lithuania
            /// </summary>
            private void GetVilniusTransportData(string line)
            {
                if (_isActive)
                {
                    return;
                }
                _isActive = true;

                //List<FeatureDataRow> newFeatures = new List<FeatureDataRow>();
                var fdt = VehicleDataTable();

                string url = "http://www.troleibusai.lt/puslapiai/services/vehiclestate.php?type=";

                switch (_transportType)
                {
                case TransportType.Bus:
                {
                    url += "bus";
                }
                break;

                case TransportType.TrolleyBus:
                {
                    url += "trolley";
                }
                break;
                }

                if (!string.IsNullOrEmpty(line))
                {
                    url += "&line=" + line;
                }

                url += "&app=SharpMap.WinFormSamples";

                var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                request.Timeout          = Timeout;
                request.ReadWriteTimeout = request.Timeout;
                request.Accept           = "*/*";
                request.KeepAlive        = false;

                string xml;

                using (var response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    if (response == null)
                    {
                        return;
                    }

                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream == null)
                        {
                            return;
                        }
                        using (var read = new System.IO.StreamReader(responseStream))
                        {
                            xml = read.ReadToEnd();
                        }
                    }
                }

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

                {
                    doc.LoadXml(xml);

                    var devices = doc.GetElementsByTagName("Device");
                    foreach (System.Xml.XmlNode dev in devices)
                    {
                        if (dev.Attributes == null)
                        {
                            continue;
                        }

                        double?lat = null, lng = null;
                        SharpMap.Data.FeatureDataRow dr = fdt.NewRow();
                        dr["Id"] = int.Parse(dev.Attributes["ID"].InnerText);
                        foreach (System.Xml.XmlElement elem in dev.ChildNodes)
                        {
                            // Debug.WriteLine(d.Id + "->" + elem.Name + ": " + elem.InnerText);

                            switch (elem.Name)
                            {
                            case "Lat":
                                lat = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                break;

                            case "Lng":
                                lng = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                break;

                            case "Bearing":
                                if (!string.IsNullOrEmpty(elem.InnerText))
                                {
                                    dr["Bearing"] = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                }
                                break;

                            case "LineNum":
                                dr["Line"] = elem.InnerText;
                                break;

                            case "AreaName":
                                dr["AreaName"] = elem.InnerText;
                                break;

                            case "StreetName":
                                dr["StreetName"] = elem.InnerText;
                                break;

                            case "TrackType":
                                dr["TrackType"] = elem.InnerText;
                                break;

                            case "LastStop":
                                dr["LastStop"] = elem.InnerText;
                                break;

                            case "Time":
                                dr["Time"] = elem.InnerText;
                                break;
                            }
                        }

                        if (lat.HasValue && lng.HasValue)
                        {
                            dr.Geometry = _factory.CreatePoint(new GeoAPI.Geometries.Coordinate(lng.Value, lat.Value));
                            fdt.Rows.Add(dr);
                        }
                    }
                }

                Features.Clear();

                foreach (SharpMap.Data.FeatureDataRow featureDataRow in fdt.Rows)
                {
                    var fdr = Features.NewRow();
                    fdr.ItemArray = featureDataRow.ItemArray;
                    fdr.Geometry  = featureDataRow.Geometry;
                    Features.AddRow(fdr);
                }
                Features.AcceptChanges();

                _isActive = false;
            }
Ejemplo n.º 33
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.º 34
0
        private bool ValidateResponse(HttpWebResponse resp, out string newURL, out string streamName)
        {
            streamName = string.Empty;
            PrintHttpWebResponseHeader(resp, "ValidateResponse", out streamName);
            newURL = string.Empty;
            if (resp == null)
                return false;
            if (resp.Headers == null)
            {
                return false;
            }
            string[] values = resp.Headers.GetValues("Content-Type");
            if (values == null || values.Length <= 0)
                return false;
            bool bFoundText = false;
            string txtFoundType = string.Empty;
            foreach (string strVal in values)
            {
                if (string.IsNullOrWhiteSpace(strVal))
                    continue;
                if (Common.AppSettings.Instance.DiagnosticMode)
                {
                    Common.ConsoleHelper.ColorWriteLine(ConsoleColor.Yellow, "HTTP Content-Type: {0}", strVal);
                }
                string str = strVal.ToLower().Trim();
                if (str.Contains("mpegurl") || str.Contains("x-scpls") || str.Contains("video/x-ms-asf"))
                {
                    txtFoundType = str;
                    bFoundText = true;
                    break;
                }
                if (str.Contains("audio"))
                    return true;
                if (str.Contains("text") || str.Contains("xml"))
                {
                    txtFoundType = str;
                    bFoundText = true;
                    break;
                }
            }
            if (!bFoundText)
                return false;
            try
            {
                using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                {
                    if (txtFoundType == "text/xml")
                    {
                        System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                        xDoc.LoadXml(sr.ReadToEnd());
                        System.Xml.XmlNodeList locList = xDoc.GetElementsByTagName("location");
                        if (locList != null && locList.Count > 0)
                        {
                            newURL = locList[0].InnerText;
                            Common.ConsoleHelper.ColorWriteLine(ConsoleColor.Green, "Stream {0}, redirect to URL {1}", _streamName, newURL);
                            return false;
                        }
                    }
                    else if(txtFoundType=="video/x-ms-asf")
                    {
                        System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                        xDoc.LoadXml(sr.ReadToEnd());
                        System.Xml.XmlNode refNode=FindChildNode(xDoc.DocumentElement, "REF");
                        if (refNode != null)
                        {
                            System.Xml.XmlAttribute hrefAttrib = refNode.Attributes["HREF"];
                            if(hrefAttrib!=null&&!string.IsNullOrWhiteSpace(hrefAttrib.Value))
                            {
                                newURL = hrefAttrib.Value;
                                Common.ConsoleHelper.ColorWriteLine(ConsoleColor.Green, "Stream {0}, redirect to URL {1}", _streamName, newURL);
                                return false;
                            }
                        }
                    }
                    else if (txtFoundType.Contains("x-scpls"))
                    {
                        while (!sr.EndOfStream)
                        {
                            string strPossible = sr.ReadLine();
                            if (!string.IsNullOrWhiteSpace(strPossible))
                            {
                                strPossible = strPossible.Trim();
                                if(!string.IsNullOrWhiteSpace(strPossible)&&strPossible.StartsWith("File")&&strPossible.IndexOf('=')>0)
                                {
                                    strPossible = strPossible.Substring(strPossible.IndexOf('=') + 1).Trim();
                                    if (!string.IsNullOrWhiteSpace(strPossible))
                                    {
                                        Uri test;
                                        if (Uri.TryCreate(strPossible, UriKind.Absolute, out test))
                                        {

                                            Common.ConsoleHelper.ColorWriteLine(ConsoleColor.Green, "Stream {0}, redirect to URL {1}", _streamName, strPossible);
                                            newURL = strPossible;
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        while (!sr.EndOfStream)
                        {
                            string strPossible = sr.ReadLine();
                            if (!string.IsNullOrWhiteSpace(strPossible))
                            {
                                strPossible = strPossible.Trim();
                                if (!string.IsNullOrWhiteSpace(strPossible) && !strPossible.StartsWith("#"))
                                {
                                    Uri test;
                                    if (Uri.TryCreate(strPossible, UriKind.Absolute, out test))
                                    {
                                        Common.ConsoleHelper.ColorWriteLine(ConsoleColor.Green, "Stream {0}, redirect to URL {1}", _streamName, strPossible);
                                        newURL = strPossible;
                                        return false;
                                    }
                                }
                                Common.ConsoleHelper.ColorWriteLine(ConsoleColor.DarkRed, strPossible);
                            }
                        }
                    }
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
Ejemplo n.º 35
0
        private void loadConfig()
        {
            try
            {
                System.Xml.XmlDocument file = new System.Xml.XmlDocument();

                file.Load(config_file);

                System.Xml.XmlNodeList videoNode = file.GetElementsByTagName("Directory");
                System.Xml.XmlNodeList countNode = file.GetElementsByTagName("Count");
                //System.Xml.XmlNodeList siteNode = file.GetElementsByTagName("SiteDirectory");

                for (int i = 0; i < videoNode.Count; i++)
                {
                    vidDir[i, 0] = (string)videoNode[i].InnerText;
                    vidDir[i, 1] = (string)countNode[i].InnerText;
                }

                // file.Save(config_file);

            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Ejemplo n.º 36
0
        private void cxBtnOk_Click(object sender, EventArgs e)
        {
            string sSQLServOldPwd, sSQLServNewPwd;

            if (cxTextEditOldPwd.EditValue == null || Convert.ToString(cxTextEditOldPwd.EditValue).Trim() == "")
            {
                oSecMainFrm.MessageDlg("Old Password cannot be blank...", "mtWarning", "mbOk", 0);
                return;
            }
            if (cxTextEditNewPwd.EditValue == null || Convert.ToString(cxTextEditNewPwd.EditValue).Trim() == "")
            {
                oSecMainFrm.MessageDlg("Please enter the new password.", "mtWarning", "mbOk", 0);
                return;
            }
            if (cxTextEditConfirmPwd.EditValue == null || Convert.ToString(cxTextEditConfirmPwd.EditValue).Trim() == "")
            {
                oSecMainFrm.MessageDlg("Please enter the confirm password.", "mtWarning", "mbOk", 0);
                return;
            }

            try
            {
                sSQLServOldPwd = XpedeonCrypto.XpedeonServerDecrypt(PCFSecurity.oSecDM.sSuperUserPassword);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (!Convert.ToString(cxTextEditOldPwd.EditValue).Equals(sSQLServOldPwd, StringComparison.InvariantCulture))
            {
                oSecMainFrm.MessageDlg("Old Password does not match.", "mtWarning", "mbOk", 0);
                return;
            }
            if (Convert.ToString(cxTextEditNewPwd.EditValue) != Convert.ToString(cxTextEditConfirmPwd.EditValue))
            {
                oSecMainFrm.MessageDlg("New Password and Confirm Password dont match.", "mtWarning", "mbOk", 0);
                return;
            }

            try
            {
                sSQLServNewPwd = XpedeonCrypto.XpedeonServerEncrypt(Convert.ToString(cxTextEditNewPwd.EditValue));
                UpdateSQLServPassword(Convert.ToString(cxTextEditUserName.EditValue), Convert.ToString(cxTextEditNewPwd.EditValue), Convert.ToString(cxTextEditOldPwd.EditValue));

                string sAppPath = Application.StartupPath.ToString();
                System.Xml.XmlDocument xdDataBaseConnection = new System.Xml.XmlDocument();
                xdDataBaseConnection.Load(@sAppPath + "\\PCFSecurityAccessInfo.xml");
                if (xdDataBaseConnection.GetElementsByTagName("PASSWORD").Count > 0)
                {
                    // Get the target node using XPath
                    System.Xml.XmlNode xnOldPwd = xdDataBaseConnection.SelectSingleNode("//PASSWORD");
                    // Create a new comment node with XML content of the target node
                    System.Xml.XmlComment xcOldPwd = xdDataBaseConnection.CreateComment(xnOldPwd.OuterXml);
                    // Replace the target node with the comment
                    xdDataBaseConnection.DocumentElement.ReplaceChild(xcOldPwd, xnOldPwd);

                    // Create a new node
                    System.Xml.XmlElement xeNewPwd = xdDataBaseConnection.CreateElement("PASSWORD");
                    xeNewPwd.InnerText = sSQLServNewPwd;
                    // Add the node to the document
                    xdDataBaseConnection.DocumentElement.AppendChild(xeNewPwd);
                }
                xdDataBaseConnection.Save(@sAppPath + "\\PCFSecurityAccessInfo.xml");

                PCFSecurity.oSecDM.DataModuleCreate();

                oSecMainFrm.MessageDlg("Password Changed Successfully.", "mtConfirmation", "mbOk", 0);
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 37
0
        private static void LoadReferences(System.Xml.XmlDocument xmlDocument, Models.Project project)
        {
            foreach (System.Xml.XmlNode node in xmlDocument.GetElementsByTagName("Reference"))
            {
                Models.Reference reference = new Models.Reference();

                foreach (System.Xml.XmlAttribute attribute in node.Attributes)
                {
                    switch (attribute.LocalName)
                    {
                    case "Name":
                    {
                        reference.Name = node.Attributes["Name"].Value;
                        break;
                    }

                    case "AssemblyName":
                    {
                        reference.AssemblyName = node.Attributes["AssemblyName"].Value;
                        break;
                    }

                    case "HintPath":
                    {
                        reference.HintPath = node.Attributes["HintPath"].Value;
                        break;
                    }

                    case "Project":
                    {
                        reference.Project = node.Attributes["Project"].Value;
                        break;
                    }

                    case "Package":
                    {
                        reference.Package = node.Attributes["Package"].Value;
                        break;
                    }

                    case "Guid":
                    {
                        reference.Guid = node.Attributes["Guid"].Value;
                        break;
                    }

                    case "VersionMajor":
                    {
                        reference.VersionMajor = node.Attributes["VersionMajor"].Value;
                        break;
                    }

                    case "VersionMinor":
                    {
                        reference.VersionMinor = node.Attributes["VersionMinor"].Value;
                        break;
                    }

                    case "Lcid":
                    {
                        reference.Lcid = node.Attributes["Lcid"].Value;
                        break;
                    }

                    case "WrapperTool":
                    {
                        reference.WrapperTool = node.Attributes["WrapperTool"].Value;
                        break;
                    }

                    case "Private":
                    {
                        reference.Private = node.Attributes["Private"].Value;
                        break;
                    }

                    case "AssemblyFolderKey":
                    {
                        reference.AssemblyFolderKey = node.Attributes["AssemblyFolderKey"].Value;
                        break;
                    }

                    default:
                    {
                        throw new System.Exception("Unknown project reference attribute: " + attribute.LocalName);
                    }
                    }
                }

                project.References.Add(reference);
            }
        }
Ejemplo n.º 38
0
        private DatosComprobante TraerRespuestaSri(string claveAcceso)
        {
            var resultado = string.Empty;
            DatosComprobante datosTributarios = new DatosComprobante();
            string           url = ConfigurationSettings.AppSettings.Get("url_sri");

            string xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ec=\"http://ec.gob.sri.ws.autorizacion\">";

            xml = xml + "<soapenv:Header/>";
            xml = xml + "<soapenv:Body>";
            xml = xml + "<ec:autorizacionComprobante>";
            xml = xml + "<claveAccesoComprobante>" + claveAcceso + "</claveAccesoComprobante>";
            xml = xml + "</ec:autorizacionComprobante>";
            xml = xml + "</soapenv:Body>";
            xml = xml + "</soapenv:Envelope>";

            try
            {
                byte[]         bytes   = Encoding.ASCII.GetBytes(xml);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                request.Method        = "POST";
                request.ContentLength = bytes.Length;
                request.ContentType   = "text/xml";

                //log.Debug("Clave acceso: " + claveAcceso);

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //log.Debug("Status: " + response.StatusCode);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream       responseStream = response.GetResponseStream();
                    StreamReader reader         = new StreamReader(responseStream);
                    resultado = reader.ReadToEnd();
                }

                resultado = WebUtility.HtmlDecode(resultado);
                //log.Debug("Resultado: " + resultado);
                response.Close();
                var caracterPrincipal  = resultado.IndexOf('?') - 1;
                var caracterSecundario = resultado.LastIndexOf('?') + 2;
                if (caracterPrincipal > 0 && caracterSecundario > 0)
                {
                    resultado = resultado.Remove(caracterPrincipal, (caracterSecundario - caracterPrincipal));
                }
                resultado = "<?xml version=" + "\"1.0\"" + " encoding=" + "\"UTF-8\"" + "?>" + resultado;
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(resultado);
                System.Xml.XmlNode element = doc.SelectSingleNode("numeroAutorizacion");
                datosTributarios.claveAcceso        = doc.GetElementsByTagName("claveAcceso")[0].InnerText;
                datosTributarios.numeroAutorizacion = doc.GetElementsByTagName("numeroAutorizacion")[0].InnerText;
                datosTributarios.fechaAutorizacion  = Convert.ToDateTime(doc.GetElementsByTagName("fechaAutorizacion")[0].InnerText);
                datosTributarios.estado             = doc.GetElementsByTagName("estado")[0].InnerText;
                datosTributarios.comprobante        = doc.GetElementsByTagName("comprobante")[0].InnerXml;
                //log.Debug("Estado: " + doc.GetElementsByTagName("estado")[0].InnerText);
            }
            catch (Exception e)
            {
                //log.Error(e);
            }

            return(datosTributarios);
        }
Ejemplo n.º 39
0
        public void LoadCif()
        {
            // Cargo el archivo CIF
            using (System.IO.Stream CifXml = this.Assembly.GetManifestResourceStream(this.EspacioNombres + ".cif.xml"))
            {
                if (CifXml != null)
                {
                    Log.Info("Cargando " + this.EspacioNombres + ".cif.xml");
                    // FIXME: puedo cargarlo con un lector de texto
                    using (System.IO.StreamReader Lector = new System.IO.StreamReader(CifXml))
                    {
                        this.Cif = Lector.ReadToEnd();
                        Lector.Close();
                    }
                }
            }

            if (this.Cif == null)
            {
                return;
            }

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

            DocumentoCif.LoadXml(this.Cif);
            var ListaComponentes = DocumentoCif.GetElementsByTagName("Component");

            //Abro el/los nodo(s) de componentes
            foreach (var Componente in ListaComponentes)
            {
                var NodosMenu = DocumentoCif.GetElementsByTagName("MenuItem");
                foreach (System.Xml.XmlNode NodoMenu in NodosMenu)
                {
                    if (this.MenuEntries == null)
                    {
                        this.MenuEntries = new List <Lfx.Components.MenuEntry>();
                    }

                    Lfx.Components.MenuEntry Menu = new Lfx.Components.MenuEntry();
                    Menu.Name = NodoMenu.Attributes["name"].Value;
                    if (NodoMenu.Attributes["position"] == null)
                    {
                        Menu.Parent = "Componentes";
                    }
                    else
                    {
                        Menu.Parent = NodoMenu.Attributes["position"].Value;
                    }

                    if (NodoMenu.Attributes["function"] != null)
                    {
                        Menu.Function = NodoMenu.Attributes["function"].Value;
                    }

                    this.MenuEntries.Add(Menu);
                }

                // Cargo las funciones personalizadas

                /* System.Xml.XmlNodeList NodosFunciones = DocumentoCif.GetElementsByTagName("Function");
                 * foreach (System.Xml.XmlNode NodoFuncion in NodosFunciones) {
                 *      Lfx.Components.FunctionInfo Func = new Lfx.Components.FunctionInfo(this);
                 *      Func.Nombre = NodoFuncion.Attributes["name"].Value;
                 *      if (Func.Nombre != null && Func.Nombre.Length > 0 && Func.Nombre != "-") {
                 *              if (NodoFuncion.Attributes["autorun"] != null && NodoFuncion.Attributes["autorun"].Value == "1")
                 *                      Func.AutoRun = true;
                 *
                 *              this.Funciones.Add(Func);
                 *      }
                 * } */
            }
        }
Ejemplo n.º 40
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.º 41
0
            /// <summary>
            /// gets realtime data from public transport in city vilnius of lithuania
            /// </summary>
            private void GetVilniusTransportData(string line)
            {
                if (_isActive) return;
                _isActive = true;

                //List<FeatureDataRow> newFeatures = new List<FeatureDataRow>();
                var fdt = VehicleDataTable();

                string url = "http://www.troleibusai.lt/puslapiai/services/vehiclestate.php?type=";

                switch (_transportType)
                {
                    case TransportType.Bus:
                        {
                            url += "bus";
                        }
                        break;

                    case TransportType.TrolleyBus:
                        {
                            url += "trolley";
                        }
                        break;
                }

                if (!string.IsNullOrEmpty(line))
                {
                    url += "&line=" + line;
                }

                url += "&app=SharpMap.WinFormSamples";

                var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                request.Timeout = Timeout;
                request.ReadWriteTimeout = request.Timeout;
                request.Accept = "*/*";
                request.KeepAlive = false;

                string xml;

                using (var response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    if (response == null)
                        return;

                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream == null)
                            return;
                        using (var read = new System.IO.StreamReader(responseStream))
                        {
                            xml = read.ReadToEnd();
                        }
                    }
                }

                var doc = new System.Xml.XmlDocument();
                {
                    doc.LoadXml(xml);

                    var devices = doc.GetElementsByTagName("Device");
                    foreach (System.Xml.XmlNode dev in devices)
                    {
                        if (dev.Attributes == null) continue;

                        double? lat = null, lng = null;
                        SharpMap.Data.FeatureDataRow dr = fdt.NewRow();
                        dr["Id"] = int.Parse(dev.Attributes["ID"].InnerText);
                        foreach (System.Xml.XmlElement elem in dev.ChildNodes)
                        {
                            // Debug.WriteLine(d.Id + "->" + elem.Name + ": " + elem.InnerText);

                            switch (elem.Name)
                            {
                                case "Lat":
                                    lat = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                    break;

                                case "Lng":
                                    lng = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                    break;

                                case "Bearing":
                                    if (!string.IsNullOrEmpty(elem.InnerText))
                                        dr["Bearing"] = double.Parse(elem.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                                    break;

                                case "LineNum":
                                    dr["Line"] = elem.InnerText;
                                    break;

                                case "AreaName":
                                    dr["AreaName"] = elem.InnerText;
                                    break;

                                case "StreetName":
                                    dr["StreetName"] = elem.InnerText;
                                    break;

                                case "TrackType":
                                    dr["TrackType"] = elem.InnerText;
                                    break;

                                case "LastStop":
                                    dr["LastStop"] = elem.InnerText;
                                    break;

                                case "Time":
                                    dr["Time"] = elem.InnerText;
                                    break;
                            }
                        }

                        if (lat.HasValue && lng.HasValue)
                        {
                            dr.Geometry = _factory.CreatePoint(new GeoAPI.Geometries.Coordinate(lng.Value, lat.Value));
                            fdt.Rows.Add(dr);
                        }
                    }
                }

                Features.Clear();

                foreach (SharpMap.Data.FeatureDataRow featureDataRow in fdt.Rows)
                {
                    var fdr = Features.NewRow();
                    fdr.ItemArray = featureDataRow.ItemArray;
                    fdr.Geometry = featureDataRow.Geometry;
                    Features.AddRow(fdr);
                }
                Features.AcceptChanges();

                _isActive = false;
            }
Ejemplo n.º 42
0
        /// <summary>
        /// Detects if a message is a delivery failure notification.
        /// This method uses the default signatures containing in an internal ressource file.
        /// </summary>
        /// <remarks>
        /// Signature files are XML files formatted as follows : 
        /// 
        /// &lt;?xml version='1.0'?&gt;
        /// &lt;signatures&gt;
        ///		&lt;signature from=&quot;postmaster&quot; subject=&quot;Undeliverable Mail&quot; body=&quot;Unknown user&quot; search=&quot;&quot; />
        ///		...
        /// &lt;/signatures&gt;
        /// </remarks>
        /// <returns>A BounceStatus object containing the level of revelance and if 100% identified, the erroneous email address.</returns>
        public BounceResult GetBounceStatus(string signaturesFilePath)
        {
            string ressource = string.Empty;
            
            if (signaturesFilePath == null || signaturesFilePath == string.Empty)
            {
                ressource = Header.GetResource("ActiveUp.Net.Mail.bouncedSignatures.xml");
            }
            else
                ressource = System.IO.File.OpenText(signaturesFilePath).ReadToEnd();
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(ressource);
            BounceResult result = new BounceResult();

            foreach (System.Xml.XmlElement el in doc.GetElementsByTagName("signature"))
            {
                if (this.From.Merged.IndexOf(el.GetElementsByTagName("from")[0].InnerText) != -1)
                    result.Level++;

                if (this.Subject != null && this.Subject.IndexOf(el.GetElementsByTagName("subject")[0].InnerText) != -1)
                    result.Level++;
            }

            return result;
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Executes the given <paramref name="command"/>.
        /// </summary>
        /// <param name="command">The command to execute.</param>
        public static void Execute(Command command)
        {
            if (command.Name == "time")
            {
                if (command.Args[0] == "nth")
                {
                    Console.WriteLine("Do not try to time \"nth\" command.");
                    Execute(new Command(command.Args[0], command.Args.Skip(1).ToArray()));
                    return;
                }

                DateTime start = DateTime.Now;
                Execute(new Command(command.Args[0], command.Args.Skip(1).ToArray()));
                Console.WriteLine($"The command \"{command.Args[0]}\" took {((DateTime.Now - start).Ticks) / 10000}ms");
                return;
            }

            if (command.Name == "nth")
            {
                new Nth(new Command(command.Args[0], command.Args.Skip(1).ToArray()));
                return;
            }

            if (command.Name == "clear")
            {
                Console.Clear();
                return;
            }

            if (command.Name == "ls")
            {
                new Ls(null);
                return;
            }

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

            reader.Load("../../execution.xml");

            foreach (System.Xml.XmlElement item in reader.GetElementsByTagName("command"))
            {
                if (command.Name == item.Attributes["name"].Value.ToLower())
                {
                    if (command.Args.Length == 1)
                    {
                        Run(command);
                        return;
                    }
                    if (item.Attributes["ignoreRest"].Value == "true" &&
                        command.Args.Length > int.Parse(item.Attributes["maxPossibleArgs"].Value))
                    {
                        command.Args = command.Args.SubArr(
                            int.Parse(item.Attributes["minPossibleArgs"].Value),
                            int.Parse(item.Attributes["maxPossibleArgs"].Value));
                    }

                    Run(command);
                    return;
                }
            }

            Console.WriteLine($"COMMAND \"{command.Name}\" NOT FOUND!");
        }
Ejemplo n.º 44
0
        private void button1_Click(object sender, EventArgs e)
        {
            dtRouter.Rows.Clear();
            List <string> mode = new List <string>();

            mode.Add("driving");
            mode.Add("walking");
            mode.Add("bicycling");
            mode.Add("transit");

            string url = string.Format(
                "http://maps.googleapis.com/maps/api/directions/xml?origin={0},&destination={1}&sensor=false&language=ru&mode={2}",
                Uri.EscapeDataString(textBox1.Text), Uri.EscapeDataString(textBox2.Text), Uri.EscapeDataString(mode[comboBox1.SelectedIndex]));

            HttpWebRequest request =
                (HttpWebRequest)System.Net.WebRequest.Create(url);
            WebResponse  response       = request.GetResponse();
            Stream       dataStream     = response.GetResponseStream();
            StreamReader sreader        = new System.IO.StreamReader(dataStream);
            string       responsereader = sreader.ReadToEnd();

            response.Close();

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

            xmldoc.LoadXml(responsereader);

            if (xmldoc.GetElementsByTagName("status")[0].ChildNodes[0].InnerText == "OK")
            {
                System.Xml.XmlNodeList nodes =
                    xmldoc.SelectNodes("//leg//step");

                object[] dr;
                for (int i = 0; i < nodes.Count; i++)
                {
                    dr    = new object[8];
                    dr[0] = i;
                    dr[1] = xmldoc.SelectNodes("//start_location").Item(i).SelectNodes("lat").Item(0).InnerText.ToString();
                    dr[2] = xmldoc.SelectNodes("//start_location").Item(i).SelectNodes("lng").Item(0).InnerText.ToString();
                    dr[3] = xmldoc.SelectNodes("//end_location").Item(i).SelectNodes("lat").Item(0).InnerText.ToString();
                    dr[4] = xmldoc.SelectNodes("//end_location").Item(i).SelectNodes("lng").Item(0).InnerText.ToString();
                    dr[5] = xmldoc.SelectNodes("//duration").Item(i).SelectNodes("text").Item(0).InnerText.ToString();
                    dr[6] = xmldoc.SelectNodes("//distance").Item(i).SelectNodes("text").Item(0).InnerText.ToString();
                    dr[7] = HtmlToPlainText(xmldoc.SelectNodes("//html_instructions").Item(i).InnerText.ToString());
                    dtRouter.Rows.Add(dr);
                }

                textBox1.Text = xmldoc.SelectNodes("//leg//start_address").Item(0).InnerText.ToString();
                textBox2.Text = xmldoc.SelectNodes("//leg//end_address").Item(0).InnerText.ToString();

                double latStart = 0.0;
                double lngStart = 0.0;
                double latEnd   = 0.0;
                double lngEnd   = 0.0;

                latStart = System.Xml.XmlConvert.ToDouble(xmldoc.GetElementsByTagName("start_location")[nodes.Count].ChildNodes[0].InnerText);
                lngStart = System.Xml.XmlConvert.ToDouble(xmldoc.GetElementsByTagName("start_location")[nodes.Count].ChildNodes[1].InnerText);

                latEnd = System.Xml.XmlConvert.ToDouble(xmldoc.GetElementsByTagName("end_location")[nodes.Count].ChildNodes[0].InnerText);
                lngEnd = System.Xml.XmlConvert.ToDouble(xmldoc.GetElementsByTagName("end_location")[nodes.Count].ChildNodes[1].InnerText);

                dataGridView1.DataSource = dtRouter;
                gMapControl1.Position    = new GMap.NET.PointLatLng(latStart, lngStart);
                GMapOverlay   markersOverlay = new GMapOverlay("marker");
                GMarkerGoogle markerG        =
                    new GMarkerGoogle(new PointLatLng(latStart, lngStart), GMarkerGoogleType.green_pushpin);
                markerG.ToolTip =
                    new GMap.NET.WindowsForms.ToolTips.GMapRoundedToolTip(markerG);

                markerG.ToolTipMode = MarkerTooltipMode.Always;

                string[] wordsG      = textBox1.Text.Split(',');
                string   dataMarkerG = string.Empty;
                foreach (string word in wordsG)
                {
                    dataMarkerG += word + ";\n";
                }
                markerG.ToolTipText = dataMarkerG;
                GMarkerGoogle markerR =
                    new GMarkerGoogle(
                        new PointLatLng(latEnd, lngEnd), GMarkerGoogleType.red_pushpin);
                markerG.ToolTip =
                    new GMap.NET.WindowsForms.ToolTips.GMapRoundedToolTip(markerG);
                markerR.ToolTipMode = MarkerTooltipMode.Always;
                string[] wordsR      = textBox2.Text.Split(',');
                string   dataMarkerR = string.Empty;
                foreach (string word in wordsR)
                {
                    dataMarkerR += word + ";\n";
                }

                markerR.ToolTipText = dataMarkerR;
                markersOverlay.Markers.Add(markerG);
                markersOverlay.Markers.Add(markerR);
                gMapControl1.Overlays.Clear();
                List <PointLatLng> list = new List <PointLatLng>();
                for (int i = 0; i < dtRouter.Rows.Count; i++)
                {
                    double dbStartLat = double.Parse(dtRouter.Rows[i].ItemArray[1].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                    double dbStartLng = double.Parse(dtRouter.Rows[i].ItemArray[2].ToString(), System.Globalization.CultureInfo.InvariantCulture);

                    list.Add(new PointLatLng(dbStartLat, dbStartLng));

                    double dbEndLat = double.Parse(dtRouter.Rows[i].ItemArray[3].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                    double dbEndLng = double.Parse(dtRouter.Rows[i].ItemArray[4].ToString(), System.Globalization.CultureInfo.InvariantCulture);

                    list.Add(new PointLatLng(dbEndLat, dbEndLng));
                }

                markersOverlay.Routes.Clear();
                GMapRoute r = new GMapRoute(list, "Route");
                r.IsVisible    = true;
                r.Stroke.Color = Color.DarkRed;
                markersOverlay.Routes.Add(r);
                gMapControl1.Overlays.Add(markersOverlay);
                gMapControl1.Zoom = 15;
                gMapControl1.Refresh();
            }
        }
Ejemplo n.º 45
0
        public static void InitNodePinTypes(CodeGenerateSystem.Base.ConstructionParams smParam)
        {
            var splits = smParam.ConstructParam.Split('|');

            var include = splits[0];

            if (include.Contains(":"))
            {
                include = EngineNS.CEngine.Instance.FileManager._GetRelativePathFromAbsPath(include, EngineNS.CEngine.Instance.FileManager.Bin);
            }
            include = include.Replace("\\", "/");
            if (include.Contains("bin/"))
            {
                var nIdx = include.IndexOf("bin/");
                include = include.Substring(nIdx + 4);
            }

            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(splits[1]);

            var tempElements = xmlDoc.GetElementsByTagName("Param");

            if (tempElements.Count > 0)
            {
                var cpInfos = new List <CodeGenerateSystem.Base.CustomPropertyInfo>();

                var paramInElm = tempElements[0];
                foreach (System.Xml.XmlElement node in paramInElm.ChildNodes)
                {
                    var strType = node.GetAttribute("Type");
                    var nameStr = node.GetAttribute("Name");
                    var strAttr = node.GetAttribute("Attribute");

                    if (string.IsNullOrEmpty(strAttr))
                    {
                        var linkType = LinkPinControl.GetLinkTypeFromTypeString(strType);
                        switch (linkType)
                        {
                        case enLinkType.Int32:
                        case enLinkType.Int64:
                        case enLinkType.Single:
                        case enLinkType.Double:
                        case enLinkType.Byte:
                        case enLinkType.SByte:
                        case enLinkType.Int16:
                        case enLinkType.UInt16:
                        case enLinkType.UInt32:
                        case enLinkType.UInt64:
                        case enLinkType.Float1:
                            linkType = enLinkType.NumbericalValue | enLinkType.Float1 | enLinkType.Float2 | enLinkType.Float3 | enLinkType.Float4;
                            break;

                        case enLinkType.Float2:
                            linkType = enLinkType.Float2 | enLinkType.Float3 | enLinkType.Float4;
                            break;

                        case enLinkType.Float3:
                            linkType = enLinkType.Float3 | enLinkType.Float4;
                            break;
                        }
                        CollectLinkPinInfo(smParam, strType + "_" + nameStr, linkType, enBezierType.Left, enLinkOpType.End, false);
                    }
                    else if (strAttr == "out")
                    {
                        CollectLinkPinInfo(smParam, strType + "_" + nameStr, LinkPinControl.GetLinkTypeFromTypeString(strType), enBezierType.Right, enLinkOpType.Start, true);
                    }
                    else if (strAttr == "inout")
                    {
                        var linkType = LinkPinControl.GetLinkTypeFromTypeString(strType);
                        switch (linkType)
                        {
                        case enLinkType.Int32:
                        case enLinkType.Int64:
                        case enLinkType.Single:
                        case enLinkType.Double:
                        case enLinkType.Byte:
                        case enLinkType.SByte:
                        case enLinkType.Int16:
                        case enLinkType.UInt16:
                        case enLinkType.UInt32:
                        case enLinkType.UInt64:
                        case enLinkType.Float1:
                            linkType = enLinkType.Float1 | enLinkType.Float2 | enLinkType.Float3 | enLinkType.Float4;
                            break;

                        case enLinkType.Float2:
                            linkType = enLinkType.Float2 | enLinkType.Float3 | enLinkType.Float4;
                            break;

                        case enLinkType.Float3:
                            linkType = enLinkType.Float3 | enLinkType.Float4;
                            break;
                        }
                        CollectLinkPinInfo(smParam, strType + "_" + nameStr + "_in", linkType, enBezierType.Left, enLinkOpType.End, false);
                        CollectLinkPinInfo(smParam, strType + "_" + nameStr + "_out", linkType, enBezierType.Right, enLinkOpType.Start, true);
                    }
                    else if (strAttr == "return")
                    {
                        CollectLinkPinInfo(smParam, strType + "_" + nameStr, LinkPinControl.GetLinkTypeFromTypeString(strType), enBezierType.Right, enLinkOpType.Start, true);
                    }
                }
            }
        }
Ejemplo n.º 46
0
        private void checkForUpdate()
        {
            //check for newer version
            System.Diagnostics.FileVersionInfo fv = System.Diagnostics.FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
            double currentVersion = Convert.ToDouble(fv.FileVersion.Replace(".", String.Empty));

            try
            {
                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.DownloadFile("http://www.icechat.net/update.xml", currentFolder + System.IO.Path.DirectorySeparatorChar + "update.xml");
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.Load(currentFolder + System.IO.Path.DirectorySeparatorChar + "update.xml");
                System.Xml.XmlNodeList version = xmlDoc.GetElementsByTagName("version");
                System.Xml.XmlNodeList versiontext = xmlDoc.GetElementsByTagName("versiontext");

                if (Convert.ToDouble(version[0].InnerText) > currentVersion)
                {
                    this.toolStripUpdate.Visible = true;
                }
                else
                {
                    this.toolStripUpdate.Visible = false;
                    CurrentWindowMessage(inputPanel.CurrentConnection, "You are running the latest version of IceChat (" + fv.FileVersion + ") -- Version Online = " + versiontext[0].InnerText, 4, true);
                }
            }
            catch (Exception ex)
            {
                CurrentWindowMessage(inputPanel.CurrentConnection, "Error checking for update:" + ex.Message, 4, true);
            }
        }
Ejemplo n.º 47
0
		public virtual void  TestEncoding()
		{
            String rawDocContent = "\"Smith & sons' prices < 3 and >4\" claims article";
            // run the highlighter on the raw content (scorer does not score any tokens
            // for
            // highlighting but scores a single fragment for selection
            Highlighter highlighter = new Highlighter(this, new SimpleHTMLEncoder(), new AnonymousClassScorer());
            highlighter.SetTextFragmenter(new SimpleFragmenter(2000));
            TokenStream tokenStream = analyzer.TokenStream(FIELD_NAME, new System.IO.StringReader(rawDocContent));

            String encodedSnippet = highlighter.GetBestFragments(tokenStream, rawDocContent, 1, "");
            // An ugly bit of XML creation:
            String xhtml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n"
                + "<head>\n" + "<title>My Test HTML Document</title>\n" + "</head>\n" + "<body>\n" + "<h2>"
                + encodedSnippet + "</h2>\n" + "</body>\n" + "</html>";
            // now an ugly built of XML parsing to test the snippet is encoded OK

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(xhtml);
            System.Xml.XmlNodeList nodes = doc.GetElementsByTagName("body");
            System.Xml.XmlNode body = nodes[0];
            nodes = body.ChildNodes;
            System.Xml.XmlNode h2 = (System.Xml.XmlNode)nodes[0];
            String decodedSnippet = h2.FirstChild.InnerText;
            Assert.AreEqual(rawDocContent, decodedSnippet,"XHTML Encoding should have worked:");
		}
Ejemplo n.º 48
0
 void DeleteHeightAndWidthFromSVGFile(string svgFile) {
     var fullpath = Path.Combine(workingDir, svgFile);
     var xml = new System.Xml.XmlDocument();
     xml.XmlResolver = null;
     xml.Load(fullpath);
     foreach (System.Xml.XmlNode node in xml.GetElementsByTagName("svg")) {
         var attr = node.Attributes["width"];
         if (attr != null) node.Attributes.Remove(attr);
         attr = node.Attributes["height"];
         if (attr != null) node.Attributes.Remove(attr);
     }
     xml.Save(fullpath);
 }
Ejemplo n.º 49
0
		public void readVal(){
			try {
				string strUrl = String.Format("http://{0}/xml", m_strALL_IP);
				HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                //request.Credentials = New System.Net.NetworkCredential( strUser, strPassword);
                request.Method = WebRequestMethods.Http.Get;
	        

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);
                string strResult = sr.ReadToEnd();
                strResult = strResult.Substring(strResult.IndexOf("<xml>"), strResult.IndexOf("</xml>") - strResult.IndexOf("<xml>") +6);
                strResult.Replace("\n","");
                strResult.Replace("\r","");
                response.Close();
            
//                string strResult = "<xml><data><devicename>MySensoren</devicename><n0>0</n0><t0> 32.15</t0><min0> 28.69</min0><max0> 32.60</max0><l0>0</l0><h0>100</h0><s0>65</s0><n1>1</n1><t1> 21.05</t1><min1> 20.18</min1><max1> 23.73</max1><l1>-40</l1><h1>40</h1><s1>3</s1><n2>2</n2><t2> 1020.88</t2><min2> 955.43</min2><max2>-20480.00</max2><l2>850</l2><h2>1035</h2><s2>40</s2><n3>3</n3><t3>-20480.00</t3><min3> 20480.00</min3><max3>-20480.00</max3><l3>-55</l3><h3>150</h3><s3>0</s3><n4>4</n4><t4>-20480.00</t4><min4> 20480.00</min4><max4>-20480.00</max4><l4>-55</l4><h4>150</h4><s4>0</s4><n5>5</n5><t5>-20480.00</t5><min5> 20480.00</min5><max5>-20480.00</max5><l5>-55</l5><h5>150</h5><s5>0</s5><n6>6</n6><t6>-20480.00</t6><min6> 20480.00</min6><max6>-20480.00</max6><l6>-55</l6><h6>150</h6><s6>0</s6><n7>7</n7><t7> 21.68</t7><min7> 19.87</min7><max7> 23.50</max7><l7>-40</l7><h7>40</h7><s7>2</s7><date>08.04.2006</date><time>08:20:32</time><ad>1</ad><i>60</i><f>0</f><sys>28409</sys><mem>31656</mem><fw>2.59</fw><dev>ALL4000</dev></data></xml>";               
                	/*
					 * <n0>0</n0>
					 * <t0> 32.15</t0>
					 * <min0> 28.69</min0>
					 * <max0> 32.60</max0>
					 * <l0>0</l0>
					 * <h0>100</h0>
					 * <s0>65</s0>
					 */
                
                System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
                
                xml.LoadXml(strResult);
				
				string strTag = "";
				switch (m_strALL_SENSOR_VAL) {
					case "MAX":
						strTag = "max";
						break;
					case "MIN":
						strTag = "min";
						break;
					case "CURRENT":
						strTag = "t";
						break;
				}
				m_strRetVal = xml.GetElementsByTagName(strTag + m_strALL_SENSOR_NR)[0].InnerText + ":" + xml.GetElementsByTagName("n" + m_strALL_SENSOR_NR)[0].InnerText;
				setExitCode(0);
			} catch (Exception ex) {
            	m_strRetVal = "-3: Exception:" + ex.Message;
            	setExitCode(2);
        	}
		}
Ejemplo n.º 50
0
		/// <summary>
		/// Xbox connection.
		/// </summary>
		public Xbox()
        {
            // load settings file
            var xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.Load("YeloDebugSettings.xml");

            // check that setting and assembly versions match
            string assemblyVersion = System.Reflection.Assembly.GetExecutingAssembly().FullName.Substring(19, 7);
            string settingsVersion = xmlDoc.GetElementsByTagName("Version")[0].InnerText;
            if (assemblyVersion != settingsVersion) throw new ApiException("YeloDebug version does not match the version of the settings file.");

            // get settings information
            xdkRegistryPath = xmlDoc.GetElementsByTagName("XdkRegistryPath")[0].InnerText;
            //notificationSessionEnabled = Convert.ToBoolean(xmlDoc.GetElementsByTagName("NotificationSession")[0].InnerText);
            //notificationPort = Convert.ToInt32(xmlDoc.GetElementsByTagName("NotificationPort")[0].InnerText);
        }
Ejemplo n.º 51
0
        internal void DownloadUpdatesInformation()
        {
            this.Updater.Progress.ChangeStatus("Descargando información de versiones de " + this.Name);

            if (this.Files == null)
            {
                this.Files = new FileCollection();
            }

            try {
                using (WebClient Cliente = new WebClient()) {
                    Cliente.Encoding = System.Text.Encoding.UTF8;
                    string VerFileUrl  = this.GetFullUrl() + this.Name + ".ver";
                    byte[] VersionInfo = Cliente.DownloadData(VerFileUrl + "?dm=" + new Random().Next().ToString());

                    System.Xml.XmlDocument ArchivoVer = new System.Xml.XmlDocument();
                    System.IO.MemoryStream ms         = new System.IO.MemoryStream(VersionInfo);
                    ArchivoVer.Load(ms);

                    System.Xml.XmlNodeList PackageList = ArchivoVer.GetElementsByTagName("Package");
                    foreach (System.Xml.XmlNode Pkg in PackageList)
                    {
                        string             PkgName = Pkg.Attributes["name"].Value;
                        System.Xml.XmlNode Comp    = ArchivoVer.SelectSingleNode("/VersionInfo/Package[@name='" + PkgName + "']");
                        foreach (System.Xml.XmlNode FileVers in Comp.ChildNodes)
                        {
                            if (FileVers.Name == "File")
                            {
                                if (FileVers.Attributes["name"] != null && FileVers.Attributes["name"].Value != null)
                                {
                                    File   FileVersionInfo;
                                    string FileName = FileVers.Attributes["name"].Value;
                                    if (this.Files.ContainsKey(FileName))
                                    {
                                        // Ya existe en la lista de archivos
                                        FileVersionInfo = this.Files[FileName];
                                    }
                                    else
                                    {
                                        // Lo agrego
                                        FileVersionInfo = new File(this);
                                        this.Files.Add(FileVersionInfo);
                                    }
                                    FileVersionInfo.Name = FileName;
                                    DateTime Fecha;
                                    try {
                                        DateTime.TryParseExact(FileVers.Attributes["version"].Value, Lfx.Types.Formatting.DateTime.SqlDateTimeFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AllowWhiteSpaces, out Fecha);
                                    } catch {
                                        Fecha = DateTime.MinValue;
                                    }
                                    FileVersionInfo.NewVersion = Fecha;

                                    if (FileVers.Attributes["compression"] != null && FileVers.Attributes["compression"].Value != null)
                                    {
                                        switch (FileVers.Attributes["compression"].Value)
                                        {
                                        case "none":
                                        case "":
                                            FileVersionInfo.Compression = CompressionFormats.None;
                                            break;

                                        case "bz2":
                                            FileVersionInfo.Compression = CompressionFormats.Bz2;
                                            break;

                                        default:
                                            FileVersionInfo.Compression = CompressionFormats.OtherUnsupported;
                                            break;
                                        }
                                    }
                                    if (FileVers.Attributes["size"] != null && FileVers.Attributes["size"].Value != null)
                                    {
                                        FileVersionInfo.NewSize = int.Parse(FileVers.Attributes["size"].Value);
                                    }
                                    if (FileVers.Attributes["compsize"] != null && FileVers.Attributes["compsize"].Value != null)
                                    {
                                        FileVersionInfo.NewCompSize = int.Parse(FileVers.Attributes["compsize"].Value);
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                // No pude descargar
                System.Console.WriteLine("Updater: " + ex.Message);
            }
        }
Ejemplo n.º 52
0
        private void GetList()
        {
            System.Xml.XmlDocument objDoc = new System.Xml.XmlDocument();
            try
            {
                objDoc.Load("History.xml");
                System.Xml.XmlNodeList objHistoryNodes = objDoc.GetElementsByTagName("HistoryItem");
                foreach (System.Xml.XmlElement objNode in objHistoryNodes)
                {
                    HistoryItem objItem = new HistoryItem();
                    System.Xml.XmlNodeList objProperties = objNode.ChildNodes;
                    foreach (System.Xml.XmlElement objElement in objProperties)
                    {
                        if (String.Compare(objElement.Name, "ID", true) == 0)
                        {
                            objItem.ID = objElement.InnerText;

                        }
                        else if (String.Compare(objElement.Name, "FromDate", true) == 0)
                        {
                            objItem.FromDate = objElement.InnerText;
                        }
                        else if (String.Compare(objElement.Name, "ToDate", true) == 0)
                        {
                            objItem.ToDate = objElement.InnerText;


                        }



                    }
                    if (DateTime.Parse(objItem.ToDate) > DateTime.Now)
                    {
                        // will only add to list items whos too date has already expired.
                        objHistoryList.Add(objItem);
                    }


                }
            }
            catch (Exception ex)
            {


            }

        }
Ejemplo n.º 53
0
        private UserInfo ReadUserInfo(DbCommand dc)
        {
            #region 用户查询
            string   tmpPermissionList = "";
            string   AreaXml           = "";
            UserInfo User = null;

            using (IDataReader rdr = DbHelper.ExecuteReader(dc, this.SystemStore))
            {
                if (rdr.Read())
                {
                    User             = new UserInfo();
                    User.UserType    = (EyouSoft.Model.EnumType.CompanyStructure.CompanyUserType)rdr.GetByte(rdr.GetOrdinal("UserType"));
                    User.UserName    = rdr.GetString(rdr.GetOrdinal("UserName"));
                    User.CompanyName = rdr.IsDBNull(rdr.GetOrdinal("CompanyName")) ? "" : rdr.GetString(rdr.GetOrdinal("CompanyName"));
                    User.CompanyID   = rdr.GetInt32(rdr.GetOrdinal("CompanyID"));
                    //关联公司编号 根据用户类型区分
                    int tmpCompanyId = rdr.GetInt32(rdr.GetOrdinal("TourCompanyId"));
                    if (User.UserType == EyouSoft.Model.EnumType.CompanyStructure.CompanyUserType.地接用户)
                    {
                        User.LocalAgencyCompanyInfo.CompanyId = tmpCompanyId;
                    }
                    else if (User.UserType == EyouSoft.Model.EnumType.CompanyStructure.CompanyUserType.组团用户)
                    {
                        User.TourCompany.TourCompanyId = tmpCompanyId;
                    }
                    User.SysId = rdr.GetInt32(rdr.GetOrdinal("SystemId"));
                    User.ContactInfo.UserType      = (EyouSoft.Model.EnumType.CompanyStructure.CompanyUserType)rdr.GetByte(rdr.GetOrdinal("UserType"));
                    User.ContactInfo.ContactEmail  = rdr.IsDBNull(rdr.GetOrdinal("ContactEmail")) ? "" : rdr.GetString(rdr.GetOrdinal("ContactEmail"));
                    User.ContactInfo.ContactFax    = rdr.IsDBNull(rdr.GetOrdinal("ContactFax")) ? "" : rdr.GetString(rdr.GetOrdinal("ContactFax"));
                    User.ContactInfo.ContactMobile = rdr.IsDBNull(rdr.GetOrdinal("ContactMobile")) ? "" : rdr.GetString(rdr.GetOrdinal("ContactMobile"));
                    User.ContactInfo.ContactName   = rdr.IsDBNull(rdr.GetOrdinal("ContactName")) ? "" : rdr.GetString(rdr.GetOrdinal("ContactName"));
                    User.ContactInfo.ContactSex    = (EyouSoft.Model.EnumType.CompanyStructure.Sex) int.Parse(rdr.GetString(rdr.GetOrdinal("ContactSex")));
                    User.ContactInfo.ContactTel    = rdr.IsDBNull(rdr.GetOrdinal("ContactTel")) ? "" : rdr.GetString(rdr.GetOrdinal("ContactTel"));
                    User.ContactInfo.QQ            = rdr.IsDBNull(rdr.GetOrdinal("QQ")) ? "" : rdr.GetString(rdr.GetOrdinal("QQ"));
                    User.DepartId        = rdr.IsDBNull(rdr.GetOrdinal("DepartId")) ? 0 : rdr.GetInt32(rdr.GetOrdinal("DepartId"));
                    User.DepartName      = rdr.IsDBNull(rdr.GetOrdinal("DepartName")) ? "" : rdr.GetString(rdr.GetOrdinal("DepartName"));
                    User.JGDepartId      = rdr.IsDBNull(rdr.GetOrdinal("SuperviseDepartId")) ? 0 : rdr.GetInt32(rdr.GetOrdinal("SuperviseDepartId"));
                    User.ID              = rdr.GetInt32(rdr.GetOrdinal("ID"));
                    User.IsAdmin         = rdr.GetString(rdr.GetOrdinal("IsAdmin")) == "1" ? true : false;
                    User.IsEnable        = rdr.GetString(rdr.GetOrdinal("IsEnable")) == "1" ? true : false;
                    User.ContactInfo.MSN = rdr.IsDBNull(rdr.GetOrdinal("MSN")) ? "" : rdr.GetString(rdr.GetOrdinal("MSN"));
                    User.PassWordInfo.SetEncryptPassWord(rdr.IsDBNull(rdr.GetOrdinal("Password")) == true ? "" : rdr.GetString(rdr.GetOrdinal("Password")), rdr.IsDBNull(rdr.GetOrdinal("MD5Password")) == true ? "" : rdr.GetString(rdr.GetOrdinal("MD5Password")));
                    tmpPermissionList = rdr.IsDBNull(rdr.GetOrdinal("PermissionList")) ? "" : rdr.GetString(rdr.GetOrdinal("PermissionList"));
                    AreaXml           = rdr.IsDBNull(rdr.GetOrdinal("AreaId")) ? "" : rdr.GetString(rdr.GetOrdinal("AreaId"));
                }
            }

            if (User != null)
            {
                #region 用户权限
                if (!String.IsNullOrEmpty(tmpPermissionList))
                {
                    string[] PermissionList = tmpPermissionList.Split(',');
                    User.PermissionList = new int[PermissionList.Length];
                    for (int i = 0; i < PermissionList.Length; i++)
                    {
                        User.PermissionList[i] = int.Parse(PermissionList[i]);
                    }
                }
                else
                {
                    User.PermissionList = new int[1] {
                        -1
                    };
                }
                #endregion

                #region 用户线路区域
                if (!String.IsNullOrEmpty(AreaXml))
                {
                    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                    xmlDoc.LoadXml(AreaXml);
                    System.Xml.XmlNodeList NodeList = xmlDoc.GetElementsByTagName("AreaId");
                    User.Areas = new int[NodeList.Count];
                    for (int i = 0; i < NodeList.Count; i++)
                    {
                        if (EyouSoft.Common.Function.StringValidate.IsInteger(NodeList[i].FirstChild.Value))
                        {
                            User.Areas[i] = int.Parse(NodeList[i].FirstChild.Value);
                        }
                    }
                }

                else
                {
                    User.Areas = new int[1] {
                        -1
                    };
                }
                #endregion

                #region 组团用户
                if (User.ContactInfo.UserType == EyouSoft.Model.EnumType.CompanyStructure.CompanyUserType.组团用户 &&
                    User.TourCompany.TourCompanyId != 0)

                {
                    dc.Parameters.Clear();
                    dc = this.SystemStore.GetSqlStringCommand(SQL_TOURUSERCUSTOMER);
                    this.SystemStore.AddInParameter(dc, "CompanyId", DbType.Int32, User.TourCompany.TourCompanyId);
                    using (IDataReader rdr = DbHelper.ExecuteReader(dc, this.SystemStore))
                    {
                        if (rdr.Read())
                        {
                            User.TourCompany.CustomerLevel = rdr.GetInt32(rdr.GetOrdinal("CustomerLev"));
                            User.TourCompany.CompanyName   = rdr.GetString(rdr.GetOrdinal("name"));
                        }
                    }
                }
                #endregion

                #region 地接用户
                if (User.UserType == EyouSoft.Model.EnumType.CompanyStructure.CompanyUserType.地接用户 &&
                    User.LocalAgencyCompanyInfo.CompanyId != 0)
                {
                    dc.Parameters.Clear();
                    dc = this.SystemStore.GetSqlStringCommand(SQL_SELECT_GetGYSCompanyInfo);
                    this.SystemStore.AddInParameter(dc, "CompanyId", DbType.Int32, User.LocalAgencyCompanyInfo.CompanyId);

                    using (IDataReader rdr = DbHelper.ExecuteReader(dc, this.SystemStore))
                    {
                        if (rdr.Read())
                        {
                            User.LocalAgencyCompanyInfo.CompanyName = rdr["UnitName"].ToString();
                        }
                    }
                }
                #endregion

                #region 写登录日志

                dc.Parameters.Clear();
                string GetRemoteIP = EyouSoft.Toolkit.Utils.GetRemoteIP();
                string RequestUrl  = EyouSoft.Toolkit.Utils.GetRequestUrl();

                dc = this.SystemStore.GetSqlStringCommand(SQL_USERLOGIN_LOG);
                this.SystemStore.AddInParameter(dc, "UserId", DbType.Int32, User.ID);
                this.SystemStore.AddInParameter(dc, "LastLoginIP", DbType.String, EyouSoft.Toolkit.Utils.GetRemoteIP());
                this.SystemStore.AddInParameter(dc, "CompanyId", DbType.Int32, User.CompanyID);
                DbHelper.ExecuteSql(dc, this.SystemStore);

                WriteLog(User.CompanyID, User.ID, User.DepartId, GetRemoteIP);

                #endregion
            }

            return(User);

            #endregion
        }
Ejemplo n.º 54
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.º 55
0
        private static void LoadFiles(System.Xml.XmlDocument xmlDocument, Models.Project project)
        {
            foreach (System.Xml.XmlNode node in xmlDocument.GetElementsByTagName("File"))
            {
                Models.Item item = new Models.Item();

                foreach (System.Xml.XmlAttribute attribute in node.Attributes)
                {
                    switch (attribute.LocalName)
                    {
                    case "RelPath":
                    {
                        item.RelPath = node.Attributes["RelPath"].Value;
                        break;
                    }

                    case "SubType":
                    {
                        item.SubType = node.Attributes["SubType"].Value;
                        break;
                    }

                    case "DependentUpon":
                    {
                        item.DependentUpon = node.Attributes["DependentUpon"].Value;
                        break;
                    }

                    case "BuildAction":
                    {
                        item.BuildAction = node.Attributes["BuildAction"].Value;
                        break;
                    }

                    case "Generator":
                    {
                        item.Generator = node.Attributes["Generator"].Value;
                        break;
                    }

                    case "LastGenOutput":
                    {
                        item.LastGenOutput = node.Attributes["LastGenOutput"].Value;
                        break;
                    }

                    case "DesignTime":
                    {
                        item.DesignTime = node.Attributes["DesignTime"].Value;
                        break;
                    }

                    case "AutoGen":
                    {
                        item.AutoGen = node.Attributes["AutoGen"].Value;
                        break;
                    }

                    default:
                    {
                        throw new System.Exception("Unknown project file attribute: " + attribute.LocalName);
                    }
                    }
                }

                project.Items.Add(item);
            }
        }
Ejemplo n.º 56
0
        private void saveConfig(string[] row)
        {
            try
            {
                System.Xml.XmlDocument file = new System.Xml.XmlDocument();
                file.Load(config_file);

                System.Xml.XmlNodeList directoryNode = file.GetElementsByTagName("Directory");
                System.Xml.XmlNodeList countNode = file.GetElementsByTagName("Count");

                foreach(System.Xml.XmlNode node in directoryNode)
                {
                    if(node.Value.ToString() == row[0])
                    {

                    }
                }

            }catch(Exception e)
            {

            }
        }
Ejemplo n.º 57
0
 bool svgconcat(List<string> files, string output, uint delay, uint loop) {
     if (controller_ != null) controller_.appendOutput("TeX2img: Making animation svg...");
     try {
         var outxml = new System.Xml.XmlDocument();
         outxml.XmlResolver = null;
         outxml.AppendChild(outxml.CreateXmlDeclaration("1.0", "utf-8", "no"));
         outxml.AppendChild(outxml.CreateDocumentType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", null));
         var svg = outxml.CreateElement("svg", "http://www.w3.org/2000/svg");
         var attr = outxml.CreateAttribute("xmlns:xlink");
         attr.Value = "http://www.w3.org/1999/xlink";
         svg.Attributes.Append(attr);
         attr = outxml.CreateAttribute("version");
         attr.Value = "1.1";
         svg.Attributes.Append(attr);
         outxml.AppendChild(svg);
         var defs = outxml.CreateElement("defs", "http://www.w3.org/2000/svg");
         svg.AppendChild(defs);
         var idreg = new System.Text.RegularExpressions.Regex(@"(?<!\&)#");
         foreach (var f in files) {
             var id = Path.GetFileNameWithoutExtension(f);
             var xml = new System.Xml.XmlDocument();
             xml.XmlResolver = null;
             xml.Load(Path.Combine(workingDir, f));
             foreach (System.Xml.XmlNode tag in xml.GetElementsByTagName("*")) {
                 foreach (System.Xml.XmlAttribute a in tag.Attributes) {
                     if (a.Name.ToLower() == "id") a.Value = id + "-" + a.Value;
                     else a.Value = idreg.Replace(a.Value, "#" + id + "-");
                 }
             }
             foreach (System.Xml.XmlNode tag in xml.GetElementsByTagName("svg")) {
                 var idattr = xml.CreateAttribute("id");
                 idattr.Value = id;
                 tag.Attributes.Append(idattr);
             }
             foreach (System.Xml.XmlNode n in xml.ChildNodes) {
                 if (n.NodeType != System.Xml.XmlNodeType.DocumentType && n.NodeType != System.Xml.XmlNodeType.XmlDeclaration) {
                     defs.AppendChild(outxml.ImportNode(n, true));
                 }
             }
         }
         var use = outxml.CreateElement("use", "http://www.w3.org/2000/svg");
         svg.AppendChild(use);
         var animate = outxml.CreateElement("animate", "http://www.w3.org/2000/svg");
         use.AppendChild(animate);
         attr = outxml.CreateAttribute("attributeName");
         attr.Value = "xlink:href"; animate.Attributes.Append(attr);
         attr = outxml.CreateAttribute("begin");
         attr.Value = "0s"; animate.Attributes.Append(attr);
         attr = outxml.CreateAttribute("dur");
         attr.Value = ((decimal)(delay * files.Count) / 100).ToString() + "s";
         animate.Attributes.Append(attr);
         attr = outxml.CreateAttribute("repeatCount");
         attr.Value = loop > 0 ? loop.ToString() : "indefinite";
         animate.Attributes.Append(attr);
         attr = outxml.CreateAttribute("values");
         attr.Value = String.Join(";", files.Select(d => "#" + Path.GetFileNameWithoutExtension(d)).ToArray());
         animate.Attributes.Append(attr);
         outxml.Save(Path.Combine(workingDir, output));
         if (controller_ != null) controller_.appendOutput(" done\n");
         return true;
     }
     catch (Exception) { return false; }
 }
Ejemplo n.º 58
0
        public static List<RecordLine> ReadFromXmlFile(String _XmlFilename)
        {
            List<RecordLine> result = new List<RecordLine>();

            if (!String.IsNullOrEmpty(_XmlFilename))
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(_XmlFilename);

                System.Xml.XmlNodeList lines = doc.GetElementsByTagName("RecordLine");
                foreach (System.Xml.XmlNode line in lines)
                {
                    System.Xml.XmlElement lineEle = line as System.Xml.XmlElement;
                    String palletizer = lineEle.GetAttribute("PalletizerName");
                    String readMarkDevice = lineEle.GetAttribute("ReadMarkDevice");
                    String plateCodeDevice = lineEle.GetAttribute("PlateCodeDevice");

                    System.Xml.XmlNodeList records = lineEle.GetElementsByTagName("Record");
                    if (records.Count > 0)
                    {
                        RecordLine recordLine = new RecordLine(palletizer, readMarkDevice, plateCodeDevice);
                        foreach (System.Xml.XmlNode record in records)
                        {
                            System.Xml.XmlElement recordEle = record as System.Xml.XmlElement;
                            String boxCodeDevice = recordEle.GetAttribute("BoxCodeDevice");
                            String amountDevice = recordEle.GetAttribute("AmountDevice");
                            recordLine.AddRecord(new Record(boxCodeDevice, amountDevice));
                        }
                        result.Add(recordLine);
                    }
                }
            }

            return result;
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Detects if a message is a delivery failure notification.
        /// This method uses the default signatures containing in an internal ressource file.
        /// </summary>
        /// <remarks>
        /// Signature files are XML files formatted as follows : 
        /// 
        /// &lt;?xml version='1.0'?&gt;
        /// &lt;signatures&gt;
        ///		&lt;signature from=&quot;postmaster&quot; subject=&quot;Undeliverable Mail&quot; body=&quot;Unknown user&quot; search=&quot;&quot; />
        ///		...
        /// &lt;/signatures&gt;
        /// </remarks>
        /// <returns>A BounceStatus object containing the level of revelance and if 100% identified, the erroneous email address.</returns>
        public new BounceResult GetBounceStatus(string signaturesFilePath)
        {
            string ressource = string.Empty;
            
            if (signaturesFilePath == null || signaturesFilePath == string.Empty)
                ressource = Header.GetResource("ActiveUp.Net.Mail.bouncedSignatures.xml");
            else
                ressource = System.IO.File.OpenText(signaturesFilePath).ReadToEnd();

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(ressource);
            BounceResult result = new BounceResult();

            foreach (System.Xml.XmlElement el in doc.GetElementsByTagName("signature"))
            {
                int bestResult = result.Level;
                result.Level = 0;

                if (el.GetAttribute("from").Trim() != "")
                    if (this.From.Merged.IndexOf(el.GetAttribute("from")) != -1)
                        result.Level++;

                if (this.Subject != null && el.GetAttribute("subject").Trim() != "")
                    if (this.Subject.IndexOf(el.GetAttribute("subject")) != -1)
                        result.Level++;

                if (el.GetAttribute("body").Trim() != "")
                    if (this.BodyText.Text.IndexOf(el.GetAttribute("body")) != -1)
                        result.Level++;

                if (result.Level < bestResult)
                    result.Level = bestResult;

                if (result.Level > 0)
                {
                    int start = 0;
                    string body = this.BodyText.Text;

                    if (el.GetAttribute("body") != string.Empty)
                        start = body.IndexOf(el.GetAttribute("body"));

                    if (start < 0)
                        start = 0;

                    string emailExpression = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
                    System.Text.RegularExpressions.Regex regExp = new System.Text.RegularExpressions.Regex(emailExpression);

                    if (regExp.IsMatch(body, start))
                    {
                        System.Text.RegularExpressions.Match match = regExp.Match(body, start);
                        result.Email = match.Value;
                    }

                    break;
                }
            }

            return result;
        }
Ejemplo n.º 60
0
        void btnAboutVmukti_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                cnvUploadGeneral.Visibility = Visibility.Collapsed;
                cnvUploadMod.Visibility = Visibility.Collapsed;
                cnvPBX.Visibility = Visibility.Collapsed;
                cnvHelp.Visibility = Visibility.Collapsed;
                cnvProfile.Visibility = Visibility.Collapsed;
                cnvSkin.Visibility = Visibility.Collapsed;
                cnvVMuktiVersion.Visibility = Visibility.Collapsed;
                cnvAboutVmukti.Visibility = Visibility.Visible;

                btnAboutVmukti.IsChecked = true;
                btnSkin.IsChecked = false;
                btnProfile.IsChecked = false;
                btnGeneral.IsChecked = false;
                btnAddMod.IsChecked = false;
                btnPBX.IsChecked = false;
                btnHelp.IsChecked = false;
                btnVMuktiVersion.IsChecked = false;



                System.Xml.XmlDocument ConfDoc = new System.Xml.XmlDocument();
                ConfDoc.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + "sqlceds35.dll");
                if (ConfDoc != null)
                {
                    System.Xml.XmlNodeList xmlNodes = null;
                    xmlNodes = ConfDoc.GetElementsByTagName("CurrentVersion");
                    tblVersionNumbre.Text = DecodeBase64String(xmlNodes[0].Attributes["Value"].Value.ToString());
                }
            }
            catch (Exception ex)
            {

            }
        }