Exemplo n.º 1
0
        /// <summary>
        /// Load the specified web page into a string.
        /// </summary>
        /// <param name="url">The url to load.</param>
        /// <returns>The web page as a string.</returns>
        public static String LoadPage(Uri url)
        {
            try
            {
                var result = new StringBuilder();
                var buffer = new byte[BufferSize];

                int length;

                WebRequest http     = WebRequest.Create(url);
                var        response = (HttpWebResponse)http.GetResponse();
                Stream     istream  = response.GetResponseStream();

                do
                {
                    length = istream.Read(buffer, 0, buffer.Length);
                    if (length > 0)
                    {
                        String str = Encoding.UTF8.GetString(buffer, 0, length);
                        result.Append(str);
                    }
                } while (length > 0);

                return(result.ToString());
            }
            catch (IOException e)
            {
#if logging
                if (LOGGER.IsErrorEnabled)
                {
                    LOGGER.Error("Exception", e);
                }
#endif
                throw new BotError(e);
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// Validates this instance.
 /// </summary>
 protected override void Validate()
 {
     try
     {
         foreach (ThreadPoolItem item in mSettings.ThreadPools)
         {
             if (item.MinThreadNumber < 1)
             {
                 throw new ConfigurationErrorsException("MinThreadNumber");
             }
             if (item.MaxThreadNumber < 1)
             {
                 throw new ConfigurationErrorsException("MaxThreadNumber");
             }
             if (item.ShutDownIdleThreadTime < 1)
             {
                 throw new ConfigurationErrorsException("ShutDownIdleThreadTime");
             }
             item.Name.ToString();
             item.SetReadOnlyFlag.ToString();
         }
         mLastKnownGoodSettings = mSettings;
     }
     catch (Exception ex)
     {
         if (LOGGER.IsErrorEnabled)
         {
             LOGGER.Error(string.Format("THREADPOOL: validation of the configuration has failed. Reason: {0}", ex.Message));
         }
         if (mLastKnownGoodSettings == null)
         {
             mLastKnownGoodSettings = LoadFactoryDefaults();
         }
         mSettings = mLastKnownGoodSettings;
     }
 }
Exemplo n.º 3
0
        protected override bool  Generate(System.IO.Stream str, List <ProcessedEpisode> elist)
        {
            DirFilesCache dfc = new DirFilesCache();

            try
            {
                XmlWriterSettings settings = new XmlWriterSettings
                {
                    Indent = true,
                    NewLineOnAttributes = true,
                    Encoding            = System.Text.Encoding.ASCII
                };
                using (XmlWriter writer = XmlWriter.Create(str, settings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("WhenToWatch");

                    foreach (ProcessedEpisode ei in elist)
                    {
                        writer.WriteStartElement("item");
                        XmlHelper.WriteElementToXml(writer, "id", ei.TheSeries.TvdbCode);
                        XmlHelper.WriteElementToXml(writer, "SeriesName", ei.TheSeries.Name);
                        XmlHelper.WriteElementToXml(writer, "SeasonNumber", Helpers.Pad(ei.AppropriateSeasonNumber));
                        XmlHelper.WriteElementToXml(writer, "EpisodeNumber", Helpers.Pad(ei.AppropriateEpNum));
                        XmlHelper.WriteElementToXml(writer, "EpisodeName", ei.Name);

                        writer.WriteStartElement("available");
                        DateTime?airdt = ei.GetAirDateDT(true);

                        if (airdt.HasValue && airdt.Value.CompareTo(DateTime.Now) < 0) // has aired
                        {
                            List <FileInfo> fl = TVDoc.FindEpOnDisk(dfc, ei);
                            if ((fl != null) && (fl.Count > 0))
                            {
                                writer.WriteValue("true");
                            }
                            else if (ei.Show.DoMissingCheck)
                            {
                                writer.WriteValue("false");
                            }
                        }

                        writer.WriteEndElement();
                        XmlHelper.WriteElementToXml(writer, "Overview", ei.Overview);

                        writer.WriteStartElement("FirstAired");
                        DateTime?dt = ei.GetAirDateDT(true);
                        if (dt != null)
                        {
                            writer.WriteValue(dt.Value.ToString("F"));
                        }
                        writer.WriteEndElement();

                        XmlHelper.WriteElementToXml(writer, "Rating", ei.EpisodeRating);
                        XmlHelper.WriteElementToXml(writer, "filename", ei.Filename);

                        writer.WriteEndElement(); // item
                    }
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
                return(true);
            } // try
            catch (Exception e)
            {
                if ((!Doc.Args.Unattended) && (!Doc.Args.Hide))
                {
                    MessageBox.Show(e.Message);
                }
                LOGGER.Error(e);
                return(false);
            }
        }
Exemplo n.º 4
0
        public bool GetUpdates(bool showErrorMsgBox, CancellationToken cts, IEnumerable <SeriesSpecifier> ss)
        {
            Say("Validating TMDB cache");
            MarkPlaceHoldersDirty(ss);

            try
            {
                Say($"Updates list from TMDB since {latestMovieUpdateTime.LastSuccessfulServerUpdateDateTime()}");

                long updateFromEpochTime = latestMovieUpdateTime.LastSuccessfulServerUpdateTimecode();
                if (updateFromEpochTime == 0)
                {
                    MarkAllDirty();
                    latestMovieUpdateTime.RegisterServerUpdate(DateTime.Now.ToUnixTime());
                    return(true);
                }

                List <int> updates = Client.GetChangesMovies(cts, latestMovieUpdateTime).Select(item => item.Id).Distinct().ToList();

                Say($"Processing {updates.Count} updates from TMDB. From between {latestMovieUpdateTime.LastSuccessfulServerUpdateDateTime()} and {latestMovieUpdateTime.ProposedServerUpdateDateTime()}");
                foreach (int id in updates)
                {
                    if (!cts.IsCancellationRequested)
                    {
                        if (HasMovie(id))
                        {
                            CachedMovieInfo?x = GetMovie(id);
                            if (!(x is null))
                            {
                                LOGGER.Info(
                                    $"Identified that show with TMDB Id {id} {x.Name} should be updated.");

                                x.Dirty = true;
                            }
                        }
                    }
                    else
                    {
                        return(true);
                    }
                }
                lock (MOVIE_LOCK)
                {
                    Say($"Identified {Movies.Values.Count(info => info.Dirty && !info.IsSearchResultOnly)} TMDB Movies need updating");
                    LOGGER.Info(Movies.Values.Where(info => info.Dirty && !info.IsSearchResultOnly).Select(info => info.Name).ToCsv);
                }
                return(true);
            }
            catch (SourceConnectivityException conex)
            {
                LastErrorMessage = conex.Message;
                return(false);
            }
            catch (SourceConsistencyException sce)
            {
                LOGGER.Error(sce.Message);
                LastErrorMessage = sce.Message;
                return(false);
            }
            finally
            {
                SayNothing();
            }
        }
Exemplo n.º 5
0
        public override void Check(SetProgressDelegate prog, int startpct, int totPct)
        {
            if (string.IsNullOrEmpty(TVSettings.Instance.SABAPIKey) || string.IsNullOrEmpty(TVSettings.Instance.SABHostPort))
            {
                prog.Invoke(totPct);
                return;
            }

            // get list of files being downloaded by SABnzbd

            // Something like:
            // http://localhost:8080/sabnzbd/api?mode=queue&apikey=xxx&start=0&limit=8888&output=xml
            string theUrl = "http://" + TVSettings.Instance.SABHostPort +
                            "/sabnzbd/api?mode=queue&start=0&limit=8888&output=xml&apikey=" + TVSettings.Instance.SABAPIKey;

            byte[] r = DownloadPage(theUrl);

            if (r == null)
            {
                prog.Invoke(totPct);
                return;
            }

            try
            {
                SAB.Result res = SAB.Result.Deserialize(r);
                if (res != null && res.status == "False")
                {
                    LOGGER.Error("Error processing data from SABnzbd (Queue Check): {0}", res.error);
                    prog.Invoke(totPct);
                    return;
                }
            }
            catch
            {
                // wasn't a result/error combo.  this is good!
            }

            SAB.Queue sq;
            try
            {
                sq = SAB.Queue.Deserialize(r);
            }
            catch (Exception e)
            {
                LOGGER.Error(e, "Error processing data from SABnzbd (Queue Check)");
                prog.Invoke(totPct);
                return;
            }

            System.Diagnostics.Debug.Assert(sq != null);  // shouldn't happen
            if (sq.slots == null || sq.slots.Length == 0) // empty queue
            {
                return;
            }

            ItemList newList  = new ItemList();
            ItemList toRemove = new ItemList();
            int      c        = ActionList.Count + 2;
            int      n        = 1;

            foreach (ItemMissing action in ActionList.MissingItems())
            {
                if (ActionCancel)
                {
                    return;
                }

                prog.Invoke(startpct + ((totPct - startpct) * (++n) / (c)));

                string showname = Helpers.SimplifyName(action.Episode.Show.ShowName);

                foreach (SAB.QueueSlotsSlot te in sq.slots)
                {
                    FileInfo file = new FileInfo(te.filename);

                    if (!FileHelper.SimplifyAndCheckFilename(file.FullName, showname, true, false))
                    {
                        continue;
                    }
                    if (!TVDoc.FindSeasEp(file, out int seasF, out int epF, out int _, action.Episode.Show) ||
                        (seasF != action.Episode.AppropriateSeasonNumber) || (epF != action.Episode.AppropriateEpNum))
                    {
                        continue;
                    }
                    toRemove.Add(action);
                    newList.Add(new ItemDownloading(te, action.Episode, action.TheFileNoExt, DownloadApp.SABnzbd));
                    break;
                }
            }

            foreach (Item i in toRemove)
            {
                ActionList.Remove(i);
            }

            foreach (Item action in newList)
            {
                ActionList.Add(action);
            }

            prog.Invoke(totPct);
        }
Exemplo n.º 6
0
        protected override void DoCheck(SetProgressDelegate prog, TVDoc.ScanSettings settings)
        {
            if (TVSettings.Instance.RenameCheck)
            {
                MDoc.Stats().RenameChecksDone++;
            }

            if (TVSettings.Instance.MissingCheck)
            {
                MDoc.Stats().MissingChecksDone++;
            }

            DirFilesCache dfc = new DirFilesCache();

            List <ShowConfiguration> showList = settings.Shows;

            if (settings.Type == TVSettings.ScanType.Full && showList.Count > 0)
            {
                // only do episode count if we're doing all shows and seasons
                MDoc.CurrentStats.NsNumberOfEpisodes = 0;
            }

            int c = 0;

            UpdateStatus(c, showList.Count, "Checking shows");
            foreach (ShowConfiguration si in showList.OrderBy(item => item.ShowName))
            {
                UpdateStatus(c++, showList.Count, si.ShowName);
                if (settings.Token.IsCancellationRequested)
                {
                    return;
                }

                LOGGER.Info("Rename and missing check: " + si.ShowName);
                try
                {
                    new CheckAllFoldersExist(MDoc).CheckIfActive(si, dfc, settings);
                    new MergeLibraryEpisodes(MDoc).CheckIfActive(si, dfc, settings);
                    new RenameAndMissingCheck(MDoc).CheckIfActive(si, dfc, settings);
                }
                catch (TVRenameOperationInterruptedException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    LOGGER.Error(e, $"Failed to scan {si.ShowName}. Please double check settings for this show: {si.TvdbCode}: {si.AutoAddFolderBase}");
                }
            } // for each show

            c = 0;
            UpdateStatus(c, settings.Movies.Count, "Checking movies");
            foreach (MovieConfiguration si in settings.Movies.OrderBy(item => item.ShowName))
            {
                UpdateStatus(c++, settings.Movies.Count, si.ShowName);
                if (settings.Token.IsCancellationRequested)
                {
                    return;
                }

                LOGGER.Info("Rename and missing check: " + si.ShowName);
                try
                {
                    new CheckAllMovieFoldersExist(MDoc).CheckIfActive(si, dfc, settings);
                    new RenameAndMissingMovieCheck(MDoc).CheckIfActive(si, dfc, settings);
                }
                catch (TVRenameOperationInterruptedException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    LOGGER.Error(e, $"Failed to scan {si.ShowName}. Please double check settings for this movie: {si.Code}: {si}");
                }
            } // for each movie

            MDoc.RemoveIgnored();
        }
Exemplo n.º 7
0
            public override bool LoadBlocks()
            {
                isSetup = true;

                UpdateConfig();

                gyros.Clear();
                allThrusters.Clear();
                brakingThrusters.Clear();
                otherThrusters.Clear();

                if (controllerName == "")
                {
                    List <IMyShipController> lstController = new List <IMyShipController>();
                    p.GridTerminalSystem.GetBlocksOfType(lstController);
                    if (lstController.Count == 0)
                    {
                        LOGGER.Error("No ship controller on this ship");
                        isSetup = false;
                    }
                    else
                    {
                        // Récupère le premier controller trouvé
                        referenceBlock = lstController[0];
                    }
                }
                else
                {
                    referenceBlock = (IMyShipController)p.GridTerminalSystem.GetBlockGroupWithName(controllerName);
                    isSetup        = referenceBlock != null;
                }

                p.GridTerminalSystem.GetBlocksOfType(gyros);
                p.GridTerminalSystem.GetBlocksOfType(allThrusters);

                if (referenceBlock != null)
                {
                    GetThrusterOrientation(referenceBlock);
                }


                if (brakingThrusters.Count == 0)
                {
                    isSetup = false;
                    p.Echo("CRITICAL: No braking thrusters were found");
                }

                if (gyros.Count == 0)
                {
                    isSetup = false;
                    p.Echo($"CRITICAL: No gyroscopes were found");
                }

                if (!isSetup)
                {
                    p.Echo("Setup Failed!");
                }
                else
                {
                    p.Echo("Setup Successful!");
                    shipCenterToEdge = GetShipFarthestEdgeDistance(referenceBlock);
                }
                return(isSetup);
            }
Exemplo n.º 8
0
        private void LoadXml([NotNull] XElement seriesXml)
        {
            //<Data>
            // <Series>
            //  <id>...</id>
            //  etc.
            // </Series>
            // <Episode>
            //  <id>...</id>
            //  blah blah
            // </Episode>
            // <Episode>
            //  <id>...</id>
            //  blah blah
            // </Episode>
            // ...
            //</Data>

            try
            {
                TvdbCode   = seriesXml.ExtractInt("id") ?? throw new SourceConsistencyException("Error Extracting Id for Series", TVDoc.ProviderType.TheTVDB);
                TvMazeCode = seriesXml.ExtractInt("mazeid") ?? -1;
                TmdbCode   = seriesXml.ExtractInt("TMDBCode") ?? -1;

                Name = System.Web.HttpUtility.HtmlDecode(
                    XmlHelper.ReadStringFixQuotesAndSpaces(seriesXml.ExtractStringOrNull("SeriesName") ?? seriesXml.ExtractString("seriesName")));

                SrvLastUpdated = seriesXml.ExtractLong("lastupdated") ?? seriesXml.ExtractLong("lastUpdated", 0);
                LanguageId     = seriesXml.ExtractInt("LanguageId") ?? seriesXml.ExtractInt("languageId") ?? throw new SourceConsistencyException("Error Extracting Language for Series", TVDoc.ProviderType.TheTVDB);

                CollectionId   = seriesXml.ExtractInt("CollectionId");
                CollectionName = seriesXml.ExtractStringOrNull("CollectionName");
                TwitterId      = seriesXml.ExtractStringOrNull("TwitterId");
                InstagramId    = seriesXml.ExtractStringOrNull("InstagramId");
                FacebookId     = seriesXml.ExtractStringOrNull("FacebookId");
                TagLine        = seriesXml.ExtractStringOrNull("TagLine");

                PosterUrl       = seriesXml.ExtractString("posterURL");
                TrailerUrl      = seriesXml.ExtractString("TrailerUrl");
                FanartUrl       = seriesXml.ExtractString("FanartUrl");
                Imdb            = seriesXml.ExtractStringOrNull("imdbId") ?? seriesXml.ExtractString("IMDB_ID");
                WebUrl          = seriesXml.ExtractString("WebURL");
                OfficialUrl     = seriesXml.ExtractString("OfficialUrl");
                Type            = seriesXml.ExtractString("Type");
                ShowLanguage    = seriesXml.ExtractString("ShowLanguage");
                TvRageCode      = seriesXml.ExtractInt("rageid") ?? 0;
                Network         = seriesXml.ExtractStringOrNull("network") ?? seriesXml.ExtractString("Network");
                Overview        = seriesXml.ExtractStringOrNull("overview") ?? seriesXml.ExtractString("Overview");
                ContentRating   = seriesXml.ExtractStringOrNull("rating") ?? seriesXml.ExtractString("Rating");
                Runtime         = seriesXml.ExtractStringOrNull("runtime") ?? seriesXml.ExtractString("Runtime");
                SeriesId        = seriesXml.ExtractStringOrNull("seriesId") ?? seriesXml.ExtractString("SeriesID");
                Status          = seriesXml.ExtractStringOrNull("status") ?? seriesXml.ExtractString("Status");
                SiteRatingVotes = seriesXml.ExtractInt("siteRatingCount") ?? seriesXml.ExtractInt("SiteRatingCount", 0);
                Slug            = seriesXml.ExtractString("slug");

                SiteRating = GetSiteRating(seriesXml);
                FirstAired = JsonHelper.ParseFirstAired(seriesXml.ExtractStringOrNull("FirstAired") ?? seriesXml.ExtractString("firstAired"));

                LoadActors(seriesXml);
                LoadAliases(seriesXml);
                LoadGenres(seriesXml);
            }
            catch (SourceConsistencyException e)
            {
                LOGGER.Error(e, GenerateErrorMessage());
                // ReSharper disable once PossibleIntendedRethrow
                throw e;
            }
        }
Exemplo n.º 9
0
        public WorkTimeEstimateDataSet GetWorkTimeEstimateToPrint(
            int appId,
            int prjId,
            string depCode,
            string reportType,
            Dictionary <string, string> param)
        {
            LOGGER.Finest("Entering GetWorkTimeEstimateToPrint");

            OracleConnection connection = null;

            OracleParameter    appIdParam      = null;
            OracleParameter    prjIdParam      = null;
            OracleParameter    depCodeParam    = null;
            OracleParameter    reportTypeParam = null;
            OracleParameter    prjNumberParam  = null;
            OracleParameter    prjNameParam    = null;
            OracleParameter    weightParam     = null;
            OracleParameter    qtyParam        = null;
            OracleParameter    repDateParam    = null;
            OracleParameter    authorParam     = null;
            OracleParameter    itemsParam      = null;
            OracleParameter    itemsDepParam   = null;
            NullableDataReader nullableReader  = null;


            //
            //
            WorkTimeEstimateDataSet result = new WorkTimeEstimateDataSet();
            //
            //



            OracleCommand cmd = new OracleCommand();

            cmd.CommandType = CommandType.StoredProcedure;

            try
            {
                connection      = getConnection();
                cmd.CommandText = "WB_PCK_REPORTS_WORK.get_work_time_estimate";
                cmd.Connection  = connection;

                appIdParam      = SQLUtil.CreateInt32OracleParam("P_APP_ID", cmd, appId, ParameterDirection.Input);
                prjIdParam      = SQLUtil.CreateInt32OracleParam("p_prj_id", cmd, prjId, ParameterDirection.Input);
                depCodeParam    = SQLUtil.CreateVarcharOracleParam("p_dep_code", cmd, depCode, ParameterDirection.Input);
                reportTypeParam = SQLUtil.CreateVarcharOracleParam("p_report_type", cmd, reportType, ParameterDirection.Input);
                prjNumberParam  = SQLUtil.CreateVarcharOracleParam("o_prj_number", cmd, null, ParameterDirection.Output);
                prjNameParam    = SQLUtil.CreateVarcharOracleParam("o_prj_name", cmd, null, ParameterDirection.Output);
                weightParam     = SQLUtil.CreateInt32OracleParam("o_weight", cmd, null, ParameterDirection.Output);
                qtyParam        = SQLUtil.CreateInt32OracleParam("o_qty", cmd, null, ParameterDirection.Output);
                repDateParam    = SQLUtil.CreateDateOracleParam("o_rep_date", cmd, null, ParameterDirection.Output);
                authorParam     = SQLUtil.CreateVarcharOracleParam("o_author", cmd, null, ParameterDirection.Output);
                itemsParam      = SQLUtil.CreateCursorOracleParameter("o_items", OracleDbType.RefCursor, cmd);
                itemsDepParam   = SQLUtil.CreateCursorOracleParameter("o_items_dep", OracleDbType.RefCursor, cmd);

                cmd.ExecuteNonQuery();

                WorkTimeEstimateDataSet.WorkTimeMainTableRow row = result.WorkTimeMainTable.NewWorkTimeMainTableRow();

                row.ID         = prjId.ToString();
                row.ProjNumber = SQLUtil.GetStringValue(prjNumberParam);
                row.ProjName   = SQLUtil.GetStringValue(prjNameParam);
                row.Weight     = SQLUtil.GetDecimalValue(weightParam).HasValue ? SQLUtil.GetDecimalValue(weightParam).ToString() : "---";
                row.Qty        = SQLUtil.GetDecimalValue(qtyParam).HasValue ? SQLUtil.GetDecimalValue(qtyParam).ToString() : "---";
                row.AllWeight  = SQLUtil.GetDecimalValue(weightParam).HasValue ? SQLUtil.GetDecimalValue(weightParam).ToString() : "---";
                row.ReportDate = SQLUtil.GetDateValue(repDateParam).HasValue ? SQLUtil.GetDateValue(repDateParam).Value.Date.ToShortDateString() : "---";
                row.Author     = SQLUtil.GetStringValue(authorParam);

                result.WorkTimeMainTable.AddWorkTimeMainTableRow(row);

                if (!((OracleRefCursor)itemsParam.Value).IsNull)
                {
                    nullableReader = new NullableDataReader(((OracleRefCursor)itemsParam.Value).GetDataReader());

                    string TYPE           = string.Empty;
                    string name           = string.Empty;
                    string drawing_number = string.Empty;

                    string activePath = string.Empty;
                    WorkTimeEstimateDataSet.WorkTimePathRow path = null;


                    while (nullableReader.Read())
                    {
                        string iPath = ConvertUtil.ConvertToSpecialChars(nullableReader.GetNullableString("pwei_path"));

                        if (string.IsNullOrEmpty(iPath))
                        {
                            continue;
                        }

                        WorkTimeEstimateDataSet.WorkTimeItemSimpleRow item = result.WorkTimeItemSimple.NewWorkTimeItemSimpleRow();


                        item.ID        = prjId.ToString();
                        item.ItemID    = nullableReader.GetNullableDecimal("pwei_id").ToString();
                        item.IsProduct = nullableReader.GetNullableDecimal("pwei_is_product").ToString();
                        item.ParentID  = nullableReader.GetNullableDecimal("pwei_parent_pwei_id").ToString();

                        TYPE = nullableReader.GetNullableString("pwei_itm_type");
                        name = ConvertUtil.ConvertToSpecialChars(nullableReader.GetNullableString("pwei_name"));

                        drawing_number = ConvertUtil.ConvertToSpecialChars(nullableReader.GetNullableString("pwei_drawing_number"));



                        item.DrawingNumber = drawing_number;
                        item.Qty           = nullableReader.GetNullableDecimal("pwei_qty").ToString();
                        item.QtyPerProj    = nullableReader.GetNullableDecimal("pwei_qty_per_prj").ToString();
                        if (nullableReader.GetNullableString("pwei_product_brand") != null)
                        {
                            item.ProductBrand = nullableReader.GetNullableString("pwei_product_brand");
                        }
                        else
                        {
                            item.ProductBrand = "";
                        }

                        string tmp_sizeCut = nullableReader.GetNullableString("pwei_size_cut");
                        string tmp_addInfo = nullableReader.GetNullableString("pwei_add_info");
                        item.SizeCut = string.IsNullOrEmpty(tmp_sizeCut) ? "" : ConvertUtil.ConvertToSpecialChars(tmp_sizeCut.Replace("X", " x ").Replace("L=", "L= "));
                        if (!string.IsNullOrEmpty(tmp_addInfo))
                        {
                            item.SizeCut += string.Format("\n{0}", tmp_addInfo);
                        }
                        item.SizeCut = ConvertUtil.ConvertToSpecialChars(item.SizeCut);

                        if (param.ContainsKey("productSize"))
                        {
                            if (!item.SizeCut.ToLower().Contains(param["productSize"]))
                            {
                                continue;
                            }
                        }

                        // material gatunek
                        string tempPrName = ConvertUtil.ConvertToSpecialChars(nullableReader.GetNullableString("pwei_pr_name"));
                        if (!string.IsNullOrEmpty(tempPrName))
                        {
                            item.PrName = tempPrName + "\n" + ConvertUtil.ConvertToSpecialChars(item.ProductBrand);
                        }
                        else
                        {
                            item.PrName = " " + "\n" + ConvertUtil.ConvertToSpecialChars(item.ProductBrand);
                        }

                        if (param.ContainsKey("materialType"))
                        {
                            if (!item.PrName.ToLower().Contains(param["materialType"]))
                            {
                                continue;
                            }
                        }

                        item.ProgramNumber = ConvertUtil.ConvertToSpecialChars(nullableReader.GetNullableString("pwei_program_number"));

                        decimal?value = nullableReader.GetNullableDecimal("pwei_ls");
                        item.LS = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.LS.Equals("0,000"))
                        {
                            item.LS = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_es");
                        item.ES = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.ES.Equals("0,000"))
                        {
                            item.ES = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_bn");
                        item.BN = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.BN.Equals("0,000"))
                        {
                            item.BN = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_pt");
                        item.PT = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.PT.Equals("0,000"))
                        {
                            item.PT = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_bw");
                        item.BW = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.BW.Equals("0,000"))
                        {
                            item.BW = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_bz");
                        item.BZ = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.BZ.Equals("0,000"))
                        {
                            item.BZ = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_ph");
                        item.PH = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.PH.Equals("0,000"))
                        {
                            item.PH = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_wp");
                        item.WP = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.WP.Equals("0,000"))
                        {
                            item.WP = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_rp");
                        item.RP = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.RP.Equals("0,000"))
                        {
                            item.RP = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_po");
                        item.PO = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.PO.Equals("0,000"))
                        {
                            item.PO = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_mw");
                        item.MW = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.MW.Equals("0,000"))
                        {
                            item.MW = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_mc");
                        item.MC = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.MC.Equals("0,000"))
                        {
                            item.MC = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_ML");
                        item.ML = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.ML.Equals("0,000"))
                        {
                            item.ML = "0";
                        }
                        value   = nullableReader.GetNullableDecimal("pwei_KO");
                        item.KO = value.HasValue ? string.Format("{0:f2}", value.Value) : "";
                        if (item.KO.Equals("0,000"))
                        {
                            item.KO = "0";
                        }

                        item.PlanNumber = nullableReader.GetNullableDecimal("pwei_lp").HasValue ?
                                          nullableReader.GetNullableDecimal("pwei_lp").Value.ToString() : "";

                        if (param.ContainsKey("planNo"))
                        {
                            if (!(item.PlanNumber.ToLower() == param["planNo"].ToLower()))
                            {
                                continue;
                            }
                        }

                        item.WorkTimeMainTableRow = row;

                        result.WorkTimeItemSimple.AddWorkTimeItemSimpleRow(item);
                    }
                }
            }

            catch (Exception ex)
            {
                LOGGER.Error("Problem occured while GetWorkTimeEstimateToPrint!" + ex.Message, ex);
                throw new Exception("Problem occured while GetWorkTimeEstimateToPrint!" + ex.Message, ex);
            }
            finally
            {
                SQLUtil.Close(appIdParam);
                SQLUtil.Close(prjIdParam);
                SQLUtil.Close(depCodeParam);
                SQLUtil.Close(reportTypeParam);
                SQLUtil.Close(prjNumberParam);
                SQLUtil.Close(prjNameParam);
                SQLUtil.Close(weightParam);
                SQLUtil.Close(qtyParam);
                SQLUtil.Close(repDateParam);
                SQLUtil.Close(authorParam);
                SQLUtil.Close(itemsParam);
                SQLUtil.Close(itemsDepParam);
                SQLUtil.Close(nullableReader);
                SQLUtil.Close(cmd);
                ReleaseConnection(connection);
            }


            return(result);
        }
Exemplo n.º 10
0
            protected override bool LoadBlocks()
            {
                isSetup = true;

                gyros.Clear();
                thrustersAndFlags.Clear();

                if (controllerName == "")
                {
                    List <IMyShipController> lstController = new List <IMyShipController>();
                    p.GridTerminalSystem.GetBlocksOfType(lstController);
                    if (lstController.Count == 0)
                    {
                        LOGGER.Error("No ship controller on this ship");
                        isSetup = false;
                    }
                    else
                    {
                        // Récupère le premier controller trouvé
                        referenceBlock = lstController[0];
                        LOGGER.Info("Controller found");
                    }
                }
                else
                {
                    referenceBlock = (IMyShipController)p.GridTerminalSystem.GetBlockGroupWithName(controllerName);
                    LOGGER.Info("Controller with name " + controllerName + " found");
                    isSetup = referenceBlock != null;
                }


                List <IMyThrust> allThrusters = new List <IMyThrust>();

                p.GridTerminalSystem.GetBlocksOfType(gyros);
                p.GridTerminalSystem.GetBlocksOfType(allThrusters);

                if (referenceBlock != null)
                {
                    GetThrusterOrientation(allThrusters);
                }

                if (GetThrusters(ThrustersFlag.Braking).Count == 0)
                {
                    isSetup = false;
                    p.Echo("CRITICAL: No braking thrusters were found");
                }

                if (gyros.Count == 0)
                {
                    isSetup = false;
                    p.Echo($"CRITICAL: No gyroscopes were found");
                }

                if (!isSetup)
                {
                    p.Echo("Setup Failed!");
                }
                else
                {
                    p.Echo("Setup Successful!");
                    shipCenterToEdge          = GetShipFarthestEdgeDistance(referenceBlock);
                    p.Runtime.UpdateFrequency = UPDATE_FREQUENCY;
                }
                return(isSetup);
            }
Exemplo n.º 11
0
            private void DoAcceptSocketCallback(IAsyncResult ar)
            {
                ITcpListener listener  = (ITcpListener)ar.AsyncState;
                ITcpClient   tcpClient = null;

                try
                {
                    tcpClient = listener.EndAcceptTcpClient(ar);
                    if (mManager.UseSocketKeepAlive)
                    {
                        tcpClient.Client.SetKeepAliveValues(true, mManager.SocketKeepAliveTime, mManager.SocketKeepAliveTimeInterval);
                    }
                    tcpClient.Client.SendBufferSize    = mManager.SocketSendBufferSize;
                    tcpClient.Client.ReceiveBufferSize = mManager.SocketReceiveBufferSize;
                    if (LOGGER.IsDebugEnabled)
                    {
                        LOGGER.Debug(string.Format("New TcpClient connection accepted. Local endpoint: {0}, remote endpoint: {1}", tcpClient.Client.LocalEndPoint.ToString(), tcpClient.Client.RemoteEndPoint.ToString()));
                    }
                }
                catch (Exception ex)
                {
                    // ez a szerver leállítása közben történhet
                    if (LOGGER.IsDebugEnabled)
                    {
                        LOGGER.Debug(string.Format("Failed to configure accepted TcpClient. Reason: {0}", ex.Message));
                    }
                    return;
                }

                NetworkStream networkStream = null;

                try
                {
                    if (LOGGER.IsDebugEnabled)
                    {
                        LOGGER.Debug(string.Format("Create network stream around the socket connection. Server stream factory type is '{0}'.", mServerStreamFactory.GetType().FullName));
                    }
                    networkStream = mServerStreamFactory.CreateNetworkStream(tcpClient);
                }
                catch (Exception ex)
                {
                    if (LOGGER.IsErrorEnabled)
                    {
                        LOGGER.Error(String.Format("ServerStreamFactory implementation threw an exception ({0}).", mServerStreamFactory.GetType().AssemblyQualifiedName), ex);
                    }
                }

                if (networkStream == null)
                {
                    if (LOGGER.IsDebugEnabled)
                    {
                        LOGGER.Debug(string.Format("Failed to create network stream for a connection. Server stream factory '{0}' does not provide NetworkStream.", mServerStreamFactory.GetType().FullName));
                    }
                    tcpClient.Close();
                    BeginAccept();
                }
                else
                {
                    if (LOGGER.IsDebugEnabled)
                    {
                        LOGGER.Debug(string.Format("Propagate event about the new connection. Listening endpoint: {0}, local endpoint: {1}, remote endpoint: {2}. Network stream id: {3}", listener.LocalEndpoint.ToString(), tcpClient.Client.LocalEndPoint.ToString(), tcpClient.Client.RemoteEndPoint.ToString(), networkStream.Id.ToString()));
                    }
                    BeginAccept();
                    this.mManager.OnNetworkPeerConnected(new ConnectionEventArgs(this.mServerId, listener.LocalEndpoint, networkStream));
                }
            }
Exemplo n.º 12
0
        private void SearchFiles(string path, string filters, bool searchRecursively, bool searchHidden, FoundFilesOrderByFilter order)
        {
            try
            {
                LOGGER.Info($"Searching for files");
                LOGGER.Info($"Parameters => path: '{path}', filters: '{filters}', recursive: {searchRecursively}, hidden: {searchHidden}, order by: {order}");

                runningCount++;
                State = RunningState.Running;

                if (State == RunningState.CancelPending)
                {
                    LOGGER.Info($"Canceling search");

                    return;
                }

                if (!searchHidden && new DirectoryInfo(path).Attributes.HasFlag(FileAttributes.Hidden))
                {
                    LOGGER.Info($"Path '{path}' is hidden and hidden search is disabled => skipping directory");
                    return;
                }

                string[] singleFilters = filters.Split(';');

                foreach (var filter in singleFilters)
                {
                    var files = Directory.GetFiles(path, filter).Select(p => new FileInfo(p)).ToArray();

                    LOGGER.Info($"Found {files.Length} files for filter '{filter}' in path '{path}'");

                    switch (order)
                    {
                    case FoundFilesOrderByFilter.NameAsc:
                        files = files.OrderBy((file) => file.Name).ToArray();
                        break;

                    case FoundFilesOrderByFilter.NameDsc:
                        files = files.OrderByDescending((file) => file.Name).ToArray();
                        break;

                    case FoundFilesOrderByFilter.CreationDateAsc:
                        files = files.OrderBy((file) => file.CreationTimeUtc).ToArray();
                        break;

                    case FoundFilesOrderByFilter.CreationDateDsc:
                        files = files.OrderByDescending((file) => file.CreationTimeUtc).ToArray();
                        break;

                    case FoundFilesOrderByFilter.ChangedDateAsc:
                        files = files.OrderBy((file) => file.LastWriteTimeUtc).ToArray();
                        break;

                    case FoundFilesOrderByFilter.ChangedDateDsc:
                        files = files.OrderByDescending((file) => file.LastWriteTimeUtc).ToArray();
                        break;

                    case FoundFilesOrderByFilter.SizeAsc:
                        files = files.OrderBy((file) => file.Length).ToArray();
                        break;

                    case FoundFilesOrderByFilter.SizeDsc:
                        files = files.OrderByDescending((file) => file.Length).ToArray();
                        break;

                    default:
                        files = files.OrderBy((file) => file.Name).ToArray();
                        break;
                    }

                    foreach (var file in files.Where(f => !f.Name.StartsWith("_") && IsVideoAnalyzer.IsVideo(f.Name)))
                    {
                        LOGGER.Info($"Found video file '{file.FullName}'");

                        FileFound?.Invoke(new FileSystemEventArgs(WatcherChangeTypes.All, file.DirectoryName, file.Name));
                    }
                }

                if (searchRecursively)
                {
                    LOGGER.Info($"Recursive mode is enabled => searching sub directories");

                    Directory.GetDirectories(path)
                    .ToList()
                    .ForEach(s => SearchFiles(s, filters, true, searchHidden, order));
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                LOGGER.Error($"Access to directory was denied", ex);
            }
            catch (ThreadAbortException ex)
            {
                LOGGER.Error($"Search thread was aborted", ex);
            }
            finally
            {
                LOGGER.Info($"Search for files in directory '{path}' has been finished");

                runningCount--;

                if (runningCount == 0)
                {
                    LOGGER.Info($"Searcher finished search");

                    State = RunningState.NotRunning;
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Create the command object that will be used to act on the repository.
        /// </summary>
        /// <returns>The command object that will be used to act on the
        ///     repository.</returns>
        /// <exception cref="Exception">TODO: Make a more specific exception</exception>
        /// <exception cref="NotImplementedException">If the command argument
        ///     is not implemented currently.  TODO: Implement the argument.</exception>
        public override ICommand CreateCommand()
        {
            ICSharpCode.SharpCvsLib.Commands.CommitCommand2 commitCommand;
            try {
                this.ParseOptions(this.unparsedOptions);
                string cvsFolder = Path.Combine(Environment.CurrentDirectory, "CVS");
                // set properties before creation of CommitCommand2
                // Open the Repository file in the CVS directory
                Manager    manager    = new Manager(cvsFolder);
                Repository repository = null;
                Root       root       = null;
                try {
                    repository = manager.FetchRepository(cvsFolder);
                } catch (CvsFileNotFoundException e) {
                    ConsoleMain.ExitProgram("Not a valid cvs repository.", e);
                }
                try {
                    root = manager.FetchRoot(cvsFolder);
                    if (null == this.cvsRoot)
                    {
                        this.cvsRoot = new CvsRoot(root.FileContents);
                    }
                } catch (CvsFileNotFoundException e) {
                    ConsoleMain.ExitProgram("Not a valid cvs repository.", e);
                }
                // If this fails error out and the user
                //    is not in a CVS repository directory tree.
                CurrentWorkingDirectory = new WorkingDirectory(this.cvsRoot,
                                                               cvsFolder, repository.FileContents);
                if (revision != null)
                {
                    this.CurrentWorkingDirectory.Revision = revision;
                }

                ArrayList files = new ArrayList();
                if (fileNames == null || fileNames == string.Empty)
                {
                    this.GetFilesRecursive((new DirectoryInfo(cvsFolder)).Parent, files);
                }
                else
                {
                    DirectoryInfo cvsFolderInfo = new DirectoryInfo(cvsFolder);
                    files = new ArrayList(cvsFolderInfo.GetFiles(fileNames));
                }

                CurrentWorkingDirectory.Folders = GetFoldersToCommit(files);
                // Create new CommitCommand2 object
                commitCommand = new ICSharpCode.SharpCvsLib.Commands.CommitCommand2(
                    this.CurrentWorkingDirectory);

                // set public properties on the commit command
                if (message != null)
                {
                    commitCommand.LogMessage = message;
                }

                return(commitCommand);
            } catch (CvsFileNotFoundException e) {
                ConsoleMain.ExitProgram(string.Format("No CVS folder found in path {0}",
                                                      Environment.CurrentDirectory), e);
                return(null);
            } catch (Exception e) {
                LOGGER.Error(e);
                throw e;
            }
        }