Exemplo n.º 1
0
        private async Task <string> ObtainLatestRadiometersParameters()
        {
            string retStr = "";

            if (Directory.Exists(RadiometersDataPath))
            {
                List <FileInfo> lCSVdataFilesInfoList =
                    ((new DirectoryInfo(RadiometersDataPath)).GetFiles("*.csv", SearchOption.AllDirectories)).ToList();
                lCSVdataFilesInfoList.Sort((finfo1, finfo2) => finfo1.CreationTimeUtc.CompareTo(finfo2.CreationTimeUtc));
                FileInfo lastCSVdataFileInfo            = lCSVdataFilesInfoList.Last();
                List <List <string> > Contents          = ServiceTools.ReadDataFromCSV(lastCSVdataFileInfo.FullName, 2, true, ";");
                List <string>         lastRdDataStrings = Contents.Last();

                retStr +=
                    "Radiometers:" + Environment.NewLine +
                    "Date,time: " + lastRdDataStrings[0] + Environment.NewLine +
                    "SW ave.(W/m2): " + lastRdDataStrings[7] + Environment.NewLine +
                    "LW downward ave.[W/m2]: " + lastRdDataStrings[15] + Environment.NewLine + Environment.NewLine;
            }
            else
            {
                retStr = "";
            }

            return(retStr);
        }
Exemplo n.º 2
0
        private void btnFilterSnapshotsBySunElevation_Click(object sender, EventArgs e)
        {
            theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                 "=========== Processing started on " + DateTime.Now.ToString("s") + " ===========");

            if (bgwSnapshotsFilteringWithSunElevation == null)
            {
                bgwSnapshotsFilteringWithSunElevation = new BackgroundWorker();
                bgwSnapshotsFilteringWithSunElevation.WorkerSupportsCancellation = true;
                bgwSnapshotsFilteringWithSunElevation.WorkerReportsProgress      = true;
                bgwSnapshotsFilteringWithSunElevation.DoWork          += BgwSnapshotsFilteringWithSunElevation_DoWork;
                bgwSnapshotsFilteringWithSunElevation.ProgressChanged += BgwSnapshotsFilteringWithSunElevation_ProgressChanged;

                object[] args = new object[] { CopyImagesFrom_Path, ConcurrentDataXMLfilesPath, CopyImagesAndDataTo_Path };
                bgwSnapshotsFilteringWithSunElevation.RunWorkerAsync(args);
                ThreadSafeOperations.ToggleButtonState(btnFilterSnapshotsBySunElevation, true, "CANCEL", true);
            }
            else
            {
                if (bgwSnapshotsFilteringWithSunElevation.IsBusy)
                {
                    bgwSnapshotsFilteringWithSunElevation.CancelAsync();
                }
                else
                {
                    object[] args = new object[] { CopyImagesFrom_Path, ConcurrentDataXMLfilesPath, CopyImagesAndDataTo_Path };

                    bgwSnapshotsFilteringWithSunElevation.RunWorkerAsync(args);
                    ThreadSafeOperations.ToggleButtonState(btnFilterSnapshotsBySunElevation, true, "CANCEL", true);
                }
            }
        }
        public void SaveClusteringData(string filenameTemplate)
        {
            FileInfo fInfo = new FileInfo(filenameTemplate);
            string   dir   = fInfo.DirectoryName;

            if (!ServiceTools.CheckIfDirectoryExists(dir))
            {
                return;
            }
            if (fInfo.Exists)
            {
                // не трогаем уже существующий файл
                return;
            }
            if (foundClassesContours.Count == 0)
            {
                return;
            }

            Rectangle  gridRect     = new Rectangle(0, 0, dmDensityMesh.ColumnCount, dmDensityMesh.RowCount);
            RectangleF realDataRect = new RectangleF((float)minXval, (float)minYval, (float)(maxXval - minXval),
                                                     (float)(maxYval - minYval));

            foreach (Contour <Point> foundClassContour in foundClassesContours)
            {
                ClusteringData currClusteringData = new ClusteringData(foundClassContour, gridRect, realDataRect);
                string         currClassFName     = filenameTemplate +
                                                    "-X" + currClusteringData.ptdClusterMassCenter.X.ToString("e").Replace(",", "_") +
                                                    "-Y" + currClusteringData.ptdClusterMassCenter.Y.ToString("e").Replace(",", "_") + ".xml";
                ServiceTools.WriteObjectToXML(currClusteringData, currClassFName);
            }
        }
