Beispiel #1
0
        public string preProcess(string filename)
        {
            string xmlsource = new System.IO.StreamReader(filename).ReadToEnd();

            //If READABLE_CONFIGKEY still hasn't been set, use the ConfigID to do so.
            xmlsource = xmlsource.Replace("$READABLE_CONFIGKEY", TraceJournal.Instance.getSourceFilenameNoExt()).Replace("@READABLE_CONFIGKEY@", TraceJournal.Instance.getSourceFilenameNoExt());

            // double process to make variables within replacement values possible.
            //Console.WriteLine(this.preProcessString(this.preProcessString(this.preProcessFiles(filename, xmlsource))));
            return(this.preProcessString(this.preProcessString(this.preProcessFiles(filename, xmlsource))));
        }
Beispiel #2
-1
        /// <summary>
        /// Inject HTML that displays warning
        /// </summary>
        /// <param name="linkUrl">URL for 'learn more'</param>
        /// <param name="messageText">Override text for mail message</param>
        /// <param name="learnMoreText">Override text for 'Learn more' link</param>
        /// <param name="okText">Override text for OK button</param>
        /// <returns>HTML string that displays message on the bottom of the web page</returns>
        public string Install(string linkUrl = null, string messageText = null, string learnMoreText = null, string okText = null)
        {
            if (_cookieService.Read(CookieName) != "true")
            {
                var assembly = Assembly.GetAssembly(typeof(Consent));

                var hasLink = !IsEmpty(linkUrl);

                var fileName = hasLink ? "script.html" : "scriptnolink.html";

                var html = new StreamReader(assembly.GetManifestResourceStream("EUCookies." + fileName)).ReadToEnd();

                if (hasLink)
                    html = html.Replace("{learnmore}", IsEmpty(learnMoreText)
                                    ? Captions.LearnMore
                                    : learnMoreText)
                                .Replace("{link}", linkUrl);

                return html
                    .Replace("{text}", IsEmpty(messageText) ? Captions.Text : messageText)
                    .Replace("{ok}", IsEmpty(okText) ? Captions.Ok : okText);
            }

            return string.Empty;
        }
        public static Stream ReplaceGrey(Stream stream, Color color)
        {
            string s = new StreamReader (stream).ReadToEnd ();
            s = s.Replace ("#808080", HexConvert(color));
            s = s.Replace ("#8F8F8F", HexConvert(color));
            s = s.Replace ("#6E6E6E", HexConvert(color));
            s = s.Replace ("#5C5C5C", HexConvert(color));
            s = s.Replace ("#737373", HexConvert(color));

            return GenerateStreamFromString (s);
        }
Beispiel #4
-1
        public void RunBrowser(string url, string backUrl, string mdOrder, string paReq)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            string reqPage = new StreamReader(asm.GetManifestResourceStream("RbsPayments.Test.Secure3D.request.html")).ReadToEnd();

            reqPage = reqPage.Replace("{Url}", url);
            reqPage = reqPage.Replace("{BackUrl}", backUrl);
            reqPage = reqPage.Replace("{MdOrder}", mdOrder);
            reqPage = reqPage.Replace("{PaReq}", paReq);

            File.WriteAllText("req.html", reqPage);
            System.Diagnostics.Process.Start(Secure3DTest.Browser, "req.html");
        }
Beispiel #5
-1
        protected virtual void GenerateScript()
        {
            var sb = new StringBuilder();
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Rabbit.WebForms.js"))
            {
                var webformjs = new StreamReader(stream).ReadToEnd();
                webformjs = webformjs.Replace("\r", "").Replace("\n", "");
                sb.Append("<script type=\"text/javascript\">\r\n" + webformjs);
            }
            sb.Append("\r\n$(function () { webForm.init();");

            var fields = this.GetType().GetFields(BindingFlags.Public| BindingFlags.Instance);

            foreach (var field in fields)
            {
                if(field.IsPublic)
                    sb.AppendFormat("webForm['{0}']={1};", field.Name, JsonConvert.SerializeObject(field.GetValue(this)));
            }

            var x = this.Request["__scroll_x"];
            var y = this.Request["__scroll_y"];
            if (!string.IsNullOrWhiteSpace(x) && !string.IsNullOrWhiteSpace(y))
            {
                sb.AppendFormat("window.scrollTo({0},{1});", x, y);
            }
            sb.Append("}); \r\n</script>");

            var script =  sb.ToString();
            this.Write(this.Html.Raw(script));
        }
Beispiel #6
-1
		/// <summary>
		/// Parses an instance from a stream to a CGP file
		/// </summary>
		public RetroShaderPreset(Stream stream)
		{
			var content = new StreamReader(stream).ReadToEnd();
			Dictionary<string, string> dict = new Dictionary<string, string>();

			//parse the key-value-pair format of the file
			content = content.Replace("\r", "");
			foreach (var _line in content.Split('\n'))
			{
				var line = _line.Trim();
				if (line.StartsWith("#")) continue; //lines that are solely comments
				if (line == "") continue; //empty line
				int eq = line.IndexOf('=');
				var key = line.Substring(0, eq).Trim();
				var value = line.Substring(eq + 1).Trim();
				int quote = value.IndexOf('\"');
				if (quote != -1)
					value = value.Substring(quote + 1, value.IndexOf('\"', quote + 1) - (quote + 1));
				else
				{
					//remove comments from end of value. exclusive from above condition, since comments after quoted strings would be snipped by the quoted string extraction
					int hash = value.IndexOf('#');
					if (hash != -1)
						value = value.Substring(0, hash);
					value = value.Trim();
				}
				dict[key.ToLower()] = value;
			}

			//process the keys
			int nShaders = FetchInt(dict, "shaders", 0);
			for (int i = 0; i < nShaders; i++)
			{
				ShaderPass sp = new ShaderPass();
				sp.Index = i;
				Passes.Add(sp);

				sp.InputFilterLinear = FetchBool(dict, "filter_linear" + i, false); //Should this value not be defined, the filtering option is implementation defined.
				sp.OuputFloat = FetchBool(dict, "float_framebuffer" + i, false);
				sp.FrameCountMod = FetchInt(dict, "frame_count_mod" + i, 1);
				sp.ShaderPath = FetchString(dict, "shader" + i, "?"); //todo - change extension to .cg for better compatibility? just change .cg to .glsl transparently at last second?

				//If no scale type is assumed, it is assumed that it is set to "source" with scaleN set to 1.0.
				//It is possible to set scale_type_xN and scale_type_yN to specialize the scaling type in either direction. scale_typeN however overrides both of these.
				sp.ScaleTypeX = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, "scale_type_x" + i, "Source"), true);
				sp.ScaleTypeY = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, "scale_type_y" + i, "Source"), true);
				ScaleType st = (ScaleType)Enum.Parse(typeof(ScaleType), FetchString(dict, "scale_type" + i, "NotSet"), true);
				if (st != ScaleType.NotSet)
					sp.ScaleTypeX = sp.ScaleTypeY = st;

				//scaleN controls both scaling type in horizontal and vertical directions. If scaleN is defined, scale_xN and scale_yN have no effect.
				sp.Scale.X = FetchFloat(dict, "scale_x" + i, 1);
				sp.Scale.Y = FetchFloat(dict, "scale_y" + i, 1);
				float scale = FetchFloat(dict, "scale" + i, -999);
				if (scale != -999)
					sp.Scale.X = sp.Scale.Y = FetchFloat(dict, "scale" + i, 1);

				//TODO - LUTs
			}
		}
 private string ReadResource(string resourceName)
 {
     using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Knockout.Tests." + resourceName)) {
         var result = new StreamReader(s).ReadToEnd();
         return result.Replace("\r\n", "\n");
     }
 }
