Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
示例#1
1
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            string input = sr.ReadToEnd();
            sr.Dispose();

            JavaScriptSerializer ser = new JavaScriptSerializer();
            dynamic json = ser.DeserializeObject(input);
            for (int i = 1; i < json.Length; i++)
            {
                dynamic block = json[i];
                string blockType = block[0];
                Dictionary<string, object> blockAttr = block[1];

                for (int j = 2; j < block.Length; j++)
                {
                    dynamic span = block[j];
                    string spanType = span[0];
                    string text = span[1];
                    Console.Write(text);
                }

                Console.WriteLine();
                Console.WriteLine();
            }
        }
示例#2
1
 private static void DisposeObject(ref HttpWebRequest request, ref HttpWebResponse response,
     ref Stream responseStream, ref StreamReader reader)
 {
     if (request != null)
     {
         request = null;
     }
     if (response != null)
     {
         response.Close();
         response = null;
     }
     if (responseStream != null)
     {
         responseStream.Close();
         responseStream.Dispose();
         responseStream = null;
     }
     if (reader != null)
     {
         reader.Close();
         reader.Dispose();
         reader = null;
     }
 }
示例#3
1
 /// 获取token,如果存在且没过期,则直接取token
 /// <summary>
 /// 获取token,如果存在且没过期,则直接取token
 /// </summary>
 /// <returns></returns>
 public static string GetExistAccessToken()
 {
     // 读取XML文件中的数据
     string filepath = System.Web.HttpContext.Current.Server.MapPath("/XMLToken.xml");
     FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     StreamReader str = new StreamReader(fs, System.Text.Encoding.UTF8);
     XmlDocument xml = new XmlDocument();
     xml.Load(str);
     str.Close();
     str.Dispose();
     fs.Close();
     fs.Dispose();
     string Token = xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText;
     DateTime AccessTokenExpires = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText);
     //如果token过期,则重新获取token
     if (DateTime.Now >= AccessTokenExpires)
     {
         AccessToken mode = Getaccess();
         //将token存到xml文件中,全局缓存
         xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText = mode.access_token;
         DateTime _AccessTokenExpires = DateTime.Now.AddSeconds(mode.expires_in);
         xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText = _AccessTokenExpires.ToString();
         xml.Save(filepath);
         Token = mode.access_token;
     }
     return Token;
 }
示例#4
0
        private static void Main(string[] args)
        {
            StreamReader reader = new StreamReader("../../wordFile.txt");
             StreamReader readerSearchFile = new StreamReader("../../textFile.txt");
             StreamWriter writer = new StreamWriter("../../resultFile.txt");
            try
            {

                SortedDictionary<String, int> words = new SortedDictionary<string, int>();
                string word = reader.ReadLine();
                string textFile = readerSearchFile.ReadToEnd().ToLower();
                while (word != null)
                {
                    word = word.ToLower();

                    string pattern = @"\b" + word + @"\b";
                    MatchCollection matches = Regex.Matches(textFile, pattern);
                    words.Add(word, matches.Count);
                    word = reader.ReadLine();

                }
                var ordered = words.OrderByDescending(pair => pair.Value);
                foreach (KeyValuePair<string, int> pair in ordered)
                {
                    writer.WriteLine("{0} - {1}", pair.Key, pair.Value);
                }
            }
            finally
            {
                writer.Flush();
                reader.Dispose();
                readerSearchFile.Dispose();
                writer.Dispose();
            }
        }