Exemplo n.º 4
0
        private void ExternalGraphImageFormResized(object sender, EventArgs e)
        {
            BackgroundWorker    bgwGenerateGraphImage = new BackgroundWorker();
            SimpleShowImageForm f1 = sender as SimpleShowImageForm;

            bgwGenerateGraphImage.DoWork += (sndr, args) =>
            {
                ThreadSafeOperations.SetLoadingCircleState(wcUpdatimgGraph, true, true, wcUpdatimgGraph.Color);

                Image <Bgr, byte> img = FillGraphImage(f1.pb1.Size);
                args.Result = new object[] { img };
            };

            bgwGenerateGraphImage.RunWorkerCompleted += (sndr, args) =>
            {
                Image <Bgr, byte> resImg = (args.Result as object[])[0] as Image <Bgr, byte>;

                ServiceTools.ExecMethodInSeparateThread(this, delegate()
                {
                    f1.UpdateBitmap(resImg.Bitmap);
                });

                ThreadSafeOperations.SetLoadingCircleState(wcUpdatimgGraph, false, false, wcUpdatimgGraph.Color);
            };

            bgwGenerateGraphImage.RunWorkerAsync();
        }
        private string ReadLastConcurrentInfo()
        {
            DirectoryInfo   dir           = new DirectoryInfo(DataStoreDirectory);
            List <FileInfo> lXMLFilesInfo =
                dir.GetFiles(ConventionalTransitions.ImageConcurrentDataFilesNamesPattern(), SearchOption.AllDirectories)
                .ToList();

            lXMLFilesInfo.Sort((finfo1, finfo2) => finfo1.CreationTimeUtc.CompareTo(finfo2.CreationTimeUtc));

            Dictionary <string, object> dictReadXMLfileData =
                ServiceTools.ReadDictionaryFromXML(lXMLFilesInfo.Last().FullName);

            DateTime utcNow = DateTime.UtcNow;
            DateTime concurrentDataDateTime = DateTime.Parse(dictReadXMLfileData["DateTime"] as string);

            concurrentDataDateTime = concurrentDataDateTime.ToUniversalTime();

            string strDataToReport = "Current server date/time UTC: " + utcNow.ToString("dd.MM.yyyy HH:mm:ss") +
                                     Environment.NewLine;

            strDataToReport += "Concurrent data date/time UTC: " +
                               concurrentDataDateTime.ToString("dd.MM.yyyy HH:mm:ss") +
                               Environment.NewLine;
            strDataToReport += "time elapsed since last shot: " +
                               Math.Round((utcNow - concurrentDataDateTime).TotalSeconds) + "s" + Environment.NewLine;


            GPSdata gps = new GPSdata((string)dictReadXMLfileData["GPSdata"], GPSdatasources.CloudCamArduinoGPS,
                                      concurrentDataDateTime);

            strDataToReport += "GPS: " + gps.HRString(2) + Environment.NewLine;
            SPA spaCalcObject        = null;
            AzimuthZenithAngle angle = gps.SunZenithAzimuth(out spaCalcObject);


            DateTime  dtSunriseUTC  = utcNow;
            TimeOfDay todSunriseUTC = new TimeOfDay(spaCalcObject.spa.sunrise);

            dtSunriseUTC = new DateTime(dtSunriseUTC.Year, dtSunriseUTC.Month, dtSunriseUTC.Day, todSunriseUTC.hour,
                                        todSunriseUTC.minute, todSunriseUTC.second, DateTimeKind.Utc);


            // TimeZoneInfo mowTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time");
            TimeZoneInfo mowTimeZone  = TimeZoneInfo.Local;
            DateTime     dtSunriseMOW = TimeZoneInfo.ConvertTimeFromUtc(dtSunriseUTC, mowTimeZone);

            strDataToReport += "Sunrise Moscow time: " + (dtSunriseMOW.TimeOfDay.ToString()) + Environment.NewLine;

            DateTime  dtSunsetUTC  = utcNow;
            TimeOfDay todSunsetUTC = new TimeOfDay(spaCalcObject.spa.sunset);

            dtSunsetUTC = new DateTime(dtSunsetUTC.Year, dtSunsetUTC.Month, dtSunsetUTC.Day, todSunsetUTC.hour,
                                       todSunsetUTC.minute, todSunsetUTC.second, DateTimeKind.Utc);
            DateTime dtSunsetMOW = TimeZoneInfo.ConvertTimeFromUtc(dtSunsetUTC, mowTimeZone);

            strDataToReport += "Sunset Moscow time: " + (dtSunsetMOW.TimeOfDay.ToString()) + Environment.NewLine;

            return(strDataToReport);
        }
 public static IServiceCollection AddDependencyResolver(this IServiceCollection services, ICoreModule[] modules)
 {
     foreach (var module in modules)
     {
         module.Load(services);
     }
     return(ServiceTools.Create(services));
 }
        private void btnOpenAsImage_Click(object sender, EventArgs e)
        {
            // repaint
            RaisePaintEvent(null, null);
            Image <Bgr, byte> currShowingImage = currImage.Copy();

            ServiceTools.ShowPicture(currShowingImage, "");
        }