Beispiel #8
-1
        private void buttonParse_Click( object sender , EventArgs e )
        {
            var req = WebRequest.Create(this.textBoxInputUrl.Text);
            string html = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd();

            HtmlDocument htmlDocument;
            XmlDocument  doc = new XmlDocument();

            //html = Regex.Match(html, @"/^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/").Value;
            doc.LoadXml(html.Replace("\n","").Replace("\r",""));
            var table = doc.GetElementsByTagName("table").Item(0);

            var nodes =table.FirstChild.ChildNodes;

            string lastVersion = "-1";
            int rowCount = 0;

            XmlDocument document = new XmlDocument();

            StringBuilder str = new StringBuilder();

            foreach (XmlNode nodeTr in nodes)
            {
                str.Append( "{ ");
                str.Append ( System.Environment.NewLine );
                //if (nodeTr.FirstChild.Attributes["rowspan"]!=null)
                //{
                //	lastVersion = nodeTr.FirstChild.FirstChild.Value;
                //}
                //else
                //{
                //	str.Append ( lastVersion + ", " );
                //}
                for (int i = 1; i < nodeTr.ChildNodes.Count-1; i++)
                {
                    try {
                        str.Append ( "MaskPatterns.Pattern"+nodeTr.ChildNodes[i].FirstChild.Value + ", " );
                    }
                    catch ( NullReferenceException ) {

                    }
                }

                str.Append ( System.Environment.NewLine );
                try {
                    str.Append ("new bool[] {"+ nodeTr.ChildNodes[nodeTr.ChildNodes.Count - 1].FirstChild.Value.Replace("0","false, ").Replace("1","true,")+"}" + System.Environment.NewLine+ " },");
                }
                catch ( NullReferenceException ) {

                    str.Append ( System.Environment.NewLine );
                    str.Append ( " }," );
                }
                str.Append( System.Environment.NewLine);
            }

            this.textBoxOutput.Text = str.ToString ().Replace ( "QR Version " , "" );
            //this.textBoxOutput.Text = str.ToString();
        }
 public static string GetTestDataTemplate(int index, string table, string filename, string tableName)
 {
     var template = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("DatabaseVersionControl.Cmd.Templates.TestSqlTemplate.txt")).ReadToEnd();
     template = template.Replace("%Index%", index.ToString())
         .Replace("%Description%", "Insert test data for table "+table)
         .Replace("%DateTime%", DateTime.Now.ToExactFormatString())
         .Replace("%Filename%", Path.GetFileName(filename))
         .Replace("%TableName%", tableName);
     return template;
 }
 public static string GetFileTemplate(string exportSchemaFileName, string connectionString, string outputFileName, string schemaFileName, string[] additionalUpdates)
 {
     var template = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("DatabaseVersionControl.Cmd.Templates.NewExportTemplate.txt")).ReadToEnd();
     template = template.Replace("%ConnectionString%", connectionString)
         .Replace("%DatabaseName%", Path.GetFileNameWithoutExtension(outputFileName))
         .Replace("%DateTime%", DateTime.Now.ToExactFormatString())
         .Replace("%ExportFileName%", Path.GetFileName(schemaFileName))
         .Replace("%AdditionalUpdates%", string.Join("\n", additionalUpdates));
     return template;
 }