示例#5
0
 public Site Get()
 {
     Site site = null;
     if (!File.Exists(file))
     {
         site = new Site
                        {
                            Title = "New Site",
                            Email = "*****@*****.**"
                        };
         Save(site);
         return site;
     }
     site  = null;
     StreamReader sr = null;
     try
     {
         sr = new StreamReader(file);
         var str = sr.ReadToEnd();
         var serializer = new JavaScriptSerializer();
         site = serializer.Deserialize<Site>(str);
     }
     finally
     {
         sr.Close();
         sr.Dispose();
         sr = null;
     }
     return site;
 }
 /// <summary>
 /// Serializes current XmlInterchange object into an XML string
 /// </summary>
 /// <returns>string XML value</returns>
 public virtual string Serialize(System.Text.Encoding encoding)
 {
     StreamReader streamReader = null;
     MemoryStream memoryStream = null;
     try
     {
         memoryStream = new MemoryStream();
         System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
         xmlWriterSettings.Encoding = encoding;
         xmlWriterSettings.Indent = true;
         System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
         Serializer.Serialize(xmlWriter, this);
         memoryStream.Seek(0, SeekOrigin.Begin);
         streamReader = new StreamReader(memoryStream, encoding);
         return streamReader.ReadToEnd();
     }
     finally
     {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
示例#7
0
 public static string Read(string path)
 {
     FileStream fs = null;
     StreamReader sr = null;
     try
     {
         fs = File.OpenRead(path);
         sr = new StreamReader(fs);
         string content = sr.ReadToEnd();
         content = ClearValue(content);
         return content;
     }
     catch (Exception)
     {
         throw;
     }
     finally
     {
         if (sr != null)
         {
             sr.Dispose();
         }
         if (fs != null)
         {
             fs.Dispose();
         }
     }
 }
 public static string ReadFileAsString(string filePath)
 {
     if (File.Exists(filePath))
     {
         string result = string.Empty;
         StreamReader sr = null;
         try
         {
             sr = new StreamReader(filePath, Encoding.UTF8);
             result = sr.ReadToEnd();
         }
         catch
         {
             result = string.Empty;
         }
         finally
         {
             sr.Close();
             sr.Dispose();
         }
         return result;
     }
     else
         return string.Empty;
 }
示例#9
0
文件: Utils.cs 项目: pirzada/sinapse
        public static CsvDelimiter DetectFieldDelimiterChar(string filename, System.Text.Encoding encoding)
        {
            TextReader textReader = null;
            CsvDelimiter delimiter;

            try
            {
                textReader = new StreamReader(filename, encoding);
                delimiter = DetectFieldDelimiterChar(textReader.ReadLine());

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception occured in field delimiter detection routine: " + e.Message);
                delimiter = CsvDelimiter.Comma;
                throw;
            }
            finally
            {
                if (textReader != null)
                {
                    textReader.Close();
                    textReader.Dispose();
                }
            }

            return delimiter;
        }
示例#10
0
        /// <summary>Load engine resourses (models, interface, etc)</summary>
        void EngineInit()
        {
            // READ SETUP FILE
            StreamReader setupFile = null;
            try
            {
                setupFile = new StreamReader(Settings.dir + "\\setup");
            }
            catch
            {
                Settings.TerminateWindow(Settings.dir + "\nNie można odczytać pliku konfiguracyjnego 'setup'");
            }
            string line;
            while( (line = setupFile.ReadLine()) != null )
            {
                string[] args = line.Split(' ');
                switch( args[0] )
                {
                    case "self":	// user position
                        positionCamera.X = float.Parse(args[1], CultureInfo.InvariantCulture);
                        positionCamera.Y = float.Parse(args[2], CultureInfo.InvariantCulture);
                        positionCamera.Z = float.Parse(args[3], CultureInfo.InvariantCulture);
                        break;
                }
            }

            // clean
            setupFile.Dispose();
        }
示例#11
0
 static void Main(string[] args)
 {
     TextReader rdr = null;
     try {
         rdr = new StreamReader("Hello_Debug_Trace.txt");
         string s = rdr.ReadToEnd();
         Console.WriteLine(s);
     }
     catch (Exception ex)
     {
         Console.WriteLine("StreamReader: "+ex.Message);
     }
     finally
     {
         if (rdr != null)
         {
             rdr.Dispose();
         }
     }
     TextReader rdr1 = null;
     try {
         using (rdr1 = new StreamReader("Hello_Debug_Trace.txt"))
         {
             string s = rdr1.ReadToEnd();
             Console.WriteLine(s);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("StreamReader: " + ex.Message);
     }
 }
        private IDictionary<string, string> GetFileProperties()
        {
            if (!File.Exists(PROPERTIES_FILE))
                throw new Exception(String.Format("Configuration file {0} not found.", PROPERTIES_FILE));

            IDictionary<string, string> properties = new Dictionary<string, string>();
            List<String> lines = new List<string>();
            using (StreamReader reader = new StreamReader(PROPERTIES_FILE, Encoding.GetEncoding("ISO-8859-1")))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    lines.Add(line);
                }

                if (lines.Count > 0)
                {
                    String[] keyValues = lines.ToArray();
                    properties = keyValues.ToDictionary(
                        s => (!String.IsNullOrEmpty(s) && s.Split('=').Length > 0) ? s.Split('=')[0].Trim() : String.Empty,
                        s => (!String.IsNullOrEmpty(s) && s.Split('=').Length > 1) ? s.Split('=')[1].Trim() : String.Empty);
                }

                reader.Close();
                reader.Dispose();
            }

            return properties;
        }
示例#13
0
        static public JadeData.Workspace.IWorkspace Read(string path)
        {
            WorkspaceType xml;
            XmlSerializer serializer = new XmlSerializer(typeof(WorkspaceType));
            TextReader tr = new StreamReader(path);
            try
            {                
                xml = (WorkspaceType)serializer.Deserialize(tr);                
            }
            finally
            {
                tr.Close();
                tr.Dispose();
            }

            JadeData.Workspace.IWorkspace result = new JadeData.Workspace.Workspace(xml.Name, path);

            foreach (FolderType f in xml.Folders)
            {
                result.AddFolder(MakeFolder(result.Directory, f));
            }
            foreach (ProjectType p in xml.Projects)
            {
                result.AddProject(MakeProject(result.Directory, p));
            }

            return result;
        }
示例#14
0
 public void CreateHtml(string temPath, Maticsoft.Model.CMS.Content model, string createPath)
 {
     string str = string.Empty;
     string str2 = string.Empty;
     try
     {
         str2 = HttpContext.Current.Server.MapPath(createPath);
         StreamReader reader = new StreamReader(System.IO.File.Open(HttpContext.Current.Server.MapPath(temPath), FileMode.Open, FileAccess.Read), Encoding.GetEncoding("utf-8"));
         StringBuilder builder = new StringBuilder(reader.ReadToEnd());
         reader.Close();
         reader.Dispose();
         string str4 = builder.ToString().Replace("$id$", model.ContentID.ToString()).Replace("$content$", model.Description);
         this.CreatFolder(createPath);
         str = "ContentDetail-" + model.ContentID + ".html";
         StreamWriter writer = new StreamWriter(System.IO.File.Create(str2 + "/" + str), Encoding.GetEncoding("utf-8"));
         writer.Write(str4);
         writer.Flush();
         writer.Close();
         writer.Dispose();
     }
     catch (Exception)
     {
         throw;
     }
 }
        public void Post(UserSocialConnection ConnectionData, string Update)
        {
            try
            {
                string apiCallUrl = String.Format("https://graph.facebook.com/me/feed"); // Format the call string
                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(apiCallUrl);
                wr.Method = "POST";
                wr.ContentType = "application/x-www-form-urlencoded";

                string data = "access_token=" + ConnectionData.Token + "&message=" + HttpUtility.UrlEncode(Update);
                wr.ContentLength = data.Length;
                StreamWriter sw = new StreamWriter(wr.GetRequestStream());
                sw.Write(data);
                sw.Close();

                StreamReader sr = new StreamReader(wr.GetResponse().GetResponseStream());
                string jsonResponse = sr.ReadToEnd();

                sr.Close();

                sw.Dispose();
                sr.Dispose();

                if (jsonResponse.Contains("\"error_code\"")) // Proces the response for errors - a simple throw is used to convert the text error in to an exception
                    throw new Exception(String.Format("Error calling facebook API!\nJSON: {0} \nAPI CALL: {1}", jsonResponse, apiCallUrl));
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception occurred in FacebookSocialConnector.Post processing User ID #" + ConnectionData.UserId + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
示例#16
0
        public static string Render(string templateName, Dictionary<string, string> values)
        {
            if (File.Exists(TemplateDirectory + templateName + ".html"))
            {
                var sR = new StreamReader(File.OpenRead(TemplateDirectory + templateName + ".html"));

                string fileContent = sR.ReadToEnd();

                foreach (var d in values)
                {
                    fileContent = fileContent.Replace("{"+d.Key+"}",d.Value);
                }

                sR.Close();
                sR.Dispose();

                return fileContent;
            }
            else
            {
                Logger.LogError("Can't find template " + templateName);
            }

            return "";
        }
示例#17
0
         public string GetBusinessObject(string SystemCode, string BusinessObjectName)
        {
            string text = string.Empty;
            try
            {
                if (SystemCode == null || SystemCode == "" || BusinessObjectName == null || BusinessObjectName == "")
                    return null;
                var Path = ConfigurationManager.AppSettings["BOPath"];
                var BusinessObjectFolder = GetBusinessObjectFolder(Path, SystemCode);

                if (BusinessObjectFolder == null || BusinessObjectFolder == "")
                    return null;
                Path = Path + "\\" + BusinessObjectFolder + "\\" + BusinessObjectName + ".xml";
                Tracer.Debug("GetBusinessObject,filePath" + Path);
                if (!File.Exists(Path))
                    return null;
                StreamReader file = new StreamReader(Path);
                text = file.ReadToEnd();
                file.Close();
                file.Dispose();
            }
            catch (Exception ex)
            {
                Tracer.Debug(ex.ToString());
            }
           return text;
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();

            if (!storage.FileExists("LeaveSettings.xml"))
            {
                this.PayPeriodBase.Text = PayPeriodUtilities.GetCurrentPayPeriod().AddDays(-1).ToShortDateString();
                this.AnnualBalance.Focus();
            }
            else
            {
                using (storage)
                {
                    XElement _xml;
                    IsolatedStorageFileStream location = new IsolatedStorageFileStream(@"LeaveSettings.xml", System.IO.FileMode.Open, storage);
                    System.IO.StreamReader file = new System.IO.StreamReader(location);
                    _xml = XElement.Parse(file.ReadToEnd());
                    if (_xml.Name.LocalName != null)
                    {
                        this.AnnualBalance.Text = _xml.Attribute("AnnualBalance").Value;
                        this.SickBalance.Text = _xml.Attribute("SickBalance").Value;
                        this.AnnualAccrue.Text = _xml.Attribute("AnnualAccrue").Value;
                        this.SickAccrue.Text = _xml.Attribute("SickAccrue").Value;
                        this.PayPeriodBase.Text = _xml.Attribute("PayPeriod").Value;
                    }
                    file.Dispose();
                    location.Dispose();
                }
            }
        }
示例#19
0
        public void OutOptionsTest()
        {
            MemoryStream memStream = new MemoryStream();
            StreamWriter writer = new StreamWriter(memStream);
            writer.AutoFlush = true;
            InstallerLog.AddWriter(writer, InstallerLog.DefaultLineFormat);

            String line = "test";
            InstallerLog.WriteLine(line);

            memStream.Position = 0;
            StreamReader reader = new StreamReader(memStream);
            Assert.AreEqual(line, reader.ReadLine(), "DefaultLineFormat should only write the line itself.");

            memStream.Position = 0;
            InstallerLog.RemoveWriter(writer, false);
            InstallerLog.AddWriter(writer, InstallerLog.TimeStampedLineFormat);
            InstallerLog.WriteLine(line);

            memStream.Position = 0;
            String expectedLine = String.Format(InstallerLog.TimeStampedLineFormat, line, DateTime.Now.ToString());
            Assert.AreEqual(expectedLine, reader.ReadLine(), "TimeStampLineFormat should include timestamp.");

            writer.Dispose();
            reader.Dispose();
        }
示例#20
0
        /// <summary>
        /// Http Post(utf-8编码)
        /// </summary>
        /// <param name="parms">请求参数</param>
        /// <returns>请求结果</returns>
        public static string HttpRequest(string parms)
        {
            string result = String.Empty;
            try
            {
                byte[] postData = Encoding.UTF8.GetBytes(parms);
                //old:http://124.42.83.34:8080/greatwallweb/main
                //new:http://124.42.83.34:9191/greatwallweb/main
                //official http://218.28.234.14:8080/greatwallweb/main
                //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://218.28.234.14:8080/greatwallweb/main");
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://124.42.83.34:8080/greatwallweb/main");
                webRequest.Timeout = 30000;
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = postData.Length;

                Stream requestStream = webRequest.GetRequestStream();
                requestStream.Write(postData, 0, postData.Length);
                requestStream.Close();
                requestStream.Dispose();
                StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
            }
            catch { }
            return result;
        }
        public HttpWebRequestUsage()
        {
            lock (_lock)
            {
                DataSet ds = new DataSet();

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://219.146.59.6:38000/MONITOR_WEB/servlet/QueryTerminalOnlineTime?starttime=" );
                request.Timeout = 50000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();
                StreamReader readStream = new StreamReader(resStream);

                XmlDocument d = new XmlDocument();
                d.Load(readStream);
                d.Save("a.xml");
                ds.ReadXml("a.xml");

                // Close the stream object.
                resStream.Close();

                resStream.Dispose();
                readStream.Close();
                readStream.Dispose();

                // Release the HttpWebResponse.
                response.Close();
            }
        }
示例#22
0
		public String CreateHTMLFromXMLFile (String SourceFileName, string identifier)
			{
			if (!File.Exists (SourceFileName))
				{
				WMB.Basics.ReportErrorToEventViewer ("XMLToHTML.CreateHTMLFromXMLFile","Beim Erzeugen des HTML Files fehlte der File \"" + SourceFileName +"\"");
				return String.Empty;
				}

			try
				{
				StreamReader reader = new StreamReader (SourceFileName, Encoding.UTF8);
				string str = reader.ReadToEnd ();
				reader.Close ();
				reader.Dispose ();

				CreateHTMLString (str, identifier);
				}
			catch (Exception Excp)
				{
				WMB.Basics.ReportErrorToEventViewer ("XMLToHTML.CreateHTMLFromXMLFile","Beim Erzeugen des HTML Files aus dem File \"" + SourceFileName +"\" trat folgender Fehler auf:\r\n"+ Excp.ToString());
				return String.Empty;
				}

			return CreatedHTMLResult;
			}
示例#23
0
        /// <summary>
        /// 获取城市的天气状况
        /// </summary>
        /// <returns></returns>
        public static string GetWeather(string city)
        {
            string wUrl = string.Format("http://m.weather.com.cn/data/{0}.html", city);
            //string wUrl = @"http://m.weather.com.cn/data/101050101.html";
            HttpWebRequest wNetr = (HttpWebRequest)HttpWebRequest.Create(wUrl);
            HttpWebResponse wNetp = (HttpWebResponse)wNetr.GetResponse();

            wNetr.ContentType = "text/html";
            wNetr.Method = "Get";

            Stream Streams = wNetp.GetResponseStream();
            StreamReader Reads = new StreamReader(Streams, Encoding.UTF8);

            String ReCode = Reads.ReadToEnd();
            //关闭暂时不适用的资源
            Reads.Dispose();
            Streams.Dispose();
            wNetp.Close();
            //分析返回代码
            String[] Splits = new String[] { "\"", ",", "\"" };
            String[] Temp = ReCode.Split(Splits, StringSplitOptions.RemoveEmptyEntries);
            string[] Temp1 = Temp[25].Split(new char[] { '~', '℃' });
            string[] Temp2 = Temp[28].Split(new char[] { '~', '℃' });
            string[] Temp3 = Temp[31].Split(new char[] { '~', '℃' });
            string[] Temp4 = Temp[34].Split(new char[] { '~', '℃' });
            string[] Temp5 = Temp[37].Split(new char[] { '~', '℃' });
            string[] Temp6 = Temp[40].Split(new char[] { '~', '℃' });
            ReCode = String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}", Temp1[0], Temp1[2], Temp2[0], Temp2[2], Temp3[0], Temp3[2], Temp4[0], Temp4[2], Temp5[0], Temp5[2], Temp6[0], Temp6[2]);

            return ReCode;
        }
示例#24
0
        public static string ReadLog(DateTime filename)
        {

            Encoding code = Encoding.GetEncoding("gb2312");
            var dir = System.AppDomain.CurrentDomain.BaseDirectory + "\\Log\\";
            if (Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string temp = dir + DateTime.Today.Date.ToString("yyyyMMdd") + ".txt"; //保存文件的路径
            string str = "";
            if (File.Exists(temp))
            {
                StreamReader sr = null;
                try
                {
                    sr = new StreamReader(temp, code);
                    str = sr.ReadToEnd(); // 读取文件
                }
                catch { }
                sr.Close();
                sr.Dispose();
            }
            else
            {
                str = "";
            }


            return str;
        }
示例#25
0
        /// <summary>
        /// 读取指定Url的Html源代码
        /// </summary>
        /// <param name="sUrl">指定Url</param>
        /// <param name="sEncoding">指定读取编码</param>
        /// <returns></returns>
        public static string GetUrlHtml(string sUrl, string encoding)
        {
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(sUrl);
            Req.Referer = UrlHelper._referer;
            Req.Method = "GET";
            Req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1;)";
            Req.AllowAutoRedirect = true;
            Req.MaximumAutomaticRedirections = 10;
            // 超时时间30000=30秒
            Req.Timeout = 10000;
            //  是否建立TCP持久连接
            Req.KeepAlive = false;

            HttpWebResponse response = (HttpWebResponse)Req.GetResponse();
            Stream stream = response.GetResponseStream();
            Encoding myEncoding = Encoding.GetEncoding(encoding);
            StreamReader streamReader = new StreamReader(stream, myEncoding);
            string html = streamReader.ReadToEnd();
            streamReader.Close();
            streamReader.Dispose();
            stream.Close();
            stream.Dispose();
            response.Close();

            return html;
        }
示例#26
0
        public static string Post(string uri, Dictionary<string, string> postParameters)
        {
            string postData = "";
            foreach (string key in postParameters.Keys)
            {
                postData += HttpUtility.UrlEncode(key) + "="
                      + HttpUtility.UrlEncode(postParameters[key]) + "&";
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = bytes.Length;

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

            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);

            string result = reader.ReadToEnd();
            stream.Dispose();
            reader.Dispose();
            return result;
        }
示例#27
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="pattern"></param>
 /// <returns></returns>
 public static MatchCollection GetMatches(string fileName, string pattern)
 {
     StreamReader reader = null;
     MatchCollection collection = null;
     try
     {
         reader = new StreamReader(fileName);
         string fileText;
         lock (new object())
         {
             using (reader)
             {
                 fileText = reader.ReadToEnd();
             }
         }
         collection = GetMatchesFromString(fileText, pattern);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.ToString());
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
             reader.Dispose();
         }
     }
     return collection;
 }