Exemplo n.º 8
0
        public override void Add(Action <string> output = null, Action <string> error = null)
        {
            Database userDatabase = ServiceTools.GetUserDatabase();
            string   userName     = GetArgument("name", "Please enter the name for the new user");
            string   emailAddress = GetArgument("email", "Please enter the new user's email address");

            User user = User.Create(userName, emailAddress, ServiceTools.ConfirmPasswordPrompt().Sha1());

            output($"*** user created ***\r\n{user.ToYaml()}");
        }
 private void ReadObservationsReportCSVfile()
 {
     if (File.Exists(strObservationsReportCSVfile))
     {
         List <List <string> > ObservationsReportCSVfileContents = ServiceTools.ReadDataFromCSV(strObservationsReportCSVfile, 1, true,
                                                                                                ";", "\n");
         lMissionObservedData =
             ObservationsReportCSVfileContents.ConvertAll(strList => new MissionsObservedData(strList));
     }
 }
        private void BotOnReceiveError(object sender, ReceiveErrorEventArgs e)
        {
            Debugger.Break();
            ApiRequestException ex = e.ApiRequestException;

            Console.WriteLine(ex.Message);
            ServiceTools.logToTextFile(errorFilename,
                                       "got API exception: " + ex.Message + Environment.NewLine + "Error code: " + ex.ErrorCode +
                                       Environment.NewLine + ex.StackTrace, true, true);
        }
Exemplo n.º 11
0
        //Builder
        public MonitorThread(Monitor monitor, bool running)
        {
            this.monitor = monitor;
            this.suspensionLvl = 0;
            this.serviceMgr = new ServiceTools();
            this.suspendMtx = new Mutex();

            if (!running)
                SuspendThread();
        }
        public void Start(string[] args)
        {
            readDefaultProperties();

            List <string> argsList = new List <string>(args);

            if (argsList.Any(str => str.Contains("--convert-existing-stats=")))
            {
                string foundArg = argsList.Find(str => str.Substring(0, 25) == "--convert-existing-stats=");
                FilesToProcessMask = foundArg.Replace("--convert-existing-stats=", "");
                Console.WriteLine("files mask to process: \"" + FilesToProcessMask + "\"");
            }

            if (argsList.Find(str => str == "--recursive") != null)
            {
                cbSearchImagesTopDirectoryOnly = false;
            }


            if (argsList.Find(str => str.Substring(0, 38) == "--filter-default-CenterX-double-value=") != null)
            {
                string foundArg = argsList.Find(str => str.Substring(0, 38) == "--filter-default-CenterX-double-value=");
                string strValue = foundArg.Replace("--filter-default-CenterX-double-value=", "");
                filterDefaultDoubleValueCenterX = Convert.ToDouble(strValue.Replace(".", ","));
            }


            if (argsList.Find(str => str.Substring(0, 38) == "--filter-default-CenterY-double-value=") != null)
            {
                string foundArg = argsList.Find(str => str.Substring(0, 38) == "--filter-default-CenterY-double-value=");
                string strValue = foundArg.Replace("--filter-default-CenterY-double-value=", "");
                filterDefaultDoubleValueCenterY = Convert.ToDouble(strValue.Replace(".", ","));
            }


            if (argsList.Find(str => str.Substring(0, 37) == "--filter-default-Radius-double-value=") != null)
            {
                string foundArg = argsList.Find(str => str.Substring(0, 37) == "--filter-default-Radius-double-value=");
                string strValue = foundArg.Replace("--filter-default-Radius-double-value=", "");
                filterDefaultDoubleValueRadius = Convert.ToDouble(strValue.Replace(".", ","));
            }



            ServiceTools.logToTextFile(outputDataFile,
                                       "processing data files using pattern: " + FilesToProcessMask + Environment.NewLine, true);

            Console.WriteLine("getting files list");
            EnumerateFilesToProcess();

            foreach (ImagesConvertingData enumObj in lStatsConversion)
            {
                CurrFileProcessing(enumObj);
            }
        }
        public override string EvaluateTemplate(string templateName, string templateExpression, object templatingContext)
        {
            switch (templateName)
            {
            case "ipaddress":
                return(ServiceTools.GetClientIpAddress());

            default:
                return(base.EvaluateTemplate(templateName, templateExpression, templatingContext));
            }
        }