Beispiel #11
-1
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            EditText myName = FindViewById<EditText>(Resource.Id.txtName);
            EditText myPwd = FindViewById<EditText>(Resource.Id.txtPwd);
            Button login = FindViewById<Button>(Resource.Id.btnLogin);

            login.Click += delegate
           {
               string name = myName.Text;
               string pwd = myPwd.Text;

               if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pwd))
               {
                   Toast.MakeText(this, "请输入用户名和密码!!", ToastLength.Long).Show();
                   return;
               }
               else
               {
                   string loginUrl = string.Format("http://192.168.1.102:8077/User/LogOn?userName={0}&userPwd={1}", name, pwd);

                   var httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(loginUrl));
                   var httpRes = (HttpWebResponse)httpReq.GetResponse();
                   if (httpRes.StatusCode == HttpStatusCode.OK)
                   {
                       string result = new StreamReader(httpRes.GetResponseStream()).ReadToEnd();

                       result = result.Replace("\"", "'");

                       ReturnModel s = JsonConvert.DeserializeObject<ReturnModel>(result);

                       if (s.Code == "00000")
                       {
                           var intent = new Intent(this, typeof(UserActivity));

                           intent.PutExtra("name", name);

                           StartActivity(intent);
                       }
                       else
                       {
                           Toast.MakeText(this, "用户名或密码不正确!!", ToastLength.Long).Show();
                           return;
                       }
                   }
               }
           };
        }
        internal static string ReplaceInDocument(string documentPath, IEnumerable<Replacement> replacements)
        {
            string newString;
            using (var stream = new FileStream(documentPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                newString = new StreamReader(stream).ReadToEnd();

                foreach (Replacement replacement in replacements)
                {
                    newString = newString.Replace(replacement.OldString, replacement.NewString);
                }
            }
            return newString;
        }
 public static void Main(string [] args)
 {
     var imp = new DominoModuleXmlImporter ();
     var ds = new DataContractJsonSerializer (typeof (MidiModuleDefinition));
     foreach (string arg in args) {
         var mod = imp.Import (arg);
         var ms = new MemoryStream ();
         ds.WriteObject (ms, mod);
         ms.Position = 0;
         var s = new StreamReader (ms).ReadToEnd ();
         s = s.Replace ("},", "},\n");
         using (var sw = File.CreateText (Path.ChangeExtension (arg, "midimod")))
             sw.Write (s);
     }
 }
Beispiel #14
-1
        public override object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
        {
            if ( EhRequisicaoJson( controllerContext ) )
            {
                string jsonData = new StreamReader( controllerContext.RequestContext.HttpContext.Request.InputStream ).ReadToEnd();

                if ( jsonData.StartsWith( Root ) )
                {
                    jsonData = jsonData.Replace( Root, "" );
                    jsonData = jsonData.Substring( 0, jsonData.Length - 1 );
                }

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                return serializer.Deserialize( jsonData, bindingContext.ModelMetadata.ModelType );
            }

            return base.BindModel( controllerContext, bindingContext );
        }
Beispiel #15
-1
        public XS1ActuatorList getXS1ActuatorList(String XS1_URL, String Username, String Password)
        {
            // TODO: more error handling !!!

            // check if we already cached something
            if (ActuatorListCache != null)
            {
                if ((DateTime.Now - LastActuatorListUpdated).TotalMinutes < ConfigurationCacheMinutes)
                    return ActuatorListCache;
            }

            // now we got the parameters, we need to find out which actors and which functions shall be called
            WebRequest wrGetURL = WebRequest.Create("http://" + XS1_URL + "/control?user="******"&pwd=" + Password + "&callback=actorlist&cmd=get_list_actuators");

            String _UsernameAndPassword = Username + ":" + Password;
            String _AuthorizationHeader = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(_UsernameAndPassword));

            wrGetURL.Credentials = new NetworkCredential(Username, Password);
            wrGetURL.Headers.Add("Authorization", _AuthorizationHeader);
            HttpWebResponse response = (HttpWebResponse)wrGetURL.GetResponse();
            // check for eventual errors
            if (response.StatusCode != HttpStatusCode.OK)
            {
                // TODO: refactor to correct http response codes
                return null;
            }
            // we will read data via the response stream
            String actuator_config_json = new StreamReader(response.GetResponseStream()).ReadToEnd();

            JavaScriptSerializer ser = new JavaScriptSerializer();
            ser.MaxJsonLength = 20000000;

            // remove the javascript callback/definitions
            actuator_config_json = actuator_config_json.Replace("actorlist(", "");
            actuator_config_json = actuator_config_json.Remove(actuator_config_json.Length - 4, 4);

            // deserialize the XS1 configuration json stream
            ActuatorListCache = ser.Deserialize<XS1ActuatorList>(actuator_config_json);

            LastActuatorListUpdated = DateTime.Now;

            return ActuatorListCache;
        }
Beispiel #16
-1
		public static string OCR(string filename) {
			string str2;
			object obj2;
			Monitor.Enter(obj2 = mutex);
			try {
				string str;

				string workingDirectory = Path.GetTempPath();
				if (File.Exists(workingDirectory + @"\tesseract.exe") == false) {
					using (Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("GodLesZ.Library.Captcha.tesseract.exe")) {
						byte[] buf = new byte[s.Length];
						s.Read(buf, 0, buf.Length);
						File.WriteAllBytes(workingDirectory + @"\tesseract.exe", buf);
					}
				}
				Run("tesseract.exe", Path.GetFileName(filename) + " tesseract-output", workingDirectory, 0);

				using (FileStream stream = new FileStream(workingDirectory + @"\tesseract-output.txt", FileMode.Open)) {
					str = new StreamReader(stream).ReadToEnd();
				}
				try {
					File.Delete(workingDirectory + @"\tesseract-output.txt");
				} catch { }
				try {
					File.Delete(workingDirectory + @"\tesseract.exe");
				} catch { }

				str = str.Replace(" ", "").Replace("\n", "").Replace("\r", "").Replace("\t", "");
				if (str.Length == 0) {
					return null;
				}
				str2 = str;
			} catch (ThreadAbortException) {
				throw;
			} catch (Exception) {
				str2 = null;
			} finally {
				Monitor.Exit(obj2);
			}
			return str2;
		}
		public static void GenerateDesignerFile (string resxfile, string @namespace, string classname, string designerfile)
		{
			var doc = XDocument.Load (resxfile).Root;
			
			var filetemplate = new StreamReader (System.Reflection.Assembly.GetExecutingAssembly ().GetManifestResourceStream ("ResxDesignerGenerator.HeaderTemplate.txt")).ReadToEnd ();
			var elementtemplate = new StreamReader (System.Reflection.Assembly.GetExecutingAssembly ().GetManifestResourceStream ("ResxDesignerGenerator.ElementTemplate.txt")).ReadToEnd ();

			var sb = new StringBuilder ();
			foreach (var node in 
				from d in (from n in doc.Descendants() where n.Name == "data" select n)
				let name = d.Attribute("name").Value
				let value = d.Descendants().First().Value
				orderby name
				select new { Name = name, Value = value }
				) {
				sb.Append (elementtemplate.Replace ("{name}", node.Name).Replace ("{value}", System.Web.HttpUtility.HtmlEncode (node.Value.Trim ().Replace ("\r\n", "\n").Replace ("\r", "\n").Replace ("\n", "\r\n        ///"))));
				sb.Append ("\r\n");
			}
				
			using (var w = new StreamWriter(designerfile, false, Encoding.UTF8))
				w.Write (filetemplate.Replace ("{runtime-version}", System.Environment.Version.ToString ()).Replace ("{namespace}",  @namespace).Replace ("{classname}", classname).Replace ("{elementdata}", sb.ToString ().Trim ()));
		}