示例#28
0
        protected string Read_Txt(string filename)
        {

            Encoding code = Encoding.GetEncoding("gb2312");
            string temp = HttpContext.Current.Server.MapPath("Precious\\" + filename + ".txt");
            string str = "";
            if (File.Exists(temp))
            {
                StreamReader sr = null;
                try
                {
                    sr = new StreamReader(temp, code);
                    str = sr.ReadToEnd(); // 读取文件
                }
                catch { }
                sr.Close();
                sr.Dispose();
            }
            else
            {
                str = "";
            }


            return str;
        }
示例#29
0
        /// <summary>
        /// 设置调试
        /// </summary>
        /// <param name="isDebug"></param>
        internal static void SetDebug(bool isDebug)
        {
            string content = String.Empty;
            bool isChange = false;

            using (StreamReader fs = new StreamReader(String.Format("{0}Web.config", AppDomain.CurrentDomain.BaseDirectory)))
            {
                content = fs.ReadToEnd();
                fs.Dispose();
            }

            Regex reg = new Regex("<compilation([^(debug)])+debug=\"([^\"]+)\"", RegexOptions.IgnoreCase);
            if (reg.IsMatch(content))
            {
                Match m = reg.Match(content);
                if ((m.Groups[2].Value == "true" && !isDebug) || (m.Groups[2].Value == "false" && isDebug))
                {
                    content = reg.Replace(content, String.Format("<compilation$1debug=\"{0}\"", isDebug ? "true" : "false"));
                    isChange = true;
                }
            }

            if (isChange)
            {
                using (FileStream fs = new FileStream(String.Format("{0}Web.config", AppDomain.CurrentDomain.BaseDirectory),
                    FileMode.Truncate, FileAccess.Write,FileShare.ReadWrite))
                {
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Dispose();
                }
            }
        }
