Example #1
0
        public string Authorize(string channelName, string socketId)
        {
            Stream dataStream = null;
            StreamReader reader = null;
            WebResponse response = null;
            string result = null;
            try {

                var body = JsonConvert.SerializeObject(new RegisterRequest(channelName, socketId));
                var bodyData = Encoding.UTF8.GetBytes(body);

                var webRequest = _vpdbClient.GetWebRequest(Endpoint);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = bodyData.Length;
                dataStream = webRequest.GetRequestStream();
                dataStream.Write(bodyData, 0, bodyData.Length);
                dataStream.Close();
                response = webRequest.GetResponse();
                dataStream = response.GetResponseStream();
                reader = new StreamReader(dataStream);

                result = reader.ReadToEnd();

            } catch (Exception e) {
                _logger.Error(e, "Error retrieving pusher auth token.");
                _crashManager.Report(e, "pusher");

            } finally {
                reader?.Close();
                dataStream?.Close();
                response?.Close();
            }

            return result;
        }
Example #2
0
 /// <summary>
 ///     把响应流转换为文本。
 /// </summary>
 /// <param name="rsp">响应流对象</param>
 /// <param name="encoding">编码方式</param>
 /// <returns>响应文本</returns>
 private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
 {
     Stream stream = null;
     StreamReader reader = null;
     try
     {
         // 以字符流的方式读取HTTP响应
         stream = rsp.GetResponseStream();
         reader = new StreamReader(stream, encoding);
         return reader.ReadToEnd();
     }
     finally
     {
         // 释放资源
         reader?.Close();
         stream?.Close();
         rsp?.Close();
     }
 }
Example #3
0
        public static string GetSolutionVersion(string solutionFullFileName)
        {
            string version;
            StreamReader solutionStreamReader = null;

            try
            {
                solutionStreamReader = new StreamReader(solutionFullFileName);
                string firstLine;
                do
                {
                    firstLine = solutionStreamReader.ReadLine();
                } while (firstLine == "");

                var format = firstLine.Substring(firstLine.LastIndexOf(" ")).Trim();

                switch (format)
                {
                    case "7.00":
                        version = "VC70";
                        break;

                    case "8.00":
                        version = "VC71";
                        break;

                    case "9.00":
                        version = "VC80";
                        break;

                    case "10.00":
                        version = "VC90";
                        break;

                    case "11.00":
                        version = "VC100";
                        break;

                    case "12.00":
                        version = "VC140";
                        break;

                    default:
                        throw new ApplicationException("Unknown .sln version: " + format);
                }
            }
            finally
            {
                solutionStreamReader?.Close();
            }

            return version;
        }