Beispiel #18
-1
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event and try to resolve the raw data for the error page.
        /// At the end, outputs the raw data of the content we want to display.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // initial parameters
            Language lang = UrlUtil.ResolveLanguage();
            SiteContext site = UrlUtil.ResolveSite(lang);
            string url = string.Empty;

            // Use the static error page if the site or the database is not available
            if (site == null || site.Database == null) {
                url = Sitecore.Web.WebUtil.GetServerUrl() + Sitecore.Configuration.Settings.GetSetting(SettingsKey + ".Static");
            }
            else {
                string availableLanguages = site.Properties["availableLanguages"];

                // general options for generating url
                UrlOptions options = UrlOptions.DefaultOptions;
                options.LanguageEmbedding = LanguageEmbedding.Always;
                options.LanguageLocation = LanguageLocation.QueryString;
                options.Language = lang;
                options.Site = site;
                options.AlwaysIncludeServerUrl = true;

                // get the error item
                string path = Settings.GetBoolSetting("ErrorManager.UseRootPath", false) ? site.RootPath : site.StartPath;
                Item item = site.Database.GetItem(path + Sitecore.Configuration.Settings.GetSetting(SettingsKey + ".Item"));

                // resolve the url for the error page
                if (item != null && item.HasLanguageVersion(lang, availableLanguages))
                {
                    url = LinkManager.GetItemUrl(item, options);
                }
                else
                {
                    Language.TryParse(!string.IsNullOrEmpty(site.Properties["language"]) ? site.Properties["language"] : LanguageManager.DefaultLanguage.Name, out lang);
                    if (item != null && lang != null && item.HasLanguageVersion(lang, availableLanguages))
                    {
                        options.Language = lang;
                        url = LinkManager.GetItemUrl(item, options);
                    }
                    else
                    {
                        url = Sitecore.Web.WebUtil.GetServerUrl() + Sitecore.Configuration.Settings.GetSetting(SettingsKey + ".Static");
                    }
                }

                // append current raw url
                url += url.IndexOf("?") == -1 ? "?" : "&";
                url += "rawUrl=" + Server.UrlEncode(Sitecore.Web.WebUtil.GetRawUrl());
            }

            // parse the page
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            bool ignoreInvalidSSLCertificates = Sitecore.Configuration.Settings.GetBoolSetting("ErrorManager.IgnoreInvalidSSLCertificates", false);

            // add user cookies to the request
            if (Sitecore.Configuration.Settings.GetBoolSetting("ErrorManager.SendClientCookies", false))
            {
                request.CookieContainer = new CookieContainer();
                HttpCookieCollection userCookies = Request.Cookies;
                for (int userCookieCount = 0; userCookieCount < userCookies.Count; userCookieCount++)
                {
                    HttpCookie httpCookie = userCookies.Get(userCookieCount);
                    if (httpCookie.Name != "ASP.NET_SessionId")
                    {
                        Cookie cookie = new Cookie();
                        /*  We have to add the target host because the cookie does not contain the domain information.
                            In this case, this behaviour is not a security issue, because the target is our own platform.
                            Further information: http://stackoverflow.com/a/460990
                        */
                        cookie.Domain = request.RequestUri.Host;
                        cookie.Expires = httpCookie.Expires;
                        cookie.Name = httpCookie.Name;
                        cookie.Path = httpCookie.Path;
                        cookie.Secure = httpCookie.Secure;

                        // Encode cookie value for handling commas (and other possibly unsupported chars)
                        // Furhter information: http://stackoverflow.com/q/1136405
                        cookie.Value = HttpUtility.UrlEncode(httpCookie.Value);

                        request.CookieContainer.Add(cookie);
                    }
                }
            }

            HttpWebResponse response = null;
            bool hasAddedValidationCallback = false;

            try
            {
                int timeout = 0;
                Int32.TryParse(Sitecore.Configuration.Settings.GetSetting("ErrorManager.Timeout"), out timeout);
                if (timeout == 0)
                {
                    timeout = 60*1000;
                }

                int maxRedirects = 0;
                Int32.TryParse(Sitecore.Configuration.Settings.GetSetting("ErrorManager.MaxRedirects"), out maxRedirects);
                if (maxRedirects == 0)
                {
                    maxRedirects = 3;
                }

                if (ignoreInvalidSSLCertificates)
                {
                    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
                    hasAddedValidationCallback = true;
                }

                // do the request
                request.Timeout = timeout;
                request.MaximumAutomaticRedirections = maxRedirects;
                response = (HttpWebResponse) request.GetResponse();
            }
            catch (WebException ex)
            {
                // we need to catch this, because statuscode of the sitecore default error pages may throwing an exception in the HttpWebResponse object
                response = (HttpWebResponse) ex.Response;
            }
            finally
            {
                // Remove the custom RemoteCertificateValidationCallback due to the global nature of the ServicePointManager
                if (hasAddedValidationCallback)
                {
                    ServicePointManager.ServerCertificateValidationCallback -= new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
                }
            }

            // outputs the page
            if (response != null)
            {
                string body = new StreamReader(response.GetResponseStream()).ReadToEnd();

                // Insert image with request to the static page if Analytics is enabled.
                // This is a hotfix for a Sitecore bug, see Sitecore issue #378950
                if (Settings.GetBoolSetting("Analytics.Enabled", false) && site.EnableAnalytics)
                {
                    body = body.Replace("</body>", string.Format("<img src=\"{0}?{1}\" height=\"1\" width=\"1\" border=\"0\"></body>", Sitecore.Configuration.Settings.GetSetting(SettingsKey + ".Static"), base.Request.QueryString));
                }

                Response.Write(body);
            }
            else
            {
                Response.Write("Statuscode: " + StatusCode);
            }

            // set statuscode
            if (StatusCode > 0)
            {
                Response.StatusCode = StatusCode;
            }

            // pass through the response we create here
            Response.TrySkipIisCustomErrors = true;
        }
        public void HandleUrl(Uri uri, string annotationFilePath)
        {
            var key = uri.Query.Substring(uri.Query.IndexOf('=') + 1);
            var data = (from item in _recentLinks where item.Key == key select item).FirstOrDefault();
            if (data == null)
            {
                Debug.Fail("page has more links than we can currently handle");
                return; // give up.
            }
            var content = data.Data;
            try
            {
                var doc = new XmlDocument();
                var conflict = Conflict.CreateFromConflictElement(XmlUtilities.GetDocumentNodeFromRawXml(content, doc));
                var html = @"<html>" + conflict.HtmlDetails + @"</html>";
                if (HtmlAdjuster != null)
                    html = HtmlAdjuster(html);
                if (string.IsNullOrEmpty(html))
                {
                    MessageBox.Show(LocalizationManager.GetString("Messages.NoDetailsRecorded", "Sorry, no conflict details are recorded for this conflict (it might be an old one). Here's the content:") + "\r\n" + content);
                    return;
                }
                using (var conflictForm = new ConflictDetailsForm())
                {
                    doc.LoadXml(content);
                    var detailAttr = doc.DocumentElement.Attributes["htmlDetails"];
                    if (detailAttr != null)
                        doc.DocumentElement.SetAttribute("htmlDetails", "...(see above)...");
                    MemoryStream mStream = new MemoryStream();
                    var settings = new XmlWriterSettings() {NewLineOnAttributes = true, Encoding = Encoding.UTF8, Indent = true};
                    var writer = XmlWriter.Create(mStream, settings);
                    doc.WriteContentTo(writer);
                    writer.Flush();
                    mStream.Flush();
                    mStream.Position = 0;
                    var prettyContent = new StreamReader(mStream).ReadToEnd();

                    // Insert the technical details into the original HTML right at the end.
                    int endOfBody = html.LastIndexOf("</body>");
                    var techHtml = html.Substring(0, endOfBody)
                        + "<div style='margin-top:10pt'>Source file: "
                        + annotationFilePath.Replace("<", "&lt;").Replace(">", "&gt;")
                        + "</div><PRE>"
                        + prettyContent.Replace("<", "&lt;").Replace(">", "&gt;")
                        + "</PRE>"
                        + html.Substring(endOfBody);

                    conflictForm.TechnicalDetails = techHtml;
                    conflictForm.SetDocumentText(html);
                    conflictForm.ShowDialog(Form.ActiveForm);
                    return;
                }
            }
            catch (Exception)
            {
            }
            MessageBox.Show(LocalizationManager.GetString("Messages.DetailsNotWorking", "Sorry, conflict details aren't working for this conflict (it might be an old one). Here's the content:") + "\r\n" + content);//uri.ToString());
        }