示例#30
0
    public void enviarCorreo(String correoDestino, String userToken, String mensaje)
    {
        try
        {
            var Emailtemplate = new System.IO.StreamReader(AppDomain.CurrentDomain.BaseDirectory.Insert(AppDomain.CurrentDomain.BaseDirectory.Length, ""));
            var strBody       = string.Format(Emailtemplate.ReadToEnd(), userToken);
            Emailtemplate.Close(); Emailtemplate.Dispose(); Emailtemplate = null;


            strBody = strBody.Replace("#TOKEN#", "Por favor recupere su cuenta ingresando al siguiente link: " + "su link de acceso es: " + "" + userToken);
            //Configuración del Mensaje
            MailMessage mail       = new MailMessage();
            SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");
            //Especificamos el correo desde el que se enviará el Email y el nombre de la persona que lo envía
            mail.From       = new MailAddress("*****@*****.**", "Vasbor");
            SmtpServer.Host = "smtp.gmail.com";
            //Aquí ponemos el asunto del correo
            mail.Subject = "Recuperación Contraseña";
            //Aquí ponemos el mensaje que incluirá el correo
            mail.Body = strBody;
            //Especificamos a quien enviaremos el Email, no es necesario que sea Gmail, puede ser cualquier otro proveedor
            mail.To.Add(correoDestino);
            //Si queremos enviar archivos adjuntos tenemos que especificar la ruta en donde se encuentran
            //mail.Attachments.Add(new Attachment(@"C:\Documentos\carta.docx"));
            mail.IsBodyHtml = true;

            mail.Priority = MailPriority.Normal;
            //Configuracion del SMTP
            SmtpServer.Port = 587; //Puerto que utiliza Gmail para sus servicios
            //Especificamos las credenciales con las que enviaremos el mail
            SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "isaurasegura");
            SmtpServer.EnableSsl   = true;
            SmtpServer.Send(mail);
        }
        catch (Exception ex)
        {
        }
    }
 public static COCD_TP146033UK04Author LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
 public static PRPA_MT000001UK03AppointmentStatus LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#33