Example #4
0
        private void ReadMetaData()
        {
            StreamReader headReader = null;

            try
            {
                headReader = new StreamReader(this._headerFilePath);
                String metaLineData = null;
                while ((metaLineData = headReader.ReadLine()) != null)
                {
                    if (metaLineData.Contains("samples"))
                    {
                        this.Samples = int.Parse(getDataAfterEqual(metaLineData));
                    }
                    else if (metaLineData.Contains("lines"))
                    {
                        this.Lines = int.Parse(getDataAfterEqual(metaLineData));
                    }
                    else if (metaLineData.Contains("bands"))
                    {
                        this.BandsCount = int.Parse(getDataAfterEqual(metaLineData));
                    }
                    else if (metaLineData.Contains("x start"))
                    {
                        this.XStart = int.Parse(getDataAfterEqual(metaLineData));
                    }
                    else if (metaLineData.Contains("y start"))
                    {
                        this.YStart = int.Parse(getDataAfterEqual(metaLineData));
                    }
                    else if (metaLineData.Contains("data type"))
                    {
                        this.DataType = int.Parse(getDataAfterEqual(metaLineData));
                    }
                    else if (metaLineData.Contains("interleave"))
                    {
                        this.Interleave = getDataAfterEqual(metaLineData);
                    }
                    else if (metaLineData.Contains("description"))
                    {
                        StringBuilder sb = new StringBuilder(getDataAfterEqual(metaLineData).Replace("{", ""));
                        String tmp;
                        while ((tmp = headReader.ReadLine()).Contains("}") == false)
                        {
                            sb.Append(tmp);
                        }
                        sb.Append(tmp.Trim().Replace("}", ""));
                        this.Description = sb.ToString();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                headReader?.Close();
            }
        }
Example #5
0
            private void UserStreamLoop()
            {
                var sleepSec = 0;
                do
                {
                    Stream st = null;
                    StreamReader sr = null;
                    try
                    {
                        if (!MyCommon.IsNetworkAvailable())
                        {
                            sleepSec = 30;
                            continue;
                        }

                        Started?.Invoke();

                        var res = twCon.UserStream(ref st, _allAtreplies, _trackwords, Networking.GetUserAgentString());

                        switch (res)
                        {
                            case HttpStatusCode.OK:
                                Twitter.AccountState = MyCommon.ACCOUNT_STATE.Valid;
                                break;
                            case HttpStatusCode.Unauthorized:
                                Twitter.AccountState = MyCommon.ACCOUNT_STATE.Invalid;
                                sleepSec = 120;
                                continue;
                        }

                        if (st == null)
                        {
                            sleepSec = 30;
                            //MyCommon.TraceOut("Stop:stream is null")
                            continue;
                        }

                        sr = new StreamReader(st);

                        while (_streamActive && !sr.EndOfStream && Twitter.AccountState == MyCommon.ACCOUNT_STATE.Valid)
                        {
                            StatusArrived?.Invoke(sr.ReadLine());
                            //this.LastTime = Now;
                        }

                        if (sr.EndOfStream || Twitter.AccountState == MyCommon.ACCOUNT_STATE.Invalid)
                        {
                            sleepSec = 30;
                            //MyCommon.TraceOut("Stop:EndOfStream")
                            continue;
                        }
                        break;
                    }
                    catch(WebException ex)
                    {
                        if (ex.Status == WebExceptionStatus.Timeout)
                        {
                            sleepSec = 30;                        //MyCommon.TraceOut("Stop:Timeout")
                        }
                        else if (ex.Response != null && (int)((HttpWebResponse)ex.Response).StatusCode == 420)
                        {
                            //MyCommon.TraceOut("Stop:Connection Limit")
                            break;
                        }
                        else
                        {
                            sleepSec = 30;
                            //MyCommon.TraceOut("Stop:WebException " + ex.Status.ToString())
                        }
                    }
                    catch(ThreadAbortException)
                    {
                        break;
                    }
                    catch(IOException)
                    {
                        sleepSec = 30;
                        //MyCommon.TraceOut("Stop:IOException with Active." + Environment.NewLine + ex.Message)
                    }
                    catch(ArgumentException ex)
                    {
                        //System.ArgumentException: ストリームを読み取れませんでした。
                        //サーバー側もしくは通信経路上で切断された場合?タイムアウト頻発後発生
                        sleepSec = 30;
                        MyCommon.TraceOut(ex, "Stop:ArgumentException");
                    }
                    catch(Exception ex)
                    {
                        MyCommon.TraceOut("Stop:Exception." + Environment.NewLine + ex.Message);
                        MyCommon.ExceptionOut(ex);
                        sleepSec = 30;
                    }
                    finally
                    {
                        if (_streamActive)
                        {
                            Stopped?.Invoke();
                        }
                        twCon.RequestAbort();
                        sr?.Close();
                        if (sleepSec > 0)
                        {
                            var ms = 0;
                            while (_streamActive && ms < sleepSec * 1000)
                            {
                                Thread.Sleep(500);
                                ms += 500;
                            }
                        }
                        sleepSec = 0;
                    }
                } while (this._streamActive);

                if (_streamActive)
                {
                    Stopped?.Invoke();
                }
                MyCommon.TraceOut("Stop:EndLoop");
            }
Example #6
0
        private List<FileWatcherHelper> ConvertPathsFromSettingToDictionary()
        {
            StreamReader streamReader = null;
            try
            {
                var serialiser = new XmlSerializer(typeof(List<FileWatcherHelper>));
                var paths = new ConcurrentBag<FileWatcherHelper>();
                streamReader = new StreamReader(_xmlPath);

                var pathsFromSetting = (List<FileWatcherHelper>) serialiser.Deserialize(streamReader);

                Parallel.ForEach(pathsFromSetting,
                    pathFromSetting =>
                    {
                        var fileWatcherHelper = new FileWatcherHelper
                                                {
                                                    Path = pathFromSetting.Path,
                                                    LastWriteTime = pathFromSetting.LastWriteTime
                                                };
                        paths.Add(fileWatcherHelper);
                    });

                return paths.ToList();
            }
            finally
            {
                streamReader?.Close();
            }
        }
        public ParsedSearch search(string showname, string searchString)
        {
            ParsedSearch ps = new ParsedSearch();
            ps.provider = theProvider;
            ps.SearchString = searchString;
            ps.Showname = showname;
            // request
            if (theProvider == null) {
                log.Error("No relation provider found/selected");
                return ps;
            }

            string url = getSearchUrl();
            log.Debug("Search URL: " + url);
            if (string.IsNullOrEmpty(url)) {
                log.Error("Can't search because no search URL is specified for this provider");
                return ps;
            }
            url = url.Replace(RenamingConstants.SHOWNAME_MARKER, searchString);
            url = System.Web.HttpUtility.UrlPathEncode(url);
            log.Debug("Encoded Search URL: " + url);
            WebRequest requestHtml = null;
            try {
                requestHtml = WebRequest.Create(url);
            }
            catch (Exception ex) {
                log.Error(ex.Message);
                requestHtml?.Abort();
                return ps;
            }
            //SetProxy(requestHtml, url);
            log.Info("Searching at " + url.Replace(" ", "%20"));
            requestHtml.Timeout = Convert.ToInt32(
                Settings.Instance.getAppConfiguration().getSingleNumberProperty(AppProperties.CONNECTION_TIMEOUT_KEY));
            // get response
            WebResponse responseHtml = null;
            try {
                responseHtml = requestHtml.GetResponse();
            }
            catch (Exception ex) {
                log.Error(ex.Message);
                responseHtml?.Close();
                requestHtml.Abort();
                return ps;
            }
            log.Debug("Search Results URL: " + responseHtml.ResponseUri.AbsoluteUri);
            //if search engine directs us straight to the result page, skip parsing search results
            string seriesURL = getSeriesUrl();
            if (responseHtml.ResponseUri.AbsoluteUri.Contains(seriesURL)) {
                log.Debug("Search Results URL contains Series URL: " + seriesURL);
                ps.Results = new Hashtable();
                string cleanedName = cleanSearchResultName(showname, getSearchRemove());
                if(getSearchResultsBlacklist() == "" || !Regex.Match(cleanedName,getSearchResultsBlacklist()).Success){
                    ps.Results.Add(cleanedName, responseHtml.ResponseUri.AbsoluteUri + getEpisodesUrl());
                    log.Info("Search engine forwarded directly to single result: " + responseHtml.ResponseUri.AbsoluteUri.Replace(" ", "%20") + getEpisodesUrl().Replace(" ", "%20"));
                }
                return ps;
            }
            log.Debug("Search Results URL doesn't contain Series URL: " + seriesURL + ", this is a proper search results page");
            // and download
            StreamReader r = null;
            try {
                r = new StreamReader(responseHtml.GetResponseStream());
            }
            catch (Exception ex) {
                r?.Close();
                responseHtml.Close();
                requestHtml.Abort();
                log.Error(ex.Message);
                return ps;
            }
            string source = r.ReadToEnd();
            r.Close();

            //Source cropping
            source = source.Substring(Math.Max(source.IndexOf(getSearchStart(), StringComparison.Ordinal), 0));
            source = source.Substring(0, Math.Max(source.LastIndexOf(getSearchEnd(), StringComparison.Ordinal), source.Length - 1));
            ps = parseSearch(ref source, responseHtml.ResponseUri.AbsoluteUri, showname, searchString);
            responseHtml.Close();
            return ps;
        }
        /// <summary>
        /// Parse the given configuration file and stores the data to the config
        /// </summary>
        /// <param name="configFilepath">the path to the config file to read</param>
        public static ConfigurationWrapper readConfiguration(string configFilepath)
        {
            FileStream configFileStream = null;
            StreamReader configFileReader = null;
            Configuration someConfiguration = new Configuration();
            try {
                ParserMode mode = ParserMode.Normal;
                string currentLine;
                int lineCounter = 0;
                string currentPropertyName = null;
                List<string> multipleValues = new List<string>();

                configFileStream = File.Open(configFilepath, FileMode.OpenOrCreate, FileAccess.Read);
                configFileReader = new StreamReader(configFileStream);

                while ((currentLine = configFileReader.ReadLine()) != null) {
                    lineCounter++;

                    currentLine = cleanupLine(currentLine);

                    if (String.IsNullOrEmpty(currentLine) || isComment(currentLine)) {
                        continue;
                    }

                    switch (mode) {
                        case ParserMode.MultiValueProperty:
                            if (currentLine.Equals(Configuration.END_MULTI_VALUE_FIELD)) {
                                someConfiguration[currentPropertyName] = multipleValues;
                                mode = ParserMode.Normal;
                            } else {
                                multipleValues.Add(currentLine);
                            }
                            continue;
                        case ParserMode.Normal:
                            int keyValueSeparatorIndex =
                                currentLine.IndexOf(Configuration.KEY_VALUE_SEPARATOR, StringComparison.Ordinal);
                            if (keyValueSeparatorIndex <= 0) {
                                logCorruptLine(lineCounter);
                                continue;
                            }
                            currentPropertyName = currentLine.Substring(0, keyValueSeparatorIndex).Trim();
                            string valuePart = currentLine.Substring(keyValueSeparatorIndex + 1).Trim();

                            if (String.IsNullOrEmpty(valuePart)) {
                                log.Debug("Property " + currentPropertyName + " is not set");
                                continue;
                            }
                            if (valuePart.Equals(Configuration.BEGIN_MULTI_VALUE_PROPERTY)) {
                                mode = ParserMode.MultiValueProperty;
                                multipleValues.Clear();
                            } else {
                                someConfiguration[currentPropertyName] = valuePart;
                            }
                            break;
                        default:
                            continue;
                    }

                }

            } catch (Exception ex) {
                AppConfigurationWrapper appConfiguration = AppDefaults.getDefaultConfiguration();
                writeConfiguration(appConfiguration, configFilepath);
                log.Error("Couldn't process config file " + configFilepath + ":" + ex.Message);
                log.Warn("Generating configuration file using default values.");
            } finally {
                configFileStream?.Close();
                configFileReader?.Close();
            }
            return new ConfigurationWrapper(someConfiguration);
        }