Beispiel #20
-1
 /// <summary>
 /// Permet de récupérer la liste des utilisateurs ayant répondu dernièrement aux sujet
 /// </summary>
 /// <returns>Un array de string comprenant tous les utilisateurs</returns>
 public static List<string> LastReplyByUsers()
 {
     List<string> xx = new List<string>();
     var entries =
         Helpers.GetStringInBetween("<td>Sujet</td><td>Heure&nbsp;</td><td>Auteur</td><td>Derniers</td><td>Forum</td>",
             "</table></td>", Forum, false, false);
     var x = 0;
     while (x < 15)
     {
         entries = entries.Replace("<tr class=\"trow1 smalltext\" style=\"\">", null);
         entries = entries.Replace("<td>", null);
         entries = entries.Replace(
             "<img src=\"/images/prostats/ps_minion.gif\" style=\"vertical-align:middle;\" alt=\"\"/>&nbsp;",
             null);
         entries = entries.Replace(
             "<img src=\"/images/prostats/ps_minioff.gif\" style=\"vertical-align:middle;\" alt=\"\"/>&nbsp;",
             null);
         entries = entries.Replace("</tr>", null);
         x++;
     }
     File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + @"\" + "HFB_users2.txt",entries);
     var file_users = AppDomain.CurrentDomain.BaseDirectory + @"\" + "HFB_users2.txt";
     var sr = new StreamReader(file_users).ReadToEnd();
     var user12delet = Helpers.GetStringInBetween("<strong>", "</strong>", sr, true, true);
     sr.Replace(sr, user12delet);
     //
     var user1 = GetLine(file_users, 8);
     var cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>"+userB+"</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     string user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 15);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 22);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 29);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 36);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 43);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 50);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 57);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 64);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 71);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 78);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 85);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 92);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 99);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     //
     user1 = GetLine(file_users, 106);
     cbdefois = Regex.Matches(user1, "<strong>").Count;
     if (cbdefois == 2)
     {
         string userB = Helpers.GetStringInBetween("<strong>", "</strong>", user1, true, true);
         userB = userB.Replace("<del>", "");
         userB = userB.Replace("</del>", "");
         userB = userB.Replace("<strong>", "");
         userB = userB.Replace("</strong>", "");
         user1 = user1.Replace("<strong>" + userB + "</strong>", null);
         if (!xx.Contains(userB))
         {
             xx.Add(userB);
         }
     }
     user = Helpers.GetStringInBetween("<strong>", "</strong>", user1, false, false);
     user.Replace("<del>", "");
     user.Replace("</del>", "");
     if (!xx.Contains(user))
     {
         xx.Add(user);
     }
     return xx;
 }
        private string ReadFile(string fileName, ArrayList errors, out XmlDocument document)
        {
            string baseClass = null;
            try
            {
                string cleandown = new StreamReader(fileName).ReadToEnd();
                cleandown = "<DOCUMENT_ELEMENT>" + cleandown + "</DOCUMENT_ELEMENT>";

                cleandown = cleandown.Replace("System.Windows.Forms.Label, CustomPanelControl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                cleandown = cleandown.Replace("Uhr.Uhrzeit, Uhr, Version=1.0.5388.24524, Culture=neutral, PublicKeyToken=null", "System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                cleandown = cleandown.Replace("Fixed, CustomPanelControl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Windows.Forms.ContainerControl, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(cleandown);
                foreach (XmlNode node in doc.DocumentElement.ChildNodes)
                {
                    if (baseClass == null)
                    {
                        baseClass = node.Attributes["name"].Value;
                    }
                    if (node.Name.Equals("Object"))
                    {
                        this.ReadObject(node, errors);
                    }
                    else
                    {
                        errors.Add(string.Format("Node type {0} is not allowed here.", node.Name));
                    }
                }
                document = doc;
            }
            catch (Exception ex)
            {
                document = null;
                errors.Add(ex);
            }
            return baseClass;
        }
        public static string RenderCfdChartSettingsInput(this HtmlHelper html, string path, int xAxisMax)
        {
            var settings = new StreamReader(HttpContext.Current.Server.MapPath(path)).ReadToEnd();

            return string.Format("<div style=\"display:none;\" id=\"ChartSettingsPath\" >{0}</div>",
                                 settings.Replace("#xAxis", xAxisMax.ToString()).Replace('\"', '\''));
        }
Beispiel #23
-1
        protected void grvOrders_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToLower().Equals("page"))
            {
                return;
            }

            string mailBody = string.Empty;
            string mailSubject = string.Empty;

            int toStatus=0;
            if (e.CommandName.ToLower().Equals("isprocessing"))
            {
                toStatus=(int)OrderStatus.IsProcessing;
                mailSubject = "您的订单被受理";
                
            }
            else if (e.CommandName.ToLower().Equals("notpass"))
            {
                toStatus=(int)OrderStatus.NotPass;
                mailSubject = "您的订单没有被受理";
            }
            else if (e.CommandName.ToLower().Equals("selectimage"))
            {
                //toStatus=(int)OrderStatus.IsProcessing;
            }
            else if (e.CommandName.ToLower().Equals("complete"))
            {
                toStatus=(int)OrderStatus.Completed;
                mailSubject = "您的订单已经完成,请上线查看相关图片";
            }
            string id = e.CommandArgument.ToString();



            QJVRMS.Business.Orders obj = new QJVRMS.Business.Orders();
            if(obj.UpdateStatus(id,toStatus))
            {
                
                ShowMessage("操作完成");
                bindMyOrders();



                //发送邮件
                mailBody = "订单";
                try
                {
                    DataSet ds = obj.GetOrdersById(id);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataRow dr = ds.Tables[0].Rows[0];

                        string _title = dr["title"].ToString();
                        string _rd = dr["RequestDate"].ToString();
                        string _size = dr["RequestSize"].ToString();
                        string _usage = dr["usage"].ToString();
                        string _content = dr["contents"].ToString();
                        string _addDate = dr["AddDate"].ToString();
                        string _userName = dr["userName"].ToString();
                        

                        MemberShipManager objUserOP = new MemberShipManager();
                        User objUser = objUserOP.GetUser(dr["userName"].ToString());
                        string _userRealName = objUser.UserName;
                        string _userEmail = objUser.Email;

                        string templatePath = Server.MapPath("../orderMailTemplate.htm");
                        mailBody = new StreamReader(templatePath).ReadToEnd();
                        mailBody = mailBody.Replace("{txtAddDate}", _addDate);
                        mailBody = mailBody.Replace("{txtUserName}", _userName);
                        mailBody = mailBody.Replace("{txtUserRealName}", _userRealName);
                        mailBody = mailBody.Replace("{txtContents}", _content.Replace("\r\n", "<br>"));
                        mailBody = mailBody.Replace("{txtUsage}", _usage);
                        mailBody = mailBody.Replace("{txtRD}", _rd);
                        mailBody = mailBody.Replace("{txtTitle}", _title);
                        //mailBody = mailBody.Replace("{host}", Request.Url.Authority);
                        //mailBody = mailBody.Replace("{apppath}", Request.ApplicationPath);
                        string link = "<a href='http://{0}/{1}/Modules/UserProfile.aspx?tabid=2&orderStatus=" + toStatus.ToString() + "' target='_blank'>去我的订单中查看详细信息</a>";
                        mailBody = mailBody.Replace("{link}", string.Format(link, Request.Url.Authority, Request.ApplicationPath));
                        Session["MailBody"] = mailBody;
                        //obj.sendNewOrderToUser(_userEmail, mailSubject, mailBody);
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript'>sendMail('" + _userEmail + "', '" + mailSubject + "')</script>");
                    }

                }
                catch (Exception ex)
                {
                    LogWriter.WriteExceptionLog(ex);
                }


                


            }
           
        }
        /// <summary>
        ///     Loads from the unofficial online tool
        /// </summary>
        public static void LoadBuildFromPoezone(SkillTree tree, string buildUrl)
        {
            if (!buildUrl.Contains('#')) throw new FormatException();

            const string dataUrl = "http://poezone.ru/skilltree/data.js";
            const string buildPostUrl = "http://poezone.ru/skilltree/";
            string build = buildUrl.Substring(buildUrl.LastIndexOf('#') + 1);

            string dataFile, buildFile;
            {
                var req = (HttpWebRequest) WebRequest.Create(dataUrl);
                req.UserAgent =
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30";
                WebResponse resp = req.GetResponse();
                dataFile = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }

            {
                string postData = "build=" + build;
                byte[] postBytes = Encoding.ASCII.GetBytes(postData);
                var req = (HttpWebRequest) WebRequest.Create(buildPostUrl);
                req.Method = "POST";
                req.ContentLength = postBytes.Length;
                req.ContentType = "application/x-www-form-urlencoded";
                req.UserAgent =
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30";
                req.Accept = "application/json, text/javascript, */*; q=0.01";
                req.Host = "poezone.ru";
                req.Referer = "http://poezone.ru/skilltree/";
                req.AutomaticDecompression = DecompressionMethods.GZip;
                //req.Headers.Add( "Accept", "application/json, text/javascript" );
                req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
                req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
                req.Headers.Add("Accept-Language", "en-US,en;q=0.8");

                //req.Headers.Add( "Connection", "keep-alive" );
                //req.Headers.Add( "Host", "poezone.ru" );
                req.Headers.Add("Origin", "http://poezone.ru");
                //req.Headers.Add( "Referer", "http://poezone.ru/skilltree/" );
                //req.Headers.Add( "User-Agent", );
                req.Headers.Add("X-Requested-With", "XMLHttpRequest");
                req.Expect = "";
                req.Credentials = CredentialCache.DefaultCredentials;

                Stream dataStream = req.GetRequestStream();
                dataStream.Write(postBytes, 0, postBytes.Length);
                dataStream.Close();

                WebResponse resp = req.GetResponse();
                string status = (resp as HttpWebResponse).StatusDescription;
                buildFile = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }

            if (!buildFile.Contains("["))
            {
                Popup.Error(string.Format(L10n.Message("An error occured while attempting to load Skill tree from {0} location."), "poezone.ru"));
                return;
            }

            // position decompose
            var positions = new List<Vector2D?>();
            string[] lines = dataFile.Split('\n');
            foreach (string line in lines)
                if (line.StartsWith("skillpos="))
                {
                    string posString = line.Substring(line.IndexOf('[') + 1,
                        line.LastIndexOf(']') - line.IndexOf('[') - 1);
                    var sb = new StringBuilder();
                    bool inBracket = false;
                    foreach (char c in posString)
                    {
                        if (!inBracket && c == ',')
                        {
                            positions.Add(sb.Length == 0
                                ? null
                                : new Vector2D?(new Vector2D(
                                    int.Parse(sb.ToString().Split(',')[0]),
                                    int.Parse(sb.ToString().Split(',')[1])
                                    )));
                            sb.Clear();
                        }
                        else
                        {
                            if (c == '[') inBracket = true;
                            else if (c == ']') inBracket = false;
                            else sb.Append(c);
                        }
                    }
                    positions.Add(sb.Length == 0
                        ? null
                        : new Vector2D?(new Vector2D(
                            int.Parse(sb.ToString().Split(',')[0]),
                            int.Parse(sb.ToString().Split(',')[1])
                            )));
                }

            // min max
            double minx = float.MaxValue, miny = float.MaxValue, maxx = float.MinValue, maxy = float.MinValue;
            foreach (var posn in positions)
            {
                if (!posn.HasValue) continue;
                Vector2D pos = posn.Value;
                minx = Math.Min(pos.X, minx);
                miny = Math.Min(pos.Y, miny);
                maxx = Math.Max(pos.X, maxx);
                maxy = Math.Max(pos.Y, maxy);
            }

            double nminx = float.MaxValue, nminy = float.MaxValue, nmaxx = float.MinValue, nmaxy = float.MinValue;
            foreach (SkillNode node in SkillTree.Skillnodes.Values)
            {
                Vector2D pos = node.Position;
                nminx = Math.Min(pos.X, nminx);
                nminy = Math.Min(pos.Y, nminy);
                nmaxx = Math.Max(pos.X, nmaxx);
                nmaxy = Math.Max(pos.Y, nmaxy);
            }

            //respose
            string[] buildResp = buildFile.Replace("[", "").Replace("]", "").Split(',');
            int character = int.Parse(buildResp[0]);
            var skilled = new List<int>();

            tree.Chartype = character;
            tree.SkilledNodes.Clear();
            SkillNode startnode =
                SkillTree.Skillnodes.First(nd => nd.Value.Name == SkillTree.CharName[tree.Chartype].ToUpper()).Value;
            tree.SkilledNodes.Add(startnode.Id);

            for (int i = 1; i < buildResp.Length; ++i)
            {
                if (!positions[int.Parse(buildResp[i])].HasValue) Debugger.Break();

                Vector2D poezonePos = (positions[int.Parse(buildResp[i])].Value - new Vector2D(minx, miny))*
                                      new Vector2D(1/(maxx - minx), 1/(maxy - miny));
                double minDis = 2;
                var minNode = new KeyValuePair<ushort, SkillNode>();
                foreach (var node in SkillTree.Skillnodes)
                {
                    Vector2D nodePos = (node.Value.Position - new Vector2D(nminx, nminy))*
                                       new Vector2D(1/(nmaxx - nminx), 1/(nmaxy - nminy));
                    double dis = (nodePos - poezonePos).Length;
                    if (dis < minDis)
                    {
                        minDis = dis;
                        minNode = node;
                    }
                }

                tree.SkilledNodes.Add(minNode.Key);
            }
            tree.UpdateAvailNodes();

            //string dataFile = 
        }
        private string SendPostRequest(
            string url,
            string content,
            string contentType,
            out HttpWebResponse response,
            bool isLogging = true)
        {
            string logMessage = string.Empty;
            string responseFromServer = null;
            response = null;

            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            using (request as IDisposable)
            {
                request.Timeout = HTTP_WEB_REQUEST_TIMEOUT;
                request.KeepAlive = false;
                request.Method = "POST";

                request.CookieContainer = this.AuthCookies;
                // Create POST data and convert it to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = contentType;
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                using (Stream dataStream = request.GetRequestStream())
                {
                    // Write the data to the request stream.
                    dataStream.Write(byteArray, 0, byteArray.Length);
                }

                // Get the response.
                try
                {
                    response = request.GetResponse() as HttpWebResponse;
                }
                catch (WebException e)
                {
                    if (isLogging)
                    {
                        Trace.TraceError(e.ToString());

                        using (response = e.Response as HttpWebResponse)
                        {
                            logMessage = response.Method + " " + request.Address + " " + (int)response.StatusCode;
                            DebugLog.WriteLine(logMessage);
                            Trace.TraceWarning(logMessage);

                            using (Stream data = response.GetResponseStream())
                            {
                                string text = new StreamReader(data).ReadToEnd();
                                logMessage = "\t" + text.Replace("\n", "");
                                DebugLog.WriteLine(logMessage);
                                Trace.TraceWarning(logMessage);
                            }
                        }
                        throw;
                    }
                    else
                    {
                        using (response = e.Response as HttpWebResponse)
                            Trace.TraceError("Exception occured (" + (int)response.StatusCode + ") but logging is disabled");
                        throw;
                    }
                }

                if (isLogging)
                {
                    logMessage = response.Method + " " + request.Address + " " + (int)response.StatusCode;
                    DebugLog.WriteLine(logMessage);
                    Trace.TraceInformation(logMessage);
                }

                try
                {
                    // Display the status.
                    //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                    // Get the stream containing content returned by the server.
                    using (Stream dataStream = response.GetResponseStream())
                    {
                        // Open the stream using a StreamReader for easy access.
                        using (StreamReader reader = new StreamReader(dataStream))
                        {
                            // Read the content.
                            responseFromServer = reader.ReadToEnd();
                            // Display the content.
                            //Console.WriteLine(responseFromServer);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (isLogging)
                    {
                        Trace.TraceError(ex.ToString());
                    }
                    else
                    {
                        Trace.TraceError("Exception occured but logging is disabled");
                    }

                    (response as IDisposable).Dispose();
                    response = null;
                    throw;
                }
            }
            return responseFromServer;
        }
Beispiel #26
-1
        /// <summary>
        /// The save population.
        /// </summary>
        /// <param name="population">
        /// The population. 
        /// </param>
        /// <param name="generation">
        /// The generation. 
        /// </param>
        /// <param name="properties">
        /// The properties. 
        /// </param>
        /// <param name="filename">
        /// The filename. 
        /// </param>
        public static void SavePopulation(
            List<Critter> population, int generation, EvolutionaryProperties properties, string filename)
        {
            // Console.ForegroundColor = ConsoleColor.Green;

            // List<KeyValuePair<List<int>, TimeSpan>> kvps = population.ToList();
            // kvps.Sort((x, y) => x.Value.CompareTo(y.Value));
            // File.Delete("Results.txt");
            string template = new StreamReader("Template.htm").ReadToEnd();
            foreach (Critter kvp in population)
            {
                // Console.WriteLine("{0} : {1}", kvp.UnifiedFitnessScore, kvp.Key.Count);
                string file = filename;

                string markerCode = string.Empty;
                foreach (NodeWrapper<INetworkNode> t in kvp.Route)
                {
                    int key = Convert.ToInt32(t.Node.Id);
                    TimeSpan time = t.TotalTime;

                    string latlng = string.Format(
                        "new google.maps.LatLng({0},{1})",
                        properties.NetworkDataProviders[0].GetNodeFromId(key).Latitude,
                        properties.NetworkDataProviders[0].GetNodeFromId(key).Longitude);
                    markerCode +=
                        string.Format(
                            "var marker = new google.maps.Marker({{position: {0}, map: map,title:\"{1}: {2} ({3})\"}});\n",
                            latlng,
                            key,
                            time.ToString(),
                            ((PtvNode)properties.NetworkDataProviders[0].GetNodeFromId(key)).StopSpecName);
                }

                using (var sw = new StreamWriter(file, false))
                {
                    sw.Write(template.Replace(@"//##//", markerCode));
                }

                /*
                using (StreamWriter sw = new StreamWriter("Results.txt", true))
                {
                    sw.WriteLine(String.Format("{0} : {1} \n", kvp.Value.ToString(CultureInfo.InvariantCulture), string.Join(",", kvp.Key)));

                    try
                    {
                        sw.WriteLine(
                            String.Format(
                                "{0} : {1} \n\n",
                                kvp.Value.ToString(CultureInfo.InvariantCulture),
                                string.Join(",", kvp.Key.Select(id => properties.DataStructures.List[id][0].StopSpecName).ToList())));
                    }
                    catch
                    {
                        string why = "why?";

                    }
                }
                 */
            }

            Console.ForegroundColor = ConsoleColor.Gray;
        }
Beispiel #27
-1
        protected void lbComplete_Click(object sender, EventArgs e)
        {
            string mailBody = string.Empty;
            string mailSubject = string.Empty;
            string id = _orderId;
            int toStatus = (int)OrderStatus.Completed;
            mailSubject = "您的订单已经完成,请上线查看相关图片";
            QJVRMS.Business.Orders obj = new QJVRMS.Business.Orders();
            if (obj.UpdateStatus(id, toStatus))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>doAccept();</script>");
               
                //发送邮件
                mailBody = "订单";
                try
                {
                    DataSet ds = obj.GetOrdersById(id);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataRow dr = ds.Tables[0].Rows[0];

                        string _title = dr["title"].ToString();
                        string _rd = dr["RequestDate"].ToString();
                        string _size = dr["RequestSize"].ToString();
                        string _usage = dr["usage"].ToString();
                        string _content = dr["contents"].ToString();
                        string _addDate = dr["AddDate"].ToString();
                        string _userName = dr["userName"].ToString();


                        MemberShipManager objUserOP = new MemberShipManager();
                        User objUser = objUserOP.GetUser(dr["userName"].ToString());
                        string _userRealName = objUser.UserName;
                        string _userEmail = objUser.Email;

                        string templatePath = Server.MapPath("orderMailTemplate.htm");
                        mailBody = new StreamReader(templatePath).ReadToEnd();
                        mailBody = mailBody.Replace("{txtAddDate}", _addDate);
                        mailBody = mailBody.Replace("{txtUserName}", _userName);
                        mailBody = mailBody.Replace("{txtUserRealName}", _userRealName);
                        mailBody = mailBody.Replace("{txtContents}", _content.Replace("\r\n", "<br>"));
                        mailBody = mailBody.Replace("{txtUsage}", _usage);
                        mailBody = mailBody.Replace("{txtRD}", _rd);
                        mailBody = mailBody.Replace("{txtTitle}", _title);

                        string link = "<a href='http://{0}/{1}/Modules/UserProfile.aspx?tabid=2&orderStatus=" + toStatus.ToString() + "' target='_blank'>去我的订单中查看详细信息</a>";
                        mailBody = mailBody.Replace("{link}", string.Format(link, Request.Url.Authority, Request.ApplicationPath));


                        Session["MailBody"] = mailBody;
                        //obj.sendNewOrderToUser(_userEmail, mailSubject, mailBody);
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language='javascript'>sendMail('" + _userEmail + "', '" + mailSubject + "')</script>");

                    }

                }
                catch (Exception ex)
                {
                    LogWriter.WriteExceptionLog(ex);
                }


            }

        }