0
 public static CV_SuspectedCongenitalAbnormalityType LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#34
0
 public static POCD_MT170001UK06ClinicalDocumentEffectiveTime LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#35
0
 public static PORX_MT121302UK05DispenseReturnRejectionReason LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
 public static RCMR_MT030101UK06EhrComposition LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
 public static PORX_MT132004UK32TemporaryExemptionInfo LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
 public static UKCT_MT130201UK02PertinentInformation10 LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#39
0
 public static UKCT_MT140301UK01MedicationAdministrationReviewDate LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#40
0
 public static QUPC_MT160004UK05PSISDocMetaDataAvailabilityTime LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#41
0
 public static QUPA_IN000016UK02MCCI_MT010101UK12MessageProcessingCode LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#42
0
 public static PORX_IN050102UK32ControlActEvent LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#43
0
 public static UKCT_MT144040UK01ReasonRiskToPatient LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
 public static POII_MT000002UK01Component4TemplateId LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
 public static PORX_MT024001UK31SuppliedManufacturedProduct LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#46
0
 public static COCD_TP147022UK03AllergicOrAdverseReactionEventRefTemplateId LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#47
0
 public static ADNPfITCodedCountryStreetNameType LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
 public static PORX_MT142005UK06ReimbursmentClaim LoadFromFile(string fileName)
 {
     System.IO.FileStream   file = null;
     System.IO.StreamReader sr   = null;
     try {
         file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
         sr   = new System.IO.StreamReader(file);
         string xmlString = sr.ReadToEnd();
         sr.Close();
         file.Close();
         return(Deserialize(xmlString));
     }
     finally {
         if ((file != null))
         {
             file.Dispose();
         }
         if ((sr != null))
         {
             sr.Dispose();
         }
     }
 }
示例#49
0
    public static string Save(string user, string data)
    {
        string sendData = "user="******"&" + "data=" + data;           //发送的数据
        string url      = "http://192.168.199.185:8080/save/?" + sendData; //请求路径
                                                                           //string url = "http://192.168.199.107:8080/save/?" + sendData;//请求路径
        string backMsg = "";                                               //接收服务端返回数据

        try
        {
            System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
            httpRquest.Method = "GET";

            /*byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
             * System.IO.Stream requestStream = null;
             * if (string.IsNullOrWhiteSpace(sendData) == false)
             * {
             *  requestStream = httpRquest.GetRequestStream();
             *  requestStream.Write(dataArray, 0, dataArray.Length);
             *  requestStream.Close();
             * }*/
            System.Net.WebResponse response       = httpRquest.GetResponse();
            System.IO.Stream       responseStream = response.GetResponseStream();
            System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
            backMsg = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();
            //requestStream.Dispose();
            responseStream.Close();
            responseStream.Dispose();
        }
        catch (System.Exception e1)
        {
            //Console.WriteLine(e1.ToString());
            Debug.Log(e1.ToString());
        }
        return(backMsg);
    }
示例#50
0
    public string SendSMS(string PostData)
    {
        string Result = string.Empty;

        #region 发送 接收
        try
        {
            byte[] SendBytes = Encoding.UTF8.GetBytes(PostData);
            System.Net.HttpWebRequest request = System.Net.HttpWebRequest.Create("http://115.29.206.137:8081/myservice.asmx/SendSMS") as System.Net.HttpWebRequest;
            request.Method        = "POST";
            request.ContentType   = "application/x-www-form-urlencoded";
            request.ContentLength = SendBytes.Length;

            using (System.IO.Stream newStream = request.GetRequestStream())
            {
                newStream.Write(SendBytes, 0, SendBytes.Length);
                newStream.Close();
            }

            using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse())
            {
                using (System.IO.StreamReader readStream = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    Result = readStream.ReadToEnd();
                    readStream.Close();
                    readStream.Dispose();
                }
                response.Close();
            }
        }
        catch
        { }
        #endregion

        return(Result);
    }