Exemplo n.º 14
0
        public override void List(Action <string> output = null, Action <string> error = null)
        {
            Database       userDatabase = ServiceTools.GetUserDatabase();
            RoleCollection roles        = Role.LoadAll(userDatabase);
            int            num          = 1;

            foreach (Role role in roles)
            {
                output($"{num}. {role.Name}\r\n");
            }
        }
Exemplo n.º 15
0
        public override void List(Action <string> output = null, Action <string> error = null)
        {
            Database       userDatabase = ServiceTools.GetUserDatabase();
            UserCollection users        = User.LoadAll(userDatabase);
            int            num          = 1;

            foreach (User user in users)
            {
                output($"{num}. ({user.Email}) {user.UserName}");
                output($"\tRoles: {string.Join(",", user.Roles.Select(r => r.Name).ToArray())}");
            }
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            Dictionary <string, object> dictSettings = new Dictionary <string, object>();

            foreach (Pair <string, object> item in (DictionaryBindingList <string, object>)propertyGrid.DataSource)
            {
                dictSettings.Add(item.Key, item.Value);
            }

            //string fname = Directory.GetCurrentDirectory() + "\\settings\\SkyImagesAnalyzerSettings.xml";
            ServiceTools.WriteDictionaryToXml(dictSettings, fNamePropertiesXMLfile, false);

            this.Close();
        }
Exemplo n.º 17
0
        public override void Show(Action <string> output = null, Action <string> error = null)
        {
            Database userDatabase = ServiceTools.GetUserDatabase();
            string   userName     = GetArgument("name", "Please enter the user name to show.");
            User     user         = User.FirstOneWhere(n => n.UserName == userName);

            if (user == null)
            {
                error($"User ({userName}) was not found");
                Exit(1);
            }

            output(user.ToYaml());
        }
Exemplo n.º 18
0
        private void readDefaultProperties()
        {
            defaultProperties = new Dictionary <string, object>();
            string CurDir = Directory.GetCurrentDirectory();
            string defaultPropertiesXMLfileName = CurDir + "\\settings\\GPSdataCorrectorSettings.xml";

            if (!File.Exists(defaultPropertiesXMLfileName))
            {
                return;
            }
            defaultProperties = ServiceTools.ReadDictionaryFromXML(defaultPropertiesXMLfileName);


            rtbPath.Text = (string)defaultProperties["InputDataFilesDirectory"];
            rtbVesselNavDataDirectoryPath.Text = (string)defaultProperties["VesselMeteoNavDataPath"];
        }