Beispiel #28
-1
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     var incomingData = new StreamReader(filterContext.HttpContext.Request.InputStream).ReadToEnd();
     filterContext.ActionParameters["jsoncommand"] = incomingData.Replace("jsoncommand=", "");
     base.OnActionExecuting(filterContext);
 }
Beispiel #29
-1
 /// <summary>
 /// Converts the Response Stream to String.
 /// </summary>
 /// <param name="response">Http Response.</param>
 /// <returns>Response Text.</returns>
 private static string ConvertResponseToString(HttpWebResponse response)
 {
     string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
     return result.Replace("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">", "").Replace("</string>", "");
 }
Beispiel #30
-1
        private static string GetResourceString(string name, bool escapeBraces = false)
        {
            // '{' and '}' are special in CSS, so we use "[[[0]]]" instead for {0} (and so on).
            var assembly = typeof(StartupExceptionPage).GetTypeInfo().Assembly;
            var resourceName = assembly.GetName().Name + ".compiler.resources." + name;
            var manifestStream = assembly.GetManifestResourceStream(resourceName);
            var formatString = new StreamReader(manifestStream, Encoding.UTF8, detectEncodingFromByteOrderMarks: false).ReadToEnd();
            if (escapeBraces)
            {
                formatString = formatString.Replace("{", "{{").Replace("}", "}}").Replace("[[[", "{").Replace("]]]", "}");
            }

            return formatString;
        }
Beispiel #31
-1
        public String SetStateActuatorPreset(String XS1_URL, String Username, String Password, Int32 ActuatorID, Int32 PresetID)
        {
            // TODO: more error handling !!!

            WebRequest wrGetURL = WebRequest.Create("http://" + XS1_URL + "/control?user="******"&pwd=" + Password + "&callback=setstate&cmd=set_state_actuator&number="+ActuatorID+"&function="+PresetID);

            String _UsernameAndPassword = Username + ":" + Password;
            String _AuthorizationHeader = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(_UsernameAndPassword));

            wrGetURL.Credentials = new NetworkCredential(Username, Password);
            wrGetURL.Headers.Add("Authorization", _AuthorizationHeader);
            HttpWebResponse response = (HttpWebResponse)wrGetURL.GetResponse();
            // check for eventual errors
            if (response.StatusCode != HttpStatusCode.OK)
            {
                // TODO: refactor to correct http response codes
                return null;
            }
            // we will read data via the response stream
            String actuator_config_json = new StreamReader(response.GetResponseStream()).ReadToEnd();

            JavaScriptSerializer ser = new JavaScriptSerializer();
            ser.MaxJsonLength = 20000000;

            // remove the javascript callback/definitions
            actuator_config_json = actuator_config_json.Replace("setstate(", "");
            actuator_config_json = actuator_config_json.Remove(actuator_config_json.Length - 4, 4);


            return "";
        }