示例#51
0
 /// <summary>
 /// Serializes current test object into an XML document
 /// </summary>
 /// <returns>string XML value</returns>
 public virtual string Serialize(System.Text.Encoding encoding)
 {
     System.IO.StreamReader streamReader = null;
     System.IO.MemoryStream memoryStream = null;
     try {
         memoryStream = new System.IO.MemoryStream();
         System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
         xmlWriterSettings.Encoding = encoding;
         System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
         Serializer.Serialize(xmlWriter, this);
         memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
         streamReader = new System.IO.StreamReader(memoryStream);
         return(streamReader.ReadToEnd());
     } finally {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
示例#52
0
        /// 发送请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sendData">参数格式 “name=王武&pass=123456”</param>
        /// <returns></returns>
        public static string RequestWebAPI(string url, string sendData)
        {
            string backMsg = "";

            try
            {
                System.Net.WebRequest httpRquest = System.Net.HttpWebRequest.Create(url);
                httpRquest.Method = "POST";
                //这行代码很关键,不设置ContentType将导致后台参数获取不到值
                httpRquest.ContentType = "application/json;charset=UTF-8";
                byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
                //httpRquest.ContentLength = dataArray.Length;
                System.IO.Stream requestStream = null;
                if (string.IsNullOrWhiteSpace(sendData) == false)
                {
                    requestStream = httpRquest.GetRequestStream();
                    requestStream.Write(dataArray, 0, dataArray.Length);
                    requestStream.Close();
                }
                System.Net.WebResponse response       = httpRquest.GetResponse();
                System.IO.Stream       responseStream = response.GetResponseStream();
                System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                backMsg = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();

                requestStream.Dispose();
                responseStream.Close();
                responseStream.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            return(backMsg);
        }
示例#53
0
        /// <summary>
        /// Platform-Specific implementations
        /// <para>Android: returns the shader as a string from assets.</para>
        /// <para>iOS: returns the shader as a string from the app bundle.</para>
        /// </summary>
        private string GetResourceAsString(string name, string extension)
        {
            string resource = String.Empty;
            string contents = String.Empty;

                        #if __ANDROID__
            resource = name + "." + extension;
            string shaderPath = Path.Combine("Shaders", resource);

            var context = AndroidContext;
            System.IO.StreamReader sr = new System.IO.StreamReader(context.Assets.Open(shaderPath));
            contents = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
                        #endif

                        #if __IOS__
            string shaderPath = System.IO.Path.Combine("Shaders", name);
            resource = NSBundle.MainBundle.PathForResource(shaderPath, extension);
            contents = System.IO.File.ReadAllText(resource);
                        #endif

            return(contents);
        }
示例#54
0
 /// <summary>
 /// Serializes current dijAdat object into an XML document
 /// </summary>
 /// <returns>string XML value</returns>
 public virtual string Serialize()
 {
     System.IO.StreamReader streamReader = null;
     System.IO.MemoryStream memoryStream = null;
     try
     {
         memoryStream = new System.IO.MemoryStream();
         Serializer.Serialize(memoryStream, this);
         memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
         streamReader = new System.IO.StreamReader(memoryStream);
         return(streamReader.ReadToEnd());
     }
     finally
     {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
示例#55
0
    protected Boolean Send_Email_Internal()
    {
        var emailSent = true;

        // Standard
        var to1Name      = System.Configuration.ConfigurationManager.AppSettings["t13Name"];
        var to1Email     = System.Configuration.ConfigurationManager.AppSettings["to1Email"];
        var emailAddress = new MailAddress(to1Email, to1Name);

        var    emailUser      = System.Configuration.ConfigurationManager.AppSettings["mail1User"];
        var    emailName      = System.Configuration.ConfigurationManager.AppSettings["mail1Name"];
        var    emailPass      = System.Configuration.ConfigurationManager.AppSettings["mail1Pass"];
        var    senderEmail    = new MailAddress(emailUser, emailName);
        string senderPassword = emailPass;

        const string emailSubject = "Cash Incentive Program - Email Sent";

        var emailFile = "Application_Email_Internal.html";
        var emailPath = "Emails/";

        System.IO.StreamReader rdr = new System.IO.StreamReader(Server.MapPath(emailPath + emailFile));
        var htmlBody = rdr.ReadToEnd();

        rdr.Close();
        rdr.Dispose();

        // Convert the html Body to be dynamic with the Business Name > Client Name, etc
        // Also add a disclosure to the body

        #region Business Details
        htmlBody = htmlBody.Replace("{businessname}", tbBusinessName.Text);
        htmlBody = htmlBody.Replace("{businessphone}", tbBusinessPhone.Text);
        htmlBody = htmlBody.Replace("{businessemail}", tbBusinessEmail.Text);
        htmlBody = htmlBody.Replace("{firstname}", tbFirstName.Text);
        htmlBody = htmlBody.Replace("{middlename}", tbMiddleName.Text);
        htmlBody = htmlBody.Replace("{lastname}", tbLastName.Text);
        #endregion
        #region Agent Details
        htmlBody = htmlBody.Replace("{callcenter}", ddlCallCenter.SelectedValue);
        htmlBody = htmlBody.Replace("{agentfirstname}", tbAgentFirstName.Text);
        htmlBody = htmlBody.Replace("{agentlastname}", tbAgentLastName.Text);
        htmlBody = htmlBody.Replace("{agentid}", ddlAgentID.SelectedValue);
        htmlBody = htmlBody.Replace("{calltime}", hfCallTime.Value);
        htmlBody = htmlBody.Replace("{ani}", hfANI.Value);
        htmlBody = htmlBody.Replace("{dnis}", hfDNIS.Value);

        #endregion

        htmlBody = htmlBody.Replace("{timestamp}", DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"));
        htmlBody = htmlBody.Replace("{year}", DateTime.UtcNow.Year.ToString());

        var smtp = new SmtpClient
        {
            Host                  = "smtp.gmail.com",
            Port                  = 587,
            EnableSsl             = true,
            DeliveryMethod        = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials           = new NetworkCredential(senderEmail.Address, senderPassword)
        };

        var message = new MailMessage(senderEmail, emailAddress);
        message.Subject    = emailSubject;
        message.IsBodyHtml = true;
        message.Body       = htmlBody;

        if (Request.Url.Host == "devapp.cardgroupintl.com")
        {
            // DeBug Client
            var to2Name       = System.Configuration.ConfigurationManager.AppSettings["to2Name"];
            var to2Email      = System.Configuration.ConfigurationManager.AppSettings["to2Email"];
            var emailAddress2 = new MailAddress(to2Email, to2Name);
            // DeBug Admin
            var to3Name       = System.Configuration.ConfigurationManager.AppSettings["to3Name"];
            var to3Email      = System.Configuration.ConfigurationManager.AppSettings["to3Email"];
            var emailAddress3 = new MailAddress(to3Email, to3Name);

            message.To.Add(emailAddress2);
            message.To.Add(emailAddress3);
        }

        try
        {
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            emailSent = false;
            lblProcessMessage.Text = "Error sending email";

            lblProcessMessage.Text += String.Format("<table class='table_error'>"
                                                    + "<tr><td>Error<td/><td>{0}</td></tr>"
                                                    + "<tr><td>Message<td/><td>{1}</td></tr>"
                                                    + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                                    + "<tr><td>Source<td/><td>{3}</td></tr>"
                                                    + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                                    + "<tr><td>Data<td/><td>{5}</td></tr>"
                                                    + "</table>"
                                                    , "Email Sender"    //0
                                                    , ex.Message        //1
                                                    , ex.StackTrace     //2
                                                    , ex.Source         //3
                                                    , ex.InnerException //4
                                                    , ex.Data           //5
                                                    , ex.HelpLink
                                                    , ex.TargetSite
                                                    );
        }

        return(emailSent);
    }
示例#56
0
        /// <summary>
        /// 获取身份证信息
        /// </summary>
        public static CardInfo ReadCardInfo(int nPort, out string sMsg, string sSavePath)
        {
            CardInfo objCardInfo = null;

            try
            {
                byte[] cmd   = { 0x43 };
                int    para0 = 0;
                int    para1 = 8811;
                int    para2 = 9986;
                int    nRet  = UCommand1(cmd, ref para0, ref para1, ref para2);

                Console.WriteLine(DateTime.Now.ToString() + " 验证 - nRet: " + nRet);

                if (nRet == 62171)//身份证验证成功
                {
                    byte[] bcmd = { 0x44 };
                    para0 = 0;
                    para1 = 8811;
                    para2 = 9986;
                    nRet  = UCommand1(bcmd, ref para0, ref para1, ref para2);// '读卡内信息

                    Console.WriteLine(DateTime.Now.ToString() + " 读卡 - nRet: " + nRet);

                    if ((nRet == 62171) || (nRet == 62172))
                    {
                        sMsg        = string.Empty;
                        objCardInfo = new CardInfo();
                        System.IO.StreamReader objStreamReader = new System.IO.StreamReader(sSavePath + "wx.txt", System.Text.Encoding.Default);

                        //读取已转化文本
                        objCardInfo.Name       = objStreamReader.ReadLine();
                        objCardInfo.Sex        = objStreamReader.ReadLine();
                        objCardInfo.Nation     = objStreamReader.ReadLine();
                        objCardInfo.Birthday   = objStreamReader.ReadLine();
                        objCardInfo.Address    = objStreamReader.ReadLine();
                        objCardInfo.CardNo     = objStreamReader.ReadLine();
                        objCardInfo.Department = objStreamReader.ReadLine();
                        objCardInfo.StartDate  = objStreamReader.ReadLine();
                        objCardInfo.EndDate    = objStreamReader.ReadLine();
                        objCardInfo.PhotoPath  = sSavePath + "zp.bmp";
                        string sPhotoPath = objCardInfo.PhotoPath;

                        //读取追加地址(读取unicode格式的文本)
                        byte[] ccmd = { 0x45 };//0x45 读追加地址,生成两个对应的文本文件。
                        nRet = UCommand1(ccmd, ref para0, ref para1, ref para2);
                        //判断是否存在最新地址
                        if (62171 == nRet)
                        {
                            if (File.Exists(sSavePath + "NewAddgb.txt"))
                            {
                                try
                                {
                                    System.IO.StreamReader newAdd = new System.IO.StreamReader(sSavePath + "NewAddgb.txt", System.Text.Encoding.Unicode);
                                    string newaddress             = newAdd.ReadToEnd();
                                    objCardInfo.AddressEx = newaddress;
                                    newAdd.Close();
                                    newAdd.Dispose();
                                }
                                catch
                                {
                                }
                            }
                        }
                        else
                        {
                            objCardInfo.AddressEx = " ";
                        }
                        objStreamReader.Close();
                        objStreamReader.Dispose();

                        return(objCardInfo);
                    }
                    else if (-5 == nRet)
                    {
                        sMsg = "返回值:" + nRet.ToString() + "软件未授权!";
                    }
                    else
                    {
                        sMsg = "返回值:" + nRet.ToString() + "读身份证不成功";
                    }
                }
                else
                {
                    sMsg = "请将身份证放置感应区,谢谢合作!";
                }

                return(objCardInfo);
            }
            catch (Exception ex)
            {
                sMsg = "读身份证失败,原因是:" + ex.Message;
                return(null);
            }
        }
示例#57
0
        /// <summary>
        /// 访问URL地址
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="postDataStr">参数</param>
        /// <param name="Encod">编码方式</param>
        /// <returns></returns>
        private static string CallWebPage(string url, string postDataStr, Encoding Encod)
        {
            string rStr = "";

            System.Net.WebRequest  req  = null;
            System.Net.WebResponse resp = null;
            System.IO.Stream       os   = null;
            System.IO.StreamReader sr   = null;
            try
            {
                //创建连接
                req = System.Net.WebRequest.Create(url);
                //设置访问方式和发送的请求数据的内容类型
                if (string.IsNullOrEmpty(postDataStr))
                {
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Method      = "GET";
                }
                else
                {
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Method      = "POST";
                    if (Encod == null)
                    {
                        Encod = Encoding.Default;
                    }
                    byte[] bytes = Encod.GetBytes(postDataStr);
                    req.ContentLength = bytes.Length;
                    os = req.GetRequestStream();
                    os.Write(bytes, 0, bytes.Length);
                    os.Close();
                }

                //读取返回结果
                resp = req.GetResponse();
                sr   = new System.IO.StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8);
                rStr = sr.ReadToEnd();
            }
            catch (Exception)
            {
                //LogUtil.Warn("HttpUtil.CallWebPage 异常:" + ex1.Message);
            }
            finally
            {
                try
                {
                    //关闭资源
                    if (os != null)
                    {
                        os.Dispose();
                        os.Close();
                    }
                    if (sr != null)
                    {
                        sr.Dispose();
                        sr.Close();
                    }

                    if (resp != null)
                    {
                        resp.Close();
                    }


                    if (req != null)
                    {
                        req = null;
                    }
                }
                catch (Exception)
                {
                    //LogUtil.Exception("HttpUtil.CallWebPage 关闭连接异常:" + ex2.Message);
                }
            }
            return(rStr);
        }
示例#58
0
    protected Boolean Send_Email_Client(String sp_token, String sp_email, String sp_firstname, String sp_lastname)
    {
        var emailSent    = true;
        var toName       = (sp_firstname + " " + sp_lastname).Trim();
        var emailAddress = new MailAddress(sp_email, toName);

        var emailUser = System.Configuration.ConfigurationManager.AppSettings["mail1User"];
        var emailName = System.Configuration.ConfigurationManager.AppSettings["mail1Name"];
        var emailPass = System.Configuration.ConfigurationManager.AppSettings["mail1Pass"];

        var    senderEmail    = new MailAddress(emailUser, emailName);
        string senderPassword = emailPass;

        string emailSubject = "Application - Password Recovery";
        var    emailFile    = "Password_Recovery_Email.html";
        var    emailPath    = @"~/App_Data/Emails/";

        System.IO.StreamReader rdr = new System.IO.StreamReader(Server.MapPath(emailPath + emailFile));
        var htmlBody = rdr.ReadToEnd();

        rdr.Close();
        rdr.Dispose();

        // Update html variables
        htmlBody = htmlBody.Replace("{username}", sp_email);
        htmlBody = htmlBody.Replace("{token}", sp_token);
        htmlBody = htmlBody.Replace("{host}", Request.Url.Host);

        var smtp = new SmtpClient
        {
            Host                  = "smtp.gmail.com",
            Port                  = 587,
            EnableSsl             = true,
            DeliveryMethod        = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials           = new NetworkCredential(senderEmail.Address, senderPassword)
        };

        var message = new MailMessage(senderEmail, emailAddress);

        message.Subject    = emailSubject;
        message.IsBodyHtml = true;
        message.Body       = htmlBody;

        try
        {
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            emailSent       = false;
            lblMessage.Text = "Error sending email";

            lblMessage.Text += String.Format("<table class='table_error'>"
                                             + "<tr><td>Error<td/><td>{0}</td></tr>"
                                             + "<tr><td>Message<td/><td>{1}</td></tr>"
                                             + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                             + "<tr><td>Source<td/><td>{3}</td></tr>"
                                             + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                             + "<tr><td>Data<td/><td>{5}</td></tr>"
                                             + "</table>"
                                             , "Email Sender"    //0
                                             , ex.Message        //1
                                             , ex.StackTrace     //2
                                             , ex.Source         //3
                                             , ex.InnerException //4
                                             , ex.Data           //5
                                             , ex.HelpLink
                                             , ex.TargetSite
                                             );
        }

        return(emailSent);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string tourName = "未知路线";
            if (Request.Params["tour"] != null)
            {
                tourName = Request.Params["tour"].ToString();
            }
            string exhibitions = "";
            if (Request.Params["exhibits"] != null)
            {
                exhibitions = Request.Params["exhibits"].ToString();
            }


            if (string.IsNullOrEmpty(exhibitions))
            {
                return;
            }

            string[] exhibits = exhibitions.Split(',');

            if (!string.IsNullOrEmpty(tourName))
            {
                RoamingClass  roamingClass = new RoamingClass();
                RoamingConfig config       = new RoamingConfig();
                for (int i = 0; i < exhibits.Length; i++)
                {
                    string filePath = configRoot + "/" + exhibits[i] + ".txt";
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
                    {
                        try
                        {
                            string content = reader.ReadToEnd();
                            //content = Encoding.GetEncoding( "GBK").GetString( Encoding.UTF8.GetBytes(content));

                            RoamingClass configObj = Newtonsoft.Json.JsonConvert.DeserializeObject <RoamingClass>(content);
                            //HttpContext.Current.Response.Write(configObj.roamingConfig.places.Count);
                            foreach (RoamingPlace p in configObj.roamingConfig.places)
                            {
                                if (p != null)
                                {
                                    //HttpContext.Current.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(p));
                                    config.places.Add(p);
                                }
                            }
                        }
                        catch (Exception eee)
                        {
                            HttpContext.Current.Response.Write(eee.ToString());
                        }
                        finally
                        {
                            reader.Dispose();
                            reader.Close();
                        }
                    }
                }

                roamingClass.roamingConfig = config;
                string responseStr = Newtonsoft.Json.JsonConvert.SerializeObject(roamingClass);

                HttpContext.Current.Response.Write(responseStr);
                HttpContext.Current.Response.End();
            }
        }
    }
        protected void SetUp()
        {
            var f = new FileStream("config.json", FileMode.Open);
            var sr = new StreamReader(f);
            try
            {
                var settings = JsonConvert
                    .DeserializeObject<MongoSettings>(sr.ReadToEnd());
                var client = new MongoClient(new MongoUrl(settings.Url));
                _database = client.GetDatabase(settings.DatabaseName);
            }
            catch (FileNotFoundException)
            {
                throw new Exception("Talk to John about why this one fails");
            }
            finally
            {
                f.Dispose();
                sr.Dispose();
            }

            _collectionName = Guid.NewGuid().ToString();
            _collection = _database.GetCollection<Container>(_collectionName);
            var mapper = new StringMapper<BasePaymentModel>(x => x.PaymentType)
                .Register<AchInputModel>("ach")
                .Register<CreditCardInputModel>("cc")
                .Register<PayPalInputModel>("paypal");
            BsonSerializer.RegisterDiscriminatorConvention(
                typeof(BasePaymentModel),
                new DiscriminatorConvention<string, BasePaymentModel>(mapper));
        }