Ejemplo n.º 1
0
        public List <IPData> GetAllIPDatas()
        {
            List <IPData> pingInfoList = new List <IPData>();
            string        jsonFileName = System.IO.Path.Combine(Environment.CurrentDirectory, @"Mode\WarframeIP.json");

            using (System.IO.StreamReader file = System.IO.File.OpenText(jsonFileName))
            {
                using JsonTextReader reader = new JsonTextReader(file);
                JObject o = (JObject)JToken.ReadFrom(reader);
                var     w = o["warframe"];
                foreach (JObject e in w)
                {
                    IPData pingInfo = new IPData();
                    pingInfo.DomainName = e["domainname"].ToString();

                    var           l    = e["ipaddrs"];
                    List <string> list = new List <string>();
                    for (int i = 0; i < l.Count(); i++)
                    {
                        list.Add(l[i].ToString());
                    }
                    pingInfo.IPAddrs = list;
                    pingInfoList.Add(pingInfo);
                }
            }
            return(pingInfoList);
        }
Ejemplo n.º 2
0
        public static void Set(ref IPHeader header, IPData ipData, ushort count)
        {
            header = new IPHeader();

            ushort allLength = GetAllLength(count);

            header._IPHeader0_32._Version_HeaderLength = 0b0100_0101;


            header._IPHeader0_32._AllLegnth = Meth.AsBigEndian(allLength);

            header._IPHeader64_96._Protocol = (byte)ipData.Protocol;

            header._IPHeader64_96._TTL = 128;

            header._SourceAddress = ipData.SourceAddress;

            header._DesAddress = ipData.DesAddress;

            header._IPHeader32_64._16Flag = Meth.GetCount();

            header._IPHeader32_64._Frag = 0x40;


            header.CalculationHeaderChecksum();
        }
Ejemplo n.º 3
0
 public static IPResponse CreateIPResponse(IPData ipData, LocationData locationData)
 {
     return(new IPResponse()
     {
         Location = CreateLocation(ipData, locationData, true)
     });
 }
Ejemplo n.º 4
0
        private void fillForm(IPData ipdata)
        {
            label_IP.Content      = ipdata.IPAddress;
            label_Geo.Content     = ipdata.Country;
            label_Carrier.Content = ipdata.Carrier;
            label_Org.Content     = ipdata.Organisation;
            label_State.Content   = ipdata.State;
            label_Sld.Content     = ipdata.Sld;
            setFlagToForm(ipdata.CountryCode);

            Table table = new Table();

            table.RowGroups.Add(new TableRowGroup());
            table.RowGroups[0].Rows.Add(new TableRow());

            TableRow tabRow = table.RowGroups[0].Rows[0];

            tabRow.Cells.Add(new TableCell(new Paragraph(new Run("IP"))));
            tabRow.Cells.Add(new TableCell(new Paragraph(new Run(ipdata.IPAddress))));

            table.RowGroups[0].Rows.Add(new TableRow());
            tabRow = table.RowGroups[0].Rows[1];

            tabRow.Cells.Add(new TableCell(new Paragraph(new Run("IP2"))));
            tabRow.Cells.Add(new TableCell(new Paragraph(new Run(ipdata.IPAddress))));

            RichTextBox_History.Document.Blocks.Add(table);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            string GeoIPAPI   = "http://ip-api.com/json/";
            string WhoIsIPAPI = "http://whois.arin.net/rest/ip/";

            List <string> IPAddresList = FileParser.GetIPAddressList();
            List <IPData> ipDataList   = new List <IPData>();

            foreach (string ipAddress in IPAddresList)
            {
                string whoIsJson = WhoIsLookup.GET(WhoIsIPAPI + ipAddress);
                string geoJson   = IPGeoLookup.GET(GeoIPAPI + ipAddress);

                JObject o = JObject.Parse(whoIsJson);
                string  whoIsCustomerName = (string)o.SelectToken("net.customerRef.@name");
                string  whoIsOrganization = (string)o.SelectToken("net.orgRef.@name");

                IPData geoIPdata = JsonConvert.DeserializeObject <IPData>(geoJson);

                geoIPdata.WhoIsName         = whoIsCustomerName;
                geoIPdata.WhoIsOrganization = whoIsOrganization;

                ipDataList.Add(geoIPdata);
            }

            FileWriter.CreateOutputFile(ipDataList);
        }
Ejemplo n.º 6
0
        public List <IPData> getIPDNS(string hostname)
        {
            InfoBloxIPSearch.url url        = new InfoBloxIPSearch.url();
            string serverAddress            = url.server;
            string resource                 = url.resource + hostname;
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling     = NullValueHandling.Ignore
            };
            List <InfoBloxIPSearch.RootIPSearch> data = new List <InfoBloxIPSearch.RootIPSearch>();
            IRestResponse response = EstablishInfoBloxConnection(resource, serverAddress);

            data = JsonConvert.DeserializeObject <List <InfoBloxIPSearch.RootIPSearch> >(response.Content, settings);


            List <IPData> results = new List <IPData>();

            if (data != null)
            {
                foreach (var item in data)
                {
                    IPData ipdata = new IPData();
                    ipdata.names      = item.names.ToList();
                    ipdata.ip_address = item.ip_address;
                    ipdata.network    = item.network;
                    results.Add(ipdata);
                }
            }

            return(results);
        }
Ejemplo n.º 7
0
    List <IPData> StringToServerConnectInfos(string s)
    {
        List <IPData> serverInfos = new List <IPData>();

        string[] records = s.Split('\n');
        foreach (var c in records)
        {
            string[] ps = c.Split(':');
            if (ps.Length != 2)
            {
                continue;
            }

            string ip   = ps[0];
            string port = ps[1];

            if (!ipRegex.IsMatch(ip.Trim()))
            {
                continue;
            }

            IPData connectInfo = new IPData();
            connectInfo.ip   = ip.Trim();
            connectInfo.port = ushort.Parse(port);


            serverInfos.Add(connectInfo);
        }
        return(serverInfos);
    }
Ejemplo n.º 8
0
        /// <summary>
        /// コンバートしたリストを出力する
        /// </summary>
        /// <param name="filePath"></param>
        public void FileOutput(string filePath = "")
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = "convert.txt";
            }

            string output = "";

            IPData temp = new IPData();

            PropertyInfo[] proInfo = temp.GetType().GetProperties();

            foreach (PropertyInfo info in proInfo)
            {
                output += info.Name + ",";
            }
            output  = output.Remove(output.Length - 1, 1);
            output += "\n";

            foreach (IPData tmp in dataList)
            {
                output += string.Format("{0},{1},{2},{3},{4}\n", tmp.country, tmp.startIP, tmp.endIP, tmp.startIpNum, tmp.endIpNum);
            }

            using (StreamWriter sw = new StreamWriter("convert.txt", false, System.Text.Encoding.GetEncoding("shift_jis")))
            {
                sw.Write(output);
            }
        }
        public NetworkAdapterPropertiesView(ref IPData ipInfo)
        {
            InitializeComponent();

            var viewModel = this.DataContext as NetworkAdapterPropertiesViewModel;

            viewModel.IPInfo = ipInfo;
        }
        public void CreateIPData(int probeDataId, IPData data)
        {
            data.ProbeDataId = probeDataId;
            data.CreatedOn   = DateTime.UtcNow;

            _Context.IPData.Add(data);
            _Context.SaveChanges();
        }
Ejemplo n.º 11
0
 public void BindIPRecord(IPData connectInfo)
 {
     bindConnectInfo = connectInfo;
     if (bindConnectInfo != null)
     {
         ipDisplayField.text = bindConnectInfo.ip + ":" + bindConnectInfo.port.ToString();
     }
 }
Ejemplo n.º 12
0
 public void DeleteIPRecord(IPData s)
 {
     if (!inLocalEditingMode)
     {
         return;
     }
     localServerInfoEditingCache.Remove(s);
     dataDirty = true;
 }
Ejemplo n.º 13
0
 private static Location CreateLocation(IPData ipData, LocationData locationData, bool withCity)
 {
     return(new Location()
     {
         City = withCity ? Converter.ConvertToString(locationData.city) : null,
         RangeIp = string.Format("{0} - {1}", Converter.ConvertToIp(ipData.ip_from), Converter.ConvertToIp(ipData.ip_to)),
         Country = Converter.ConvertToString(locationData.country),
         Organization = Converter.ConvertToString(locationData.organization),
         Postal = Converter.ConvertToString(locationData.postal),
         Region = Converter.ConvertToString(locationData.region),
         Longitude = locationData.longitude,
         Latitude = locationData.latitude,
     });
 }
Ejemplo n.º 14
0
            public VisualIPData(IPData ipdata, string Clipdata_)
            {
                IPData _ipdata = ipdata.ShallowCopy();

                this.IPAddress    = _ipdata.IPAddress;
                this.City         = _ipdata.City;
                this.Country      = _ipdata.Country;
                this.Organisation = _ipdata.Organisation;
                this.Carrier      = _ipdata.Carrier;
                this.CountryCode  = _ipdata.CountryCode;
                this.State        = _ipdata.State;
                this.Sld          = _ipdata.Sld;

                this.Clipdata = Clipdata_;
            }
Ejemplo n.º 15
0
    public void AddRecordUI(IPData info)
    {
        if (info == null)
        {
            return;
        }

        var go = Instantiate(uiPrefab.gameObject);
        var ui = go.GetComponent <IPRecordItem>();

        ui.GetComponent <RectTransform>().SetParent(GetComponent <RectTransform>(), true);
        ui.transform.localScale = Vector3.one;
        ui.BindIPRecord(info);
        ipRecords.Add(ui);
    }
Ejemplo n.º 16
0
        /// <summary>
        /// Called when an image becomes available from camera.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImageAvailable(object sender, ICImagingControl.ImageAvailableEventArgs e)
        {
            ImageBuffer buff = cam.ImageBuffers[e.bufferIndex];

            double elapsedTime = -1.0;
            double time        = cam.ReferenceTimeCurrent;

            // get time elapsed
            if (lastTime > 0.0)
            {
                elapsedTime = time - lastTime;
            }
            lastTime = time;

            // lock the image buffer so that it is not overwritten while we are saving it.
            buff.Lock();
            bool isImageSet = true;

            imageNumber++;
            IPData data = new IPData(elapsedTime, exposure_s, false, imageNumber);

            try
            {
                data.SetRawDataFromImage(buff.Bitmap);
            }
            catch (Exception inner)
            {
                string          errMsg = "Camera.ImageAvailable : Unable to save image into raw data of IPData object.";
                CameraException ex     = new CameraException(errMsg, inner);
                log.Error(errMsg, ex);
                isImageSet = false;
            }
            buff.Unlock();


            lock (_camLock)
            {
                // only push the image if stored successfully
                if (isImageSet)
                {
                    for (int i = 0; i < subscribers.Count; i++)
                    {
                        subscribers[i].push(new QueueElement(cameraName, data));
                    }
                }
            }
        }
Ejemplo n.º 17
0
        private static void GetIPs()
        {
            try
            {
                // My address
                var host = Dns.GetHostEntry(Dns.GetHostName());

                // Get Local IP4 address
                var ip = new WebClient().DownloadString("https://ipv4.icanhazip.com/").Replace("\n", "");
                var externalServerIPAddress = System.Net.IPAddress.Parse(ip);

                Console.WriteLine("External IP: " + externalServerIPAddress.ToString());

                var thisIPAddress = host.AddressList.Where(m => m.AddressFamily == AddressFamily.InterNetwork).LastOrDefault();

                // Linux
                if (thisIPAddress == null)
                {
                    thisIPAddress = NetworkInterface.GetAllNetworkInterfaces().SelectMany(i => i.GetIPProperties().UnicastAddresses).Select(a => a.Address).Where(a => a.AddressFamily == AddressFamily.InterNetwork).LastOrDefault();
                    Console.WriteLine("Internal IP: " + thisIPAddress.ToString());
                }
                else
                {
                    var ipAddresses = host.AddressList.Where(m => m.AddressFamily == AddressFamily.InterNetwork).ToList();
                    foreach (var theIP in ipAddresses)
                    {
                        Console.WriteLine("Internal IP: " + theIP.ToString());
                    }
                }

                var data = new IPData()
                {
                    ExternalAddress = externalServerIPAddress.ToString(),
                    InternalAddress = thisIPAddress.ToString(),
                    Host            = host.HostName
                };

                _AssetDataService.CreateIPData(_MachineData.Id, data);
            }
            catch (Exception e)
            {
                _AssetDataService.CreateError(_MachineData.Id, "GetIPs", e);
            }
        }
Ejemplo n.º 18
0
        public IPData GetIPGeoLocation(string IP)
        {
            WebClient client = new WebClient();

            try
            {
                string response = client.DownloadString("http://ip-api.com/json/" + IP);
                IPData ipdata   = JsonConvert.DeserializeObject <IPData>(response);
                if (ipdata.status == "fail")
                {
                    throw new Exception("Invalid IP");
                }

                return(ipdata);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 19
0
    public IPData AppendIPRecord(string ip, ushort port)
    {
        if (!inLocalEditingMode)
        {
            return(null);
        }

        if (!CheckIPValidation(ip))
        {
            return(null);
        }

        IPData sci = new IPData();

        sci.ip   = ip;
        sci.port = port;
        localServerInfoEditingCache.Add(sci);
        dataDirty = true;
        return(sci);
    }
Ejemplo n.º 20
0
 /// <summary>
 /// Saves all contents of history buffer inside of saveLocation.
 /// </summary>
 /// <param name="saveLocation">Location to save history buffer to.</param>
 /// <param name="camHistory">IPData history to save to disk.</param>
 private void saveHistoryBuffer(string saveLocation, IPData[] camHistory)
 {
     for (int j = 0; j < DEFAULT_TEST_HISTORY_SIZE; j++)
     {
         IPData ipdata = camHistory[j];
         if (ipdata != null)
         {
             try
             {
                 SaveIPData(saveLocation, ref ipdata);
             }
             catch (Exception inner)
             {
                 string errMsg = "ImageHistoryBuffer : Error saving image data " + j.ToString("D2") + " in image history buffer.";
                 ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                 log.Error(errMsg, ex);
                 // do not throw this error, bc we still want to try to save the rest of data
             }
         }
     }
 }
Ejemplo n.º 21
0
        private void Process()
        {
            // get a local copy of metadata singleton
            MetaData metadata = MetaData.Instance;

            // location of folders in saving directory structure
            string rootLocation      = metadata.SaveLocation;
            string cam1TestLocation  = "";
            string cam2TestLocation  = "";
            string cam1DebugLocation = "";
            string cam2DebugLocation = "";

            // list to keep image data in
            IPData[] cam1History            = new IPData[DEFAULT_TEST_HISTORY_SIZE];
            IPData[] cam2History            = new IPData[DEFAULT_TEST_HISTORY_SIZE];
            int      cam1HistoryInsertIndex = 0;
            int      cam2HistoryInsertIndex = 0;

            // tracks consecutive cracks in data and a flag to confirm a crack
            int  cam1ConsecutiveCrackedSampleCount = 0;
            int  cam2ConsecutiveCrackedSampleCount = 0;
            bool crackConfirmed = false;

            // timers for throttling thread, and updating save requests
            Stopwatch _threadTimer          = new Stopwatch();
            Stopwatch _debugSaveUpdateTimer = new Stopwatch();
            Stopwatch _testSaveUpdateTimer  = new Stopwatch();

            // flags to reset when timers trigger indicating corresponding data needs to be updated
            bool updateCam1DebugData = true;
            bool updateCam2DebugData = true;
            bool updateCam1TestData  = true;
            bool updateCam2TestData  = true;

            // attempt to create root directory and unique identify folder
            try
            {
                // updates the rootLocation to include the unique identifier folder generated inside function call
                rootLocation = initRootDirectory(rootLocation);
            }
            catch (Exception inner)
            {
                string errMsg = "ImageHistoryBuffer.Process : Unable to create root directory and unique identifier folder.";
                ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                log.Error(errMsg, ex);

                // shutdown thread here
                ThreadErrorEventArgs er = new ThreadErrorEventArgs(errMsg, ex, true);
                ThreadErrorEventArgs.OnThreadError(this, ThreadError, er);
            }

            // attempt to create directory structure for test data
            try
            {
                initTestDirectory(rootLocation, ref cam1TestLocation, ref cam2TestLocation);
            }
            catch (Exception inner)
            {
                string errMsg = "ImageHistoryBuffer.Process : Unable to create directory structure for test data.";
                ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                log.Error(errMsg, ex);

                // shutdown thread here
                ThreadErrorEventArgs er = new ThreadErrorEventArgs(errMsg, ex, true);
                ThreadErrorEventArgs.OnThreadError(this, ThreadError, er);
            }

            // attempt to create directory structure for debug saving if enabled
            if (metadata.EnableDebugSaving)
            {
                try
                {
                    initDebugDirectory(rootLocation, ref cam1DebugLocation, ref cam2DebugLocation);
                }
                catch (Exception inner)
                {
                    string errMsg = "ImageHistoryBuffer.Process : Unable to create directory structure for debug saving.";
                    ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                    log.Error(errMsg, ex);

                    // shutdown thread here
                    ThreadErrorEventArgs er = new ThreadErrorEventArgs(errMsg, ex, true);
                    ThreadErrorEventArgs.OnThreadError(this, ThreadError, er);
                }
            }

            // start threading timers
            _threadTimer.Start();
            _debugSaveUpdateTimer.Start();
            _testSaveUpdateTimer.Start();

            while (isRunning)
            {
                // throttles the thread to prevent it from consuming 100% of processor it is running on
                int timeToSleep = threadThrottlePeriod - Convert.ToInt32(_threadTimer.ElapsedMilliseconds);
                if (timeToSleep > 0)
                {
                    Thread.Sleep(timeToSleep);
                }
                _threadTimer.Restart();

                // check if debug data needs to be updated
                if (_debugSaveUpdateTimer.ElapsedMilliseconds >= metadata.DebugSaveFrequency * 1000)
                {
                    updateCam1DebugData = true;
                    updateCam2DebugData = true;
                    _debugSaveUpdateTimer.Restart();
                }

                // check to see if test data needs to be updated
                if (_testSaveUpdateTimer.ElapsedMilliseconds >= 250)
                {
                    updateCam1TestData = true;
                    updateCam2TestData = true;
                    _testSaveUpdateTimer.Restart();
                }

                // pop everything off of savequeue
                List <QueueElement> imageElements = new List <QueueElement>();
                consumerQueue.popAll(ref imageElements);
                if (imageElements.Count > 0)
                {
                    for (int i = 0; i < imageElements.Count; i++)
                    {
                        //figure our where the iamge is coming from
                        IPData data = (IPData)imageElements[i].Data;
                        string type = imageElements[i].Type;
                        if (type.Contains("1"))
                        {
                            // see if image needs to be stored in recent history buffer 1
                            if (updateCam1TestData)
                            {
                                // requires a slot in buffer
                                cam1History[cam1HistoryInsertIndex] = data;
                                cam1HistoryInsertIndex = (cam1HistoryInsertIndex + 1) % DEFAULT_TEST_HISTORY_SIZE;
                                updateCam1TestData     = false;
                            }
                            if (metadata.EnableDebugSaving)
                            {
                                if (updateCam1DebugData)
                                {
                                    // need to save image to debug slot
                                    SaveIPData(cam1DebugLocation, ref data);
                                    updateCam1DebugData = false;
                                }
                            }
                            if (data.ContainsCrack)
                            {
                                cam1ConsecutiveCrackedSampleCount++;
                                if (cam1ConsecutiveCrackedSampleCount > CONSECUTIVE_CRACKS)
                                {
                                    crackConfirmed = true;
                                }
                            }
                            else
                            {
                                cam1ConsecutiveCrackedSampleCount = 0;
                                crackConfirmed = false;
                            }
                        }
                        else if (type.Contains("2"))
                        {
                            // see if image needs to be stored in recent history buffer 2
                            if (updateCam2TestData)
                            {
                                // requires a slot in buffer
                                cam2History[cam2HistoryInsertIndex] = data;
                                cam2HistoryInsertIndex = (cam2HistoryInsertIndex + 1) % DEFAULT_TEST_HISTORY_SIZE;
                                updateCam2TestData     = false;
                            }
                            if (metadata.EnableDebugSaving)
                            {
                                if (updateCam2DebugData)
                                {
                                    // need to save image to debug slot
                                    SaveIPData(cam2DebugLocation, ref data);
                                    updateCam2DebugData = false;
                                }
                            }
                            if (data.ContainsCrack)
                            {
                                cam2ConsecutiveCrackedSampleCount++;
                                if (cam2ConsecutiveCrackedSampleCount > CONSECUTIVE_CRACKS)
                                {
                                    crackConfirmed = true;
                                }
                            }
                            else
                            {
                                cam2ConsecutiveCrackedSampleCount = 0;
                                crackConfirmed = false;
                            }
                        }
                        else
                        {
                            // unknown data type
                            log.Info("ImageHistoryBuffer.Process : Received unknown data type.");
                        }
                        // check to see if we have confirmed a crack existing
                        if (crackConfirmed)
                        {
                            // trigger the USB Relay
                            USBRelayController usb_relay = USBRelayController.Instance;
                            if (usb_relay.IsOpen)
                            {
                                usb_relay.SetRelay0Status(true);
                                usb_relay.SetRelay1Status(true);
                            }

                            // save all images in history buffer
                            saveHistoryBuffer(cam1TestLocation, cam1History);
                            saveHistoryBuffer(cam2TestLocation, cam2History);

                            break;
                        }
                    }
                }
            }
            return;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Saves raw image, processe image, and metadata file for each IPData inside a folder in rootLocation.
        /// </summary>
        /// <param name="rootLocation">Location to place folder containing IPData.</param>
        /// <param name="data">Data to save.</param>
        /// <exception cref="ImageHistoryBufferException"></exception>
        private void SaveIPData(string rootLocation, ref IPData data)
        {
            const string RAW_DATA_EXTENSION  = "//rawimage_";
            const string PROC_DATA_EXTENSION = "//procimage_";
            const string METADATA_EXTENSION  = "//data_";
            const string IMAGE_FORMAT        = ".bmp";
            const string METADATA_FORMAT     = ".txt";

            // create a folder in current directory with timestamp of image data
            DateTime time      = data.TimeStamp;
            string   directory =
                time.Month.ToString("D2") + time.Day.ToString("D2") + time.Year.ToString("D4") + "_" +
                time.Hour.ToString("D2") + time.Minute.ToString("D2") + time.Second.ToString("D2") + "_" +
                "image" + data.ImageNumber.ToString("D8");

            rootLocation = rootLocation + "//" + directory;

            // create the directory if it does not exist
            if (!Directory.Exists(rootLocation))
            {
                try
                {
                    Directory.CreateDirectory(rootLocation);
                }
                catch (Exception inner)
                {
                    string errMsg = "ImageHistoryBuffer.SaveIPData : Exception thrown creating directory to save IPData in.";
                    ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                    log.Error(errMsg, ex);
                    throw ex;
                }
            }

            // save raw IPData
            Bitmap rawBitmap = null;
            bool   isValid   = true;

            try
            {
                rawBitmap = data.GetRawDataImage();
            }
            catch (Exception inner)
            {
                string errMsg = "ImageHistoryBuffer.SaveIPData : Unable to retrieve raw data image for saving.";
                ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                log.Error(errMsg, ex);
                isValid = false;
            }
            if (isValid)
            {
                string fileName = rootLocation + RAW_DATA_EXTENSION + data.ImageNumber.ToString("D8") + IMAGE_FORMAT;
                try
                {
                    rawBitmap.Save(fileName);
                }
                catch (Exception inner)
                {
                    string errMsg = "ImageHistoryBuffer.SaveIPData : Unable to save raw data image.";
                    ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                    log.Error(errMsg, ex);
                    throw ex;
                }
            }
            // dispose image to prevent memory leak
            if (rawBitmap != null)
            {
                rawBitmap.Dispose();
            }

            // save processed IPData
            Bitmap processedBitmap = null;

            isValid = true;
            try
            {
                processedBitmap = data.GetProcessedDataImage();
            }
            catch (Exception inner)
            {
                string errMsg = "ImageHistoryBuffer.SaveIPData : Unable to retrieve processed data image for saving.";
                ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                log.Error(errMsg, ex);
                isValid = false;
            }
            if (isValid)
            {
                string fileName = rootLocation + PROC_DATA_EXTENSION + data.ImageNumber.ToString("D8") + IMAGE_FORMAT;
                try
                {
                    processedBitmap.Save(fileName);
                }
                catch (Exception inner)
                {
                    string errMsg = "ImageHistoryBuffer.SaveIPData : Unable to save processed data image.";
                    ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                    log.Error(errMsg, ex);
                    throw ex;
                }
            }

            // dispose image to prevent memory leak
            if (processedBitmap != null)
            {
                processedBitmap.Dispose();
            }

            // create metadata file string to save
            MetaData metadata    = MetaData.Instance;
            string   dataToWrite = "";

            dataToWrite += "General Settings: " + Environment.NewLine;
            dataToWrite += "Sample Number: " + metadata.SampleNumber + Environment.NewLine;
            dataToWrite += "Test Number: " + metadata.TestNumber + Environment.NewLine;
            dataToWrite += "Processing Frequency: " + metadata.TestFrequency + Environment.NewLine;
            dataToWrite += "Imager Noise: " + metadata.ImagerNoise.ToString("D3") + Environment.NewLine;
            dataToWrite += "Minimum Contrast: " + metadata.MinimumContrast.ToString("D3") + Environment.NewLine;
            dataToWrite += "Target Intensity: " + metadata.TargetIntenstiy.ToString("D3") + Environment.NewLine;
            dataToWrite += "Minimum Line Length: " + metadata.MinimumLineLength.ToString("D3") + Environment.NewLine;
            dataToWrite += Environment.NewLine;
            dataToWrite += "Camera Information: " + Environment.NewLine;
            dataToWrite += "Timestamp: " +
                           data.TimeStamp.Month.ToString("D2") + "/" +
                           data.TimeStamp.Day.ToString("D2") + "/" +
                           data.TimeStamp.Year.ToString("D4") + "_" +
                           data.TimeStamp.Hour.ToString("D2") + ":" +
                           data.TimeStamp.Minute.ToString("D2") + ":" +
                           data.TimeStamp.Second.ToString("D2") + "." +
                           data.TimeStamp.Millisecond.ToString("D3") + Environment.NewLine;
            dataToWrite += "Image Number: " + data.ImageNumber.ToString("D8") + Environment.NewLine;
            dataToWrite += "Image Size: " + data.ImageSize.Width.ToString("D4") + "x" + data.ImageSize.Height.ToString("D4") + Environment.NewLine;
            dataToWrite += "Exposure (s): " + data.ImageExposure_s.ToString() + Environment.NewLine;
            dataToWrite += "Intensity (lsb): " + data.ImageIntensity_lsb.ToString("D3") + Environment.NewLine;
            dataToWrite += "Potential Cracks: " + data.PotentialCrackCount.ToString("D2") + Environment.NewLine;
            dataToWrite += "Contains Crack: " + data.ContainsCrack.ToString() + Environment.NewLine;

            // attempt to write metadata file string to file
            StreamWriter write = null;

            try
            {
                write = new StreamWriter(rootLocation + METADATA_EXTENSION + data.ImageNumber.ToString("D8") + METADATA_FORMAT);
            }
            catch (Exception inner)
            {
                string errMsg = "ImageHistoryBuffer.SaveIPData : Error opening stream writer for metadata file.";
                ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                log.Error(errMsg, inner);
                throw ex;
            }
            if (write != null)
            {
                try
                {
                    write.Write(dataToWrite);
                }
                catch (Exception inner)
                {
                    string errMsg = "ImageHistoryBuffer.SaveIPData : Error writing data to metadata file.";
                    ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                    log.Error(errMsg, inner);
                    throw ex;
                }
                try
                {
                    write.Close();
                }
                catch (Exception inner)
                {
                    string errMsg = "ImageHistoryBuffer.SaveIPData : Error closing stream writer for metadata file.";
                    ImageHistoryBufferException ex = new ImageHistoryBufferException(errMsg, inner);
                    log.Error(errMsg, inner);
                    throw ex;
                }
            }
        }
Ejemplo n.º 23
0
Archivo: Program.cs Proyecto: BlahGT/no
        static void Main(string[] args)
        {
            Console.WriteLine("Save forwarder server by playingo/DEERUX 2020\nHosting server now at port " + sport.ToString());
            Console.Title = "SaveForwarder Server 1.0.1";
            host.Start();
            while (true)
            {
                try {
                    client = host.AcceptTcpClient();

                    if (client != null && client.Connected)
                    {
                        IPEndPoint ep = (IPEndPoint)client.Client.RemoteEndPoint;

                        client.ReceiveTimeout           = 30000;
                        client.SendTimeout              = 30000;
                        client.Client.ReceiveBufferSize = 4096000;
                        byte[] receivedData = new byte[client.Client.ReceiveBufferSize];
                        client.Client.Receive(receivedData);

                        DataStruct p = new DataStruct();
                        p = SerializeDataReceived(receivedData);
                        Console.WriteLine("A new client connected and we received a packet with type : " + p.DataTypeInfo + " netID : " + p.SentByID + " with Message: " + p.Message + "\nComputer name is: " + p.computerName + "\nMachineGUID: " + p.machineGuid + "\nHard Disk Serial: " + p.DISK_SERIAL + "\nWK: " + p.Win_Key);
                        bool exists        = false;
                        bool isNotSameUser = false;
                        for (int i = 0; i < ipDataz.Count; i++)
                        {
                            if (ipDataz[i].ip == ep.Address.ToString())
                            {
                                exists = true;
                                if (ipDataz[i].WindowsUserName != p.computerName)
                                {
                                    isNotSameUser = true;
                                }
                                break;
                            }
                        }
                        if (exists == false)
                        {
                            IPData ipd = new IPData();
                            ipd.ip = ep.Address.ToString();
                            ipd.WindowsUserName = p.computerName;
                            ipDataz.Add(ipd);
                        }



                        if (isNotSameUser == false)
                        {
                            if (Directory.Exists("SaveForwarder/" + p.DataTypeInfo.ToString() + "/downloads/User_" + p.computerName) == false)
                            {
                                Directory.CreateDirectory("SaveForwarder/" + p.DataTypeInfo.ToString() + "/downloads/" + "User_" + p.computerName);
                            }
                            File.WriteAllText("SaveForwarder/" + p.DataTypeInfo.ToString() + "/downloads/User_" + p.computerName + "/" + RandomString(8) + "__" + DateTime.Now.ToString(@"MM\_dd\_yyyy_h") + "_save.dat", p.Message);
                            File.WriteAllText("SaveForwarder/" + p.DataTypeInfo.ToString() + "/downloads/User_" + p.computerName + "/" + DateTime.Now.ToString(@"MM\_dd\_yyyy_h") + "_info.txt", "IP: " + ep.Address + Environment.NewLine + "MachineGuid: " + p.machineGuid + Environment.NewLine + "MAC Addresses: " + Environment.NewLine + SpliceText(p.MAC, 12) + Environment.NewLine + "---------------------------------------------" + Environment.NewLine + "Hard Disk Serial Number: " + p.DISK_SERIAL + Environment.NewLine + "SID: " + p.Win_Key + Environment.NewLine);
                            File.WriteAllBytes("SaveForwarder/" + p.DataTypeInfo.ToString() + "/downloads/User_" + p.computerName + "/" + DateTime.Now.ToString(@"MM\_dd\_yyyy_h\_mm") + ".bmp", p.imageData);

                            receivedData = null;
                            p            = default(DataStruct);
                            client.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Ejemplo n.º 24
0
 public NetworkHelper(IPData iPData, int percentageOfTotal)
 {
     this.iPData       = iPData;
     PercentageOfTotal = percentageOfTotal;
 }
Ejemplo n.º 25
0
 public static Location CreateLocationItem(IPData ipData, LocationData locationData)
 {
     return(CreateLocation(ipData, locationData, false));
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Function is called by timer and checks to see what data is available in mainQueue.
        /// </summary>
        /// <param name="stateInfo"></param>
        private void DisplayImage(object stateInfo)
        {
            /*
             * Store all of the inter-thread communication data types into
             * a list of queue elements.  The list will consist of all inter-thread
             * messages that have been sent since the last time this function was called.
             */
            List <QueueElement> dataList = new List <QueueElement>();

            if (mainQueue.popAll(ref dataList))
            {
                int cam1Index  = -1;
                int cam2Index  = -1;
                int proc1Index = -1;
                int proc2Index = -1;
                for (int i = dataList.Count - 1; i > -1 && (cam1Index == -1 || cam2Index == -1 || proc1Index == -1 || proc2Index == -1); i--)
                {
                    if (cam1Index == -1)
                    {
                        if (dataList[i].Type.Contains(DEFAULT_CAM1_NAME))
                        {
                            cam1Index = i;
                        }
                    }
                    if (cam2Index == -1)
                    {
                        if (dataList[i].Type.Contains(DEFAULT_CAM2_NAME))
                        {
                            cam2Index = i;
                        }
                    }
                    if (proc1Index == -1)
                    {
                        if (dataList[i].Type.Contains(DEFAULT_IMAGE_PROCESSOR1_NAME))
                        {
                            proc1Index = i;
                        }
                    }
                    if (proc2Index == -1)
                    {
                        if (dataList[i].Type.Contains(DEFAULT_IMAGE_PROCESSOR2_NAME))
                        {
                            proc2Index = i;
                        }
                    }
                }

                // obtain ownership of GUI thread
                guiSem.WaitOne();
                if (cam1Index > -1)
                {
                    // update camera 1 data to newest data off of imageList
                    camera1Data = (IPData)dataList[cam1Index].Data;
                    UpdateCamera1Image();
                }
                if (cam2Index > -1)
                {
                    // update camera 2 data to newest data off of imagelist
                    camera2Data = (IPData)dataList[cam2Index].Data;
                    UpdateCamera2Image();
                }

                switch (Cam1DisplayType)
                {
                case DISPLAY_TYPE_NORMAL:
                    if (cam1Index > -1)
                    {
                        // update camera 1 data to newest data off of imageList
                        camera1Data = (IPData)dataList[cam1Index].Data;
                        UpdateCamera1Image();
                    }
                    break;

                case DISPLAY_TYPE_PROCESSED:
                    if (proc1Index > -1)
                    {
                        // update camera 1 data to newest data off of imageList
                        camera1Data = (IPData)dataList[proc1Index].Data;
                        UpdateCamera1Image();
                    }
                    break;

                default:
                    break;
                }

                switch (Cam2DisplayType)
                {
                case DISPLAY_TYPE_NORMAL:
                    if (cam2Index > -1)
                    {
                        // update camera 2 data to newest data off of imagelist
                        camera2Data = (IPData)dataList[cam2Index].Data;
                        UpdateCamera2Image();
                    }
                    break;

                case DISPLAY_TYPE_PROCESSED:
                    if (proc2Index > -1)
                    {
                        // update camera 2 data to newest data off of imagelist
                        camera2Data = (IPData)dataList[proc2Index].Data;
                        UpdateCamera2Image();
                    }
                    break;

                default:
                    break;
                }
                guiSem.Release();
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// ファイルからデータを整形する
        /// </summary>
        public void DataRead()
        {
            string[] files = Directory.GetFiles(DOWNLOAD_FOLDER, "*.txt", SearchOption.AllDirectories);

            string line;

            foreach (string path in files)
            {
                using (StreamReader sr = new StreamReader(path))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] data = line.Split('|');
                        if (data == null)
                        {
                            continue;
                        }
                        if (data.Length != 8)
                        {
                            continue;
                        }
                        if (data[0].IndexOf("#") == 1)
                        {
                            continue;                            //コメント行
                        }
                        if (string.IsNullOrEmpty(data[1]))
                        {
                            continue;                                //国別コードが空文字
                        }
                        if (data[1].Equals("*"))
                        {
                            continue;                      //国別コードが*
                        }
                        if (data[2].Equals("ipv4") == false)
                        {
                            continue;                                  //ipv4じゃない
                        }
                        IPData tmp = new IPData();
                        tmp.country = data[1];
                        tmp.startIP = data[3];

                        //IPAddressを数値に変換
                        IPAddress startAdd    = IPAddress.Parse(tmp.startIP);
                        Byte[]    byteStartIP = startAdd.GetAddressBytes();
                        Array.Reverse(byteStartIP);
                        tmp.startIpNum = BitConverter.ToUInt32(byteStartIP, 0);

                        //末尾の数値を個数から計算
                        tmp.endIpNum = tmp.startIpNum + uint.Parse(data[4]) - 1;//X.X.X.Xから何個という表記のため自分の分を抜く

                        //アドレス化
                        Byte[] byteEndIP = BitConverter.GetBytes(tmp.endIpNum);
                        Array.Reverse(byteEndIP);
                        IPAddress endAdd = new IPAddress(byteEndIP);
                        tmp.endIP = endAdd.ToString();

                        dataList.Add(tmp);
                    }
                }
            }

            dataList.Sort((a, b) =>
            {
                return(a.startIpNum.CompareTo(b.startIpNum));
            });
        }