Exemplo n.º 19
0
        /// <summary>
        /// Adds a path to the bundle with the specified order.
        /// </summary>
        /// <param name="path">The path to add to the bundle.</param>
        /// <param name="order">The specified order.</param>
        /// <param name="recursive">When adding a folder, tells whether to include contents of subfolders</param>
        public void AddPath(string path, int order = 0, bool recursive = true)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            if (_pathsWithOrders.Any(x => x.Item1 == path))
            {
                return;
            }

            if (IsClosed)
            {
                throw new Exception("You can't add more files to the bundle when it's closed.");
            }

            // Take care of folders
            if (ServiceTools.RecurseFilesInVirtualPath(path, recursive, p => AddPath(p, order, recursive)))
            {
                return;
            }

            // Take care of files
            var  item             = Tuple.Create(path, order);
            bool foundHigherOrder = false;
            int  index            = -1;

            foreach (var pathWithOrder in _pathsWithOrders)
            {
                index++;
                if (pathWithOrder.Item2 > order)
                {
                    foundHigherOrder = true;
                    break;
                }
            }

            if (foundHigherOrder)
            {
                _pathsWithOrders.Insert(index, item);
            }
            else
            {
                _pathsWithOrders.Add(item);
            }
        }
Exemplo n.º 20
0
        private async Task <string> ObtainLastImageCC()
        {
            string retStr = "";

            if (!Directory.Exists(ConcurrentDataXMLfilesBasePath))
            {
                throw new DirectoryNotFoundException("unable to locate directory: " + ConcurrentDataXMLfilesBasePath);
            }

            DirectoryInfo   dir           = new DirectoryInfo(ConcurrentDataXMLfilesBasePath);
            List <FileInfo> lXMLFilesInfo =
                dir.GetFiles(ConventionalTransitions.ImageProcessedAndPredictedDataFileNamesPattern(),
                             SearchOption.AllDirectories).ToList();

            if (lXMLFilesInfo.Count == 0)
            {
                return("No snapshots has been analyzed yet. Please wait for a couple of minutes.");
            }

            lXMLFilesInfo.Sort((finfo1, finfo2) => finfo1.CreationTimeUtc.CompareTo(finfo2.CreationTimeUtc));

            SkyImagesProcessedAndPredictedData data = null;

            try
            {
                data =
                    (SkyImagesProcessedAndPredictedData)
                    ServiceTools.ReadObjectFromXML(lXMLFilesInfo.Last().FullName,
                                                   typeof(SkyImagesProcessedAndPredictedData));
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (data != null)
            {
                retStr += "Please note that this finction is still in BETA version!" + Environment.NewLine +
                          "date of snapshot analyzed (UTC): " + data.imageShootingDateTimeUTC.ToString("u") +
                          Environment.NewLine +
                          "Sun disk condition: " + data.PredictedSDC.ToString() + Environment.NewLine +
                          "Total cloud cover: " + data.PredictedCC.CloudCoverTotal + " (of 8)";
            }


            return(retStr);
        }
Exemplo n.º 21
0
        private void btnDoWork_Click(object sender, EventArgs e)
        {
            theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                 "=========== Processing started on " + DateTime.Now.ToString("s") + " ===========");

            if (bgwCopier.IsBusy)
            {
                bgwCopier.CancelAsync();
            }
            else
            {
                object[] args = new object[] { CopyImagesFrom_Path, rtbConcurrentDataDir.Text, rtbToPath.Text, rtbGrIxYRGBstatsDir.Text };

                bgwCopier.RunWorkerAsync(args);
                ThreadSafeOperations.ToggleButtonState(btnDoWork, true, "CANCEL", true);
            }
        }
Exemplo n.º 22
0
        private void bgwCopier_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     "ERROR has been caught: " + Environment.NewLine + e.Error.Message + Environment.NewLine);
                //ThreadSafeOperations.SetTextTB(tbLog, "ERROR has been caught: " + Environment.NewLine, true);
                //ThreadSafeOperations.SetTextTB(tbLog, e.Error.Message + Environment.NewLine, true);
            }


            //ThreadSafeOperations.SetTextTB(tbLog, "#007" + Environment.NewLine, true);
            ThreadSafeOperations.UpdateProgressBar(prbUniversalProgress, 0);
            theLogWindow = ServiceTools.LogAText(theLogWindow, "Finished work" + Environment.NewLine);
            //ThreadSafeOperations.SetTextTB(tbLog, "Finished work" + Environment.NewLine, true);
            ThreadSafeOperations.ToggleButtonState(btnDoWork, true, "SELECT", false);
        }
Exemplo n.º 23
0
        //Builder
        public AddMonitorForm(MonitorMgr caller)
        {
            InitializeComponent();

            this.comboBox_proc_cpuUsageRelative.SelectedIndex = 0;
            this.comboBox_proc_mustRun.SelectedIndex = 0;
            this.comboBox_serv_critic.SelectedIndex = 0;
            this.comboBox_serv_startMode.SelectedIndex = 0;
            this.comboBox_serv_state.SelectedIndex = 0;
            this.comboBox_serv_status.SelectedIndex = 0;

            serviceMgr = new ServiceTools();
            showGroupBoxMode(Mode.service);
            this.caller = caller;
            connected = false;
            mode = null;
        }
Exemplo n.º 24
0
        void bgwGraphsPresenterInSeparateWindow_DoWork(object sender, DoWorkEventArgs e)
        {
            ThreadSafeOperations.SetLoadingCircleState(wcUpdatimgGraph, true, true, wcUpdatimgGraph.Color);

            Image <Bgr, byte> img = FillGraphImage(new Size(1280, 1024));

            if (img != null)
            {
                ServiceTools.ExecMethodInSeparateThread(this, delegate()
                {
                    SimpleShowImageForm f1 = new SimpleShowImageForm(img.Bitmap);
                    f1.FormResizing       += ExternalGraphImageFormResized;
                    f1.Show();
                });
            }

            ThreadSafeOperations.SetLoadingCircleState(wcUpdatimgGraph, false, false, wcUpdatimgGraph.Color);
        }
        private void readDefaultProperties()
        {
            defaultProperties            = new Dictionary <string, object>();
            defaultPropertiesXMLfileName = Directory.GetCurrentDirectory() +
                                           Path.DirectorySeparatorChar + "settings" + Path.DirectorySeparatorChar +
                                           Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location) +
                                           "-Settings.xml";
            if (!File.Exists(defaultPropertiesXMLfileName))
            {
                return;
            }
            defaultProperties = ServiceTools.ReadDictionaryFromXML(defaultPropertiesXMLfileName);

            bool bDefaultPropertiesHasBeenUpdated = false;

            string CurDir = Directory.GetCurrentDirectory();

            currPath2Process = "";
            if (defaultProperties.ContainsKey("ImagesBasePath"))
            {
                currPath2Process = (string)defaultProperties["ImagesBasePath"];
            }
            else
            {
                currPath2Process = CurDir;
            }


            if (defaultProperties.ContainsKey("OutputDirectory"))
            {
                strOutputDirectory = ((string)defaultProperties["OutputDirectory"]);
            }
            else
            {
                strOutputDirectory = "";
            }



            if (bDefaultPropertiesHasBeenUpdated)
            {
                saveDefaultProperties();
            }
        }
Exemplo n.º 26
0
        public void Start(string[] args)
        {
            readDefaultProperties();

            List <string> argsList = new List <string>(args);

            if (argsList.Find(str => str.Substring(0, 7) == "--mask=") != null)
            {
                string foundArg = argsList.Find(str => str.Substring(0, 7) == "--mask=");
                FilesToProcessMask = foundArg.Substring(7);
                Console.WriteLine("files mask to process: \"" + FilesToProcessMask + "\"");
            }

            if (argsList.Find(str => str == "--recursive") != null)
            {
                cbSearchImagesTopDirectoryOnly = false;
            }


            outputDataFile = strOutputDirectory + outputDataFile;
            ServiceTools.logToTextFile(outputDataFile,
                                       "processing images using filename mask: " + FilesToProcessMask + Environment.NewLine, true);


            Console.WriteLine("getting files list");


            EnumerateFilesToProcess();


            ServiceTools.logToTextFile(outputDataFile,
                                       "filename;centerX;centerY;radius" + Environment.NewLine, true);

            var options = new ParallelOptions();

            options.MaxDegreeOfParallelism = maxConcurrentBackgroundWorkers;

            Parallel.ForEach(lStatsCalculation, options, item => { CurrImageProcessing(item); });
        }
Exemplo n.º 27
0
        /// <summary>
        /// Adds a script reference to ScriptManager that will be rendered to the html.
        /// </summary>
        /// <param name="scriptPath">Path of the script. Can be a skin-relative path.</param>
        /// <param name="control">Source control, optional. It will be used to find the current CacheablePortlet and the script reference to it too.</param>
        public static void AddScript(string scriptPath, Control control = null)
        {
            // Take care of folders
            if (ServiceTools.RecurseFilesInVirtualPath(SkinManager.Resolve(scriptPath), true, p => AddScript(p, control)))
            {
                return;
            }

            var currScriptManager = GetScriptManager();

            if (currScriptManager == null)
            {
                throw new Exception("The current page does not contain a script manager.");
            }

            if (currScriptManager is SNScriptManager)
            {
                // use SNScriptManager's SmartLoader if present
                var smartLoader = ((SNScriptManager)currScriptManager).SmartLoader;
                smartLoader.AddScript(scriptPath);
            }
            else
            {
                // fallback to ASP.NET ScriptManager
                var scriptReference = new ScriptReference {
                    Path = scriptPath
                };
                currScriptManager.Scripts.Add(scriptReference);
            }

            // Add script reference to cacheable portlet if possible, to
            // be able to add references even if the portlet html is cached.
            var cb = GetCacheablePortlet(control);

            if (cb != null)
            {
                cb.AddScript(scriptPath);
            }
        }
Exemplo n.º 28
0
        private void OpenFile(string filelistmember)
        {
            dataFileName = filelistmember;

            try
            {
                dmDataToShow = NetCDFoperations.ReadDenseMatrixFromFile(dataFileName);
            }
            catch (Exception ex)
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     "coundn`t load data from file:" + Environment.NewLine + dataFileName);
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     "exception description:" + Environment.NewLine + ex.Message);
                return;
            }

            if (dmDataToShow != null)
            {
                RepresentData();
            }
        }
Exemplo n.º 29
0
        //private bool testAnIpAddress(IPAddress testingIPaddr)
        //{
        //    bool retVal = false;
        //    Ping ping;
        //    string retStr = "areyouarduino";
        //    byte[] ret = System.Text.Encoding.ASCII.GetBytes(retStr);
        //    string returnData = "";
        //    Socket Skt = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        //    Skt.EnableBroadcast = false;
        //    Skt.ReceiveTimeout = 10;
        //    Skt.SendTimeout = 10;
        //    //string testingIP = "192.168.192." + i.ToString();//!!!!!!!!!!!!!!!!!!!!!! определить подсеть по текущему IP и маске
        //    //testingIPaddr = IPAddress.Parse(testingIP);
        //
        //    ping = new Ping();
        //    PingReply repl = ping.Send(testingIPaddr, 3, new byte[] { 1 }, new PingOptions(1, true));
        //
        //    if ((repl.Status == IPStatus.TtlExpired) || (repl.Status == IPStatus.TimedOut) || (repl.Status == IPStatus.TimeExceeded))
        //    {
        //        returnData = "ping timeout or not reachable";
        //        retVal = false;
        //    }
        //    else
        //    {
        //        IPEndPoint test = new IPEndPoint(testingIPaddr, 5555);
        //        int sent = Skt.SendTo(ret, test);
        //        // Blocks until a message returns on this socket from a remote host.
        //        Byte[] receiveBytes = new byte[128];
        //        IPEndPoint sender_ = new IPEndPoint(IPAddress.Any, 0);
        //        EndPoint senderRemote = (EndPoint)sender_;
        //
        //        try
        //        {
        //            Skt.ReceiveFrom(receiveBytes, ref senderRemote);
        //            returnData = Encoding.UTF8.GetString(receiveBytes).Trim().Replace("\0", string.Empty);
        //        }
        //        catch (Exception ex)
        //        {
        //            returnData = ex.Message;
        //            //throw;
        //        }
        //    }
        //
        //    SetTextTB(textBox1, "tested ip " + testingIPaddr.ToString() + ": " + returnData.ToString() + Environment.NewLine, true);
        //    Skt.Close();
        //    if (returnData.ToString() == "YES") retVal = true; else retVal = false;
        //
        //    return retVal;
        //}



        //private void arduinoBoardSearchingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        //{
        //    //SetTextTB(textBox1, "Данные датчиков собраны " + e.ProgressPercentage + " раз" + Environment.NewLine, true);
        //    UpdateProgressBar(progressBar1, e.ProgressPercentage);
        //}



        private void Form1_Load(object sender, EventArgs e)
        {
            string generalSettingsFilename = Directory.GetCurrentDirectory() + "\\settings\\ArduinoUDPconversationAppGeneralSettings2G.xml";

            if (!File.Exists(generalSettingsFilename))
            {
                ip2ListenDevID1 = Settings.Default.ArduinoBoardDefaultIP;
                port2converse   = Settings.Default.ArduinoBoardDefaultUDPport;
                ThreadSafeOperations.SetTextTB(tbDev1IPstr, ip2ListenDevID1, false);
            }
            else
            {
                Dictionary <string, object> generalSettings = ServiceTools.ReadDictionaryFromXML(generalSettingsFilename);

                ip2ListenDevID1 = generalSettings["ArduinoBoardID1DefaultIP"] as string;
                ip2ListenDevID2 = generalSettings["ArduinoBoardID2DefaultIP"] as string;
                port2converse   = Convert.ToInt32(generalSettings["ArduinoBoardDefaultUDPport"]);
                portBcstRecvng  = Convert.ToInt32(generalSettings["UDPBroadcastDefaultListeningPort"]);

                ThreadSafeOperations.SetTextTB(tbDev1IPstr, ip2ListenDevID1, false);
                ThreadSafeOperations.SetTextTB(tbDev2IPstr, ip2ListenDevID2, false);
            }
        }
Exemplo n.º 30
0
        private void swapResponseLog(object sender)
        {
            string filename1;
            string strtowrite;

            byte[] info2write;
            int    curDevID = 1;

            if (sender == btnSwapResponseLog1)
            {
                curDevID = 1;
            }
            else if (sender == btnSwapResponseLog2)
            {
                curDevID = 2;
            }

            filename1 = Directory.GetCurrentDirectory() + "\\ResponseLog-" + "devID" + curDevID + "-" +
                        DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour +
                        "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + ".log";
            ServiceTools.logToTextFile(filename1, tbResponseLog1.Text, true);
            ThreadSafeOperations.SetTextTB(tbResponseLog1, "", false);
        }
Exemplo n.º 31
0
        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                Array  filesArray = (Array)e.Data.GetData(DataFormats.FileDrop);
                string filename   = (string)filesArray.GetValue(0);
                if (Path.GetExtension(filename) != ".nc")
                {
                    return;
                }

                if (filesArray != null)
                {
                    this.BeginInvoke(m_DelegateOpenFile, new Object[] { filename });
                    this.Activate();
                }
            }
            catch (Exception exc1)
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     "Ошибка при обработке Drag&Drop: " + Environment.NewLine + exc1.Message, true);
            }
        }
Exemplo n.º 32
0
        private void EnumerateFilesToProcess()
        {
            string        directory = Path.GetDirectoryName(FilesToProcessMask);
            string        filemask  = FilesToProcessMask.Replace(directory + Path.DirectorySeparatorChar, "");
            List <string> filesList =
                new List <string>(Directory.EnumerateFiles(directory, filemask,
                                                           cbSearchImagesTopDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories));



            if (!filesList.Any())
            {
                Console.WriteLine("There is no images that sutisfy specified settings. Processing will not be started.");
                return;
            }



            int intFinalIndex = filesList.Count;
            int idx           = 0;
            int currPerc      = 0;
            int prevPerc      = 0;

            foreach (string fName in filesList)
            {
                Console.Write("adding file to calculation queue:" + fName + "\r");
                idx++;

                AddImageToCalculationQueue(fName);
            }


            Console.WriteLine("finished enumerating files. Files to process: " + lStatsCalculation.Count);
            ServiceTools.logToTextFile(outputDataFile,
                                       "files count to process: " + lStatsCalculation.Count + Environment.NewLine, true);
        }