Пример #1
0
        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (textBoxName.Text == "")
            {
                MessageBox.Show("Please specify the fileName first!");
                return;
            }

            SaveFileDialog saveDialog = new SaveFileDialog();
            List <Quote>   quoteList  = new List <Quote>(AllQuotes);

            quoteList.Sort();
            saveDialog.Filter   = "QuoteList as XML|*.his";
            saveDialog.FileName = textBoxName.Text + theType.ToString() + ".his";
            saveDialog.Title    = "Save the Quote List as his file...";

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                XmlSerializer serializer = new XmlSerializer(quoteList.GetType());

                using (FileStream fs = new FileStream(saveDialog.FileName, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    serializer.Serialize(fs, quoteList);
                    fs.Close();
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Retrieves whois information
        /// </summary>
        /// <param name="domainName">The registrar or domain or name server whose whois information to be retrieved</param>
        /// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
        /// <returns></returns>
        public static string Lookup(string domainName, RecordType recordType)
        {
            string whoisServerName = WhoisServerResolver.GetWhoisServerName(domainName);
            using (TcpClient whoisClient = new TcpClient())
            {
                whoisClient.Connect(whoisServerName, Whois_Server_Default_PortNumber);

                string domainQuery = recordType.ToString() + " " + domainName + "\r\n";
                byte[] domainQueryBytes = Encoding.ASCII.GetBytes(domainQuery.ToCharArray());

                Stream whoisStream = whoisClient.GetStream();
                whoisStream.Write(domainQueryBytes, 0, domainQueryBytes.Length);

                StreamReader whoisStreamReader = new StreamReader(whoisClient.GetStream(), Encoding.ASCII);

                string streamOutputContent = "";
                List<string> whoisData = new List<string>();
                while (null != (streamOutputContent = whoisStreamReader.ReadLine()))
                {
                    whoisData.Add(streamOutputContent);
                }

                whoisClient.Close();

                return String.Join(Environment.NewLine, whoisData);
            }
        }
        /// <summary>
        /// Add Aliyun DNS Record
        /// </summary>
        /// <param name="domainName"> Domain name </param>
        /// <param name="rr"> @.exmaple.com =&gt; @ </param>
        /// <param name="type"> A/NS/MX/TXT/CNAME/SRV/AAAA/CAA/REDIRECT_URL/FORWARD_URL </param>
        /// <param name="value"> Value </param>
        /// <param name="ttl"> Default 600 sec </param>
        /// <param name="priority"> Default 0(1-10 when type is MX) </param>
        /// <param name="line"> default </param>
        /// <returns>  </returns>
        private async Task <DomainRecord> AddDomainRecord(string domainName, string rr, RecordType type, string value, long ttl = 600, long priority = 0, string line = "default")
        {
            var parameters = new Dictionary <string, string>
            {
                { "Action", "AddDomainRecord" },
                { "DomainName", domainName },
                { "RR", rr },
                { "Type", type.ToString() },
                { "Value", value },
                { "TTL", ttl.ToString() },
                { "Line", line }
            };

            if (type == RecordType.MX)
            {
                if (priority < 1 || priority > 10)
                {
                    throw new Exception("priority must in 1 to 10 when type is MX");
                }
                parameters.Add("Priority", priority.ToString());
            }

            var request = new AliDnsRequest(HttpMethod.Get, _accessKeyId, _accessKeySecret, parameters);
            var url     = request.GetUrl();

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync(url);

                var content = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <DomainRecord>(content));
            }
        }
Пример #4
0
 public void UpdateElement(XElement element, HostingConfigManager manager)
 {
     element.SetElementValue("Name", Name);
     element.SetElementValue("Value", Value);
     element.SetElementValue("RecordType", RecordType.ToString());
     element.SetElementValue("Ttl", Ttl);
 }
Пример #5
0
        /// <summary>
        /// Retrieves whois information
        /// </summary>
        /// <param name="domainName">The registrar or domain or name server whose whois information to be retrieved</param>
        /// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
        /// <returns></returns>
        public static string Lookup(string domainName, RecordType recordType)
        {
            string whoisServerName = WhoisServerResolver.GetWhoisServerName(domainName);

            using (TcpClient whoisClient = new TcpClient())
            {
                whoisClient.Connect(whoisServerName, Whois_Server_Default_PortNumber);

                string domainQuery      = recordType.ToString() + " " + domainName + "\r\n";
                byte[] domainQueryBytes = Encoding.ASCII.GetBytes(domainQuery.ToCharArray());

                Stream whoisStream = whoisClient.GetStream();
                whoisStream.Write(domainQueryBytes, 0, domainQueryBytes.Length);

                StreamReader whoisStreamReader = new StreamReader(whoisClient.GetStream(), Encoding.ASCII);

                string        streamOutputContent = "";
                List <string> whoisData           = new List <string>();
                while (null != (streamOutputContent = whoisStreamReader.ReadLine()))
                {
                    whoisData.Add(streamOutputContent);
                }

                whoisClient.Close();

                return(String.Join(Environment.NewLine, whoisData));
            }
        }
        public async Task DeleteRecord(string record, string identifier, RecordType type, string value)
        {
            using (var client = _proxyService.GetHttpClient())
            {
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Authorization", $"sso-key {_apiKey}");

                var typeTxt     = type.ToString();
                var buildApiUrl = $"v1/domains/{identifier}/records/{typeTxt}/_acme-challenge";

                _logService.Information("Godaddy API with: {0}", buildApiUrl);;

                var response = await client.DeleteAsync(buildApiUrl);

                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    //_logService.Information("Godaddy Delete Responded with: {0}", content);
                    //_logService.Information("Waiting for 30 seconds");
                    //await Task.Delay(30000);
                }
                else
                {
                    var content = await response.Content.ReadAsStringAsync();

                    throw new Exception(content);
                }
            };
        }
        public override byte[] WriteMsg()
        {
            string data = "";

            data += UserNo.PadLeft(8, '0');
            data += SerialNumber.PadLeft(8, '0');
            data += StartTime.ToString("yyyyMMddHHmmss").Substring(2).PadLeft(12, '0');
            data += ((int)(StartResidualWater * 10)).ToString().PadLeft(8, '0');
            data += ((int)(StartResidualElectric * 10)).ToString().PadLeft(8, '0');
            data += EndTime.ToString("yyyyMMddHHmmss").Substring(2).PadLeft(12, '0');
            data += ((int)(EndResidualWater * 10)).ToString().PadLeft(8, '0');
            data += ((int)(EndResidualElectric * 10)).ToString().PadLeft(8, '0');
            data += ((int)(WaterUsed * 10)).ToString().PadLeft(8, '0');
            data += ((int)(ElectricUsed * 10)).ToString().PadLeft(8, '0');
            data += ((int)(YearElectricUsed * 10)).ToString().PadLeft(8, '0');
            data += ((int)(YearWaterUsed * 10)).ToString().PadLeft(8, '0');
            data += ((int)(YearExploitation * 10)).ToString().PadLeft(8, '0');
            data += ((int)(YearSurplus * 10)).ToString().PadLeft(8, '0');

            data += RecordType.ToString("X").PadLeft(2, '0');
            data += REV1.ToString("X").PadLeft(2, '0');
            data += REV2.ToString("X").PadLeft(2, '0');
            data += CRC8.ToString("X").PadLeft(2, '0');

            IsPW = false;
            PW   = "";
            IsTP = false;
            TP   = "";

            UserData = data;

            UserDataBytes = HexStringUtility.HexStringToByteArray(UserData);

            return(WriteMsg2());
        }
Пример #8
0
        public TypeOrg ImportOrganization(RecordType recordType, string clientType, string mainSpec)
        {
            OrganizationModel organizationModel = new OrganizationModel {
                RecordType = recordType.ToString(), ClientType = clientType, MainSpec = mainSpec
            };

            return(new ReadFileOrganization().GetTypeOrg(organizationModel));
        }
Пример #9
0
        // Public Methods

        public override String ToString()
        {
            return(String.Format("{0} {1} {2} {3} {4}",
                                 Name,
                                 TTL.ToString(),
                                 RecordClass.ToString(),
                                 RecordType.ToString(),
                                 RecordData));
        }
        private async Task <RecordSet> GetOrCreateRecordSetAsync(IRecordSetsOperations recordSetClient, RecordType type, string resourceGroup, string zoneName, string name, string value)
        {
            RecordSet set = null !;

            try
            {
                set = await recordSetClient.GetAsync(resourceGroup, zoneName, name, type);
            }
            catch (CloudException e)
            {
                if (e.Response.StatusCode != System.Net.HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            if (set == null)
            {
                set = new RecordSet(name: name, tTL: 1);
                switch (type)
                {
                case RecordType.TXT:
                    set.TxtRecords = new List <TxtRecord>();
                    break;

                default:
                    throw new Exception("Record type is unsupported: " + type.ToString());
                }
            }


            switch (type)
            {
            case RecordType.TXT:
                set.TxtRecords.Add(new TxtRecord(new[] { value }));
                break;

            default:
                throw new Exception("Record type is unsupported: " + type.ToString());
            }

            return(set);
        }
Пример #11
0
 public virtual bool IsDocument()
 {
     for (int i = 0; i < GetDocumentNumberKeys().Count; i++)
     {
         if (GetDocumentNumberKeys()[i].Contains(RecordType.ToString()))
         {
             return(true);
         }
     }
     return(false);
 }
        public async Task <NrlsPointerMap> FindPointerMap(string recordId, RecordType recordType)
        {
            var builder = Builders <NrlsPointerMap> .Filter;
            var filters = new List <FilterDefinition <NrlsPointerMap> >();

            filters.Add(builder.Eq(x => x.RecordId, recordId));
            filters.Add(builder.Eq(x => x.RecordType, recordType.ToString()));
            filters.Add(builder.Eq(x => x.IsActive, true));

            return(await _context.NrlsPointerMaps.FindSync(builder.And(filters), null).FirstOrDefaultAsync());
        }
Пример #13
0
 public XElement ToXElement(HostingConfigManager manager)
 {
     return(new XElement(
                "Record",
                new XElement("RecordID", DataID),
                new XElement("Name", Name),
                new XElement("Ttl", Ttl),
                new XElement("RecordType", RecordType.ToString()),
                new XElement("Value", Value)
                ));
 }
Пример #14
0
        private string GetCounterName(RecordType recordType)
        {
            switch (recordType)
            {
            case RecordType.Spectrum:
                return("Spectra");

            default:
                return(recordType.ToString() + "s");
            }
        }
        public void CreatePointerMap(string pointerId, ObjectId recordId, RecordType recordType)
        {
            var pointerMapper = new NrlsPointerMap
            {
                IsActive      = true,
                NrlsPointerId = pointerId,
                RecordId      = recordId.ToString(),
                RecordType    = recordType.ToString()
            };

            _context.NrlsPointerMaps.InsertOne(pointerMapper);
        }
Пример #16
0
 public override int GetHashCode()
 {
     return((_projNumber.ToString() +
             _jobNumber.ToString() +
             _actNumber.ToString() +
             _recordDate +
             _content +
             _alarmTime +
             _alarmRepit.ToString() +
             _note +
             _recordType.ToString() +
             _recordStatus.ToString() +
             _fill.ToString() +
             _hide.ToString()).GetHashCode());
 }
Пример #17
0
        public void DeleteRecord(string record, RecordType type, string value)
        {
            var args = new Dictionary <string, string>
            {
                { "record", record },
                { "type", type.ToString() },
                { "value", value }
            };

            var response = SendRequest("dns-remove_record", args);

            _logService.Information("Dreamhost Responded with: {0}", response.Content.ReadAsStringAsync().Result);
            _logService.Information("Waiting for 30 seconds");

            Thread.Sleep(TimeSpan.FromSeconds(30));
        }
Пример #18
0
        /// <summary>
        /// Create and store a new metadata record
        /// </summary>
        /// <param name="runId">uniquely identifies a run of the OBA service</param>
        /// <param name="regionId">uniquely identifies a region</param>
        /// <param name="agencyId">uniquely identifies an agency</param>
        /// <param name="recordType">type of record to store</param>
        /// <param name="count">number of records stored</param>
        /// <returns>a task that inserts a new metadata record</returns>
        public async Task Insert(string runId, string regionId, string agencyId, RecordType recordType, int count)
        {
            DownloadMetadataEntity entity = new DownloadMetadataEntity()
            {
                RunId      = runId,
                RegionId   = regionId,
                AgencyId   = agencyId,
                RecordType = recordType.ToString(),
                Count      = count
            };

            List <DownloadMetadataEntity> entities = new List <DownloadMetadataEntity>();

            entities.Add(entity);
            await this.Insert(entities);
        }
Пример #19
0
        public async Task DeleteRecord(string record, RecordType type, string value)
        {
            var args = new Dictionary <string, string>
            {
                { "record", record },
                { "type", type.ToString() },
                { "value", value }
            };
            var response = await SendRequest("dns-remove_record", args);

            var content = await response.Content.ReadAsStringAsync();

            _logService.Information("Dreamhost Responded with: {0}", content);
            _logService.Information("Waiting for 30 seconds");
            await Task.Delay(30000);
        }
Пример #20
0
 /// <summary>
 /// 记录类型序列化
 /// </summary>
 /// <param name="payment"></param>
 /// <returns></returns>
 public static string Serialize(RecordType type)
 {
     try
     {
         string text    = type.ToString();
         byte[] data    = System.Text.UTF8Encoding.UTF8.GetBytes(text);
         string hex     = HexStringConverter.HexToString(data, string.Empty);
         string encript = (new DTEncrypt()).Encrypt(hex);
         return(encript);
     }
     catch (Exception ex)
     {
         Ralid.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex);
     }
     return(string.Empty);
 }
Пример #21
0
        public async Task CreateRecord(string domain, string identifier, RecordType type, string value)
        {
            using (var client = _proxyService.GetHttpClient())
            {
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                if (!string.IsNullOrWhiteSpace(_apiSecret))
                {
                    client.DefaultRequestHeaders.Add("Authorization", $"sso-key {_apiKey}:{_apiSecret}");
                }
                else
                {
                    client.DefaultRequestHeaders.Add("Authorization", $"sso-key {_apiKey}");
                }
                var putData = new List <object>()
                {
                    new { ttl = 0, data = value }
                };
                var serializedObject = Newtonsoft.Json.JsonConvert.SerializeObject(putData);

                //Record successfully created
                // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
                var typeTxt     = type.ToString();
                var httpContent = new StringContent(serializedObject, Encoding.UTF8, "application/json");
                var buildApiUrl = $"v1/domains/{domain}/records/{typeTxt}/{identifier}";

                _log.Information("Godaddy API with: {0}", buildApiUrl);
                _log.Verbose("Godaddy Data with: {0}", serializedObject);

                var response = await client.PutAsync(buildApiUrl, httpContent);

                if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    //_logService.Information("Godaddy Created Responded with: {0}", content);
                    //_logService.Information("Waiting for 30 seconds");
                    //await Task.Delay(30000);
                }
                else
                {
                    var content = await response.Content.ReadAsStringAsync();

                    throw new Exception(content);
                }
            };
        }
Пример #22
0
 /// <summary>
 /// retrieves whois information
 /// </summary>
 /// <param name="domainname">The registrar or domain or name server whose whois information to be retrieved</param>
 /// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
 /// <param name="returnlist">use "whois.internic.net" if you dont know whoisservers</param>
 /// <returns>The string list containg the whois information</returns>
 public static List<string> Lookup(string domainname, RecordType recordType, string whois_server_address = "whois.internic.net")
 {
     TcpClient tcp = new TcpClient();
     tcp.Connect(whois_server_address, 43);
     string strDomain = recordType.ToString() + " " + domainname + "\r\n";
     byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray());
     Stream s = tcp.GetStream();
     s.Write(bytDomain, 0, strDomain.Length);
     StreamReader sr = new StreamReader(tcp.GetStream(), Encoding.ASCII);
     string strLine = "";
     List<string> result = new List<string>();
     while (null != (strLine = sr.ReadLine()))
     {
         result.Add(strLine);
     }
     tcp.Close();
     return result;
 }
Пример #23
0
 public static string Whois_lookup(string domainname, RecordType recordType)
 {
     string whois_server_address = "whois.internic.net";
     TcpClient tcp = new TcpClient();
     tcp.Connect(whois_server_address, 43);
     string strDomain = recordType.ToString() + " " + domainname + "\r\n";
     byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray());
     Stream s = tcp.GetStream();
     s.Write(bytDomain, 0, strDomain.Length);
     var sr = new StreamReader(tcp.GetStream(), Encoding.ASCII);
     string final = "";
     string strLine;
     while (null != (strLine = sr.ReadLine()))
     {
         final = final + strLine + "\n";
     }
     tcp.Close();
     return final;
 }
Пример #24
0
        /// <summary>
        /// Calculates the total amount for debits or credits, depending on which
        /// RecordType has been specified.
        /// </summary>
        /// <param name="type">
        /// The RecordType for which to calculate the total amount.
        /// Limited to RecordType.Debit and RecordType.Credit.
        /// </param>
        /// <returns>The total amount</returns>
        internal Double CalculateTotalAmount(RecordType type)
        {
            if (!(Equals(type, RecordType.Debit) || Equals(type, RecordType.Credit)))
            {
                throw new ArgumentException("Invalid parameter passed. " + type.ToString());
            }

            Double totalAmount = 0.0d;

            foreach (IList <IRecord> transactionList in this.RecordsMap[type].Values)
            {
                foreach (AccountRecord record in transactionList)
                {
                    totalAmount += record.Amount;
                }
            }

            return(totalAmount);
        }
        /// <summary>
        /// Get a list of persistent Objects
        /// </summary>
        /// <param name="type"></param>
        /// <param name="folder"></param>
        /// <param name="closeDate"></param>
        /// <returns>List</returns>
        public List <PersistentObject> CloseFolderAndStartRetention(RecordType type, Folder folder, DateTime closeDate)
        {
            FeedGetOptions opts = new FeedGetOptions {
                Inline = true, Links = true
            };

            Folder recordFolder = GetFolderByPath("/SystemA File Plan/INC/" + type.ToString());

            string[] folderIds = folder.GetRepeatingValuesAsString("i_folder_id", ",").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (!folderIds.Contains(recordFolder.GetPropertyValue("r_object_id").ToString()))
            {
                Folder     linkFolder  = recordFolder.CreateHrefObject <Folder>();
                FolderLink folderLink2 = folder.LinkToFolder(linkFolder, null);
            }

            Feed <PersistentObject> feed = UpdateCloseDate(folder.GetPropertyValue("r_object_id").ToString(), closeDate);

            return(feed != null?ObjectUtil.getFeedAsList(feed, true) : null);
        }
Пример #26
0
        private static void WriteDataToLog(Device device, string content, RecordType recordType, bool flush = false)
        {
            // To Log File
            DateTime      now        = DateTime.Now;
            StreamWriter  fileWriter = RecordManager.GetLogFileStream(device, now);
            string        time       = string.Format("[{0:HH:mm:ss}] ", now);
            StringBuilder sb         = new StringBuilder(time);

            sb.Append(string.Format(" <{0}> ", recordType.ToString()));
            sb.Append(content);
            string line = sb.ToString();

            fileWriter.WriteLine(line);

            // Flush Control.
#if DEBUG
            fileWriter.Flush();
#else
            if (flush)
            {
                fileWriter.Flush();
            }
#endif

            if (flushCtrlCount % 10 == 0)
            {
                fileWriter.Flush();
            }
            flushCtrlCount = (flushCtrlCount + 1) % 5;

            // To Log Console
            if (ExistLoggerConsoleProc())
            {
                string deviceKey = device.Id.ToLower();
                if (LoggerClient.Contains(deviceKey))
                {
                    logger.Send(deviceKey, line);
                }
            }
        }
Пример #27
0
        /// <summary>
        /// retrieves whois information
        /// </summary>
        /// <param name="domainname">The registrar or domain or name server whose whois information to be retrieved</param>
        /// <param name="recordType">The type of record i.e a domain, nameserver or a registrar</param>
        /// <param name="returnlist">use "whois.internic.net" if you dont know whoisservers</param>
        /// <returns>The string list containg the whois information</returns>
        public static List <string> Lookup(string domainname, RecordType recordType, string whois_server_address = "whois.internic.net")
        {
            TcpClient tcp = new TcpClient();

            tcp.Connect(whois_server_address, 43);
            string strDomain = recordType.ToString() + " " + domainname + "\r\n";

            byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray());
            Stream s         = tcp.GetStream();

            s.Write(bytDomain, 0, strDomain.Length);
            StreamReader  sr      = new StreamReader(tcp.GetStream(), Encoding.ASCII);
            string        strLine = "";
            List <string> result  = new List <string>();

            while (null != (strLine = sr.ReadLine()))
            {
                result.Add(strLine);
            }
            tcp.Close();
            return(result);
        }
Пример #28
0
        public static string Whois_lookup(string domainname, RecordType recordType)
        {
            string    whois_server_address = "whois.internic.net";
            TcpClient tcp = new TcpClient();

            tcp.Connect(whois_server_address, 43);
            string strDomain = recordType.ToString() + " " + domainname + "\r\n";

            byte[] bytDomain = Encoding.ASCII.GetBytes(strDomain.ToCharArray());
            Stream s         = tcp.GetStream();

            s.Write(bytDomain, 0, strDomain.Length);
            var    sr    = new StreamReader(tcp.GetStream(), Encoding.ASCII);
            string final = "";
            string strLine;

            while (null != (strLine = sr.ReadLine()))
            {
                final = final + strLine + "\n";
            }
            tcp.Close();
            return(final);
        }
        private async Task CleanRecordSet(string resourceGroup, string zone, RecordSet set, RecordType type, string value)
        {
            bool shouldDelete = false;

            switch (type)
            {
            case RecordType.TXT:
                set.TxtRecords = set.TxtRecords.Where(t => t.Value.FirstOrDefault() != value).ToArray();
                shouldDelete   = (set.TxtRecords.Count == 0);
                break;

            default:
                throw new Exception("Record type is unsupported: " + type.ToString());
            }

            if (shouldDelete)
            {
                await this.dnsClient.RecordSets.DeleteAsync(resourceGroup, zone, set.Name, type);
            }
            else
            {
                await this.dnsClient.RecordSets.UpdateAsync(resourceGroup, zone, set.Name, type, set);
            }
        }
Пример #30
0
        public static (List <DnsRecordBase> list, ReturnCode statusCode) ResolveOverHttpsByDnsJson(string clientIpAddress,
                                                                                                   string domainName, string dohUrl,
                                                                                                   bool proxyEnable = false, IWebProxy wProxy = null, RecordType type = RecordType.A)
        {
            string dnsStr;
            List <DnsRecordBase> recordList = new List <DnsRecordBase>();

            try
            {
                dnsStr = MyCurl.GetString(dohUrl + @"?ct=application/dns-json&" +
                                          $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}",
                                          DnsSettings.Http2Enable, proxyEnable, wProxy, DnsSettings.AllowAutoRedirect);
            }
            catch (WebException e)
            {
                HttpWebResponse response = (HttpWebResponse)e.Response;
                try
                {
                    BackgroundLog($@"| - Catch WebException : {Convert.ToInt32(response.StatusCode)} {response.StatusCode} | {e.Status} | {domainName} | {response.ResponseUri}");
                    if (DnsSettings.HTTPStatusNotify)
                    {
                        MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误",
                                                             $"异常 :{Convert.ToInt32(response.StatusCode)} {response.StatusCode} {Environment.NewLine} {domainName}", ToolTipIcon.Warning);
                    }
                    if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        DnsSettings.DnsMsgEnable = true;
                    }
                }
                catch (Exception exception)
                {
                    BackgroundLog($@"| - Catch WebException : {exception.Message} | {e.Status} | {domainName} | {dohUrl}" + @"?ct=application/dns-json&" +
                                  $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}");
                    if (DnsSettings.HTTPStatusNotify)
                    {
                        MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误",
                                                             $"异常 : {exception.Message} {Environment.NewLine} {domainName}", ToolTipIcon.Warning);
                    }
                }

                if (dohUrl != DnsSettings.HttpsDnsUrl)
                {
                    return(new List <DnsRecordBase>(), ReturnCode.ServerFailure);
                }
                BackgroundLog($@"| -- SecondDoH : {DnsSettings.SecondHttpsDnsUrl}");
                return(ResolveOverHttpsByDnsJson(clientIpAddress, domainName, DnsSettings.SecondHttpsDnsUrl,
                                                 proxyEnable, wProxy, type));
            }

            JsonValue dnsJsonValue = Json.Parse(dnsStr);

            int statusCode = dnsJsonValue.AsObjectGetInt("Status");

            if (statusCode != 0)
            {
                return(new List <DnsRecordBase>(), (ReturnCode)statusCode);
            }

            if (dnsStr.Contains("\"Answer\""))
            {
                var dnsAnswerJsonList = dnsJsonValue.AsObjectGetArray("Answer");

                foreach (var itemJsonValue in dnsAnswerJsonList)
                {
                    string answerAddr       = itemJsonValue.AsObjectGetString("data");
                    string answerDomainName = itemJsonValue.AsObjectGetString("name");
                    int    answerType       = itemJsonValue.AsObjectGetInt("type");
                    int    ttl = itemJsonValue.AsObjectGetInt("TTL");

                    switch (type)
                    {
                    case RecordType.A when Convert.ToInt32(RecordType.A) == answerType && !DnsSettings.Ipv4Disable:
                    {
                        ARecord aRecord = new ARecord(
                            DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));

                        recordList.Add(aRecord);
                        break;
                    }

                    case RecordType.A:
                    {
                        if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));

                            recordList.Add(cRecord);

                            //recordList.AddRange(ResolveOverHttps(clientIpAddress,answerAddr));
                            //return recordList;
                        }

                        break;
                    }

                    case RecordType.Aaaa when Convert.ToInt32(RecordType.Aaaa) == answerType && !DnsSettings.Ipv6Disable:
                    {
                        AaaaRecord aaaaRecord = new AaaaRecord(
                            DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));
                        recordList.Add(aaaaRecord);
                        break;
                    }

                    case RecordType.Aaaa:
                    {
                        if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                            recordList.Add(cRecord);
                        }

                        break;
                    }

                    case RecordType.CName when answerType == Convert.ToInt32(RecordType.CName):
                    {
                        CNameRecord cRecord = new CNameRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(cRecord);
                        break;
                    }

                    case RecordType.Ns when answerType == Convert.ToInt32(RecordType.Ns):
                    {
                        NsRecord nsRecord = new NsRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(nsRecord);
                        break;
                    }

                    case RecordType.Mx when answerType == Convert.ToInt32(RecordType.Mx):
                    {
                        MxRecord mxRecord = new MxRecord(
                            DomainName.Parse(answerDomainName), ttl,
                            ushort.Parse(answerAddr.Split(' ')[0]),
                            DomainName.Parse(answerAddr.Split(' ')[1]));
                        recordList.Add(mxRecord);
                        break;
                    }

                    case RecordType.Txt when answerType == Convert.ToInt32(RecordType.Txt):
                    {
                        TxtRecord txtRecord = new TxtRecord(DomainName.Parse(answerDomainName), ttl, answerAddr);
                        recordList.Add(txtRecord);
                        break;
                    }

                    case RecordType.Ptr when answerType == Convert.ToInt32(RecordType.Ptr):
                    {
                        PtrRecord ptrRecord = new PtrRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(ptrRecord);
                        break;
                    }

                    default:
                        statusCode = Convert.ToInt32(ReturnCode.ServerFailure);
                        break;
                    }
                }
            }

            return(recordList, (ReturnCode)statusCode);
        }
Пример #31
0
		private static void WriteDataToLog(Device device, string content, RecordType recordType, bool flush = false)
		{
            // To Log File
			DateTime now = DateTime.Now;
            StreamWriter fileWriter = RecordManager.GetLogFileStream(device, now);
			string time = string.Format("[{0:HH:mm:ss}] ", now);
			StringBuilder sb = new StringBuilder(time);
            sb.Append(string.Format(" <{0}> ", recordType.ToString()));
			sb.Append(content);
			string line = sb.ToString();

            fileWriter.WriteLine(line);

			// Flush Control.
#if DEBUG
            fileWriter.Flush();
#else
            if (flush)
            {
                fileWriter.Flush();
            }
#endif

			if (flushCtrlCount % 10 == 0)
			{
                fileWriter.Flush();
			}
			flushCtrlCount = (flushCtrlCount + 1) % 5;

            // To Log Console
            if (ExistLoggerConsoleProc())
            {
                string deviceKey = device.Id.ToLower();
                if (LoggerClient.Contains(deviceKey))
                {
                    logger.Send(deviceKey, line);
                }
            }
		}
Пример #32
0
        public TypeOrg ImportOrganization(RecordType recordType, string clientType, string mainSpec)
        {
            OrganizationModel organizationModel = new OrganizationModel { RecordType = recordType.ToString(), ClientType = clientType, MainSpec = mainSpec };

            return new ReadFileOrganization().GetTypeOrg(organizationModel);
        }
Пример #33
0
 public override string ToString() =>
 RecordType <TestStruct> .ToString(this);
Пример #34
0
        private static (List <dynamic> list, ReturnCode statusCode) ResolveOverHttps(string clientIpAddress, string domainName,
                                                                                     bool proxyEnable = false, IWebProxy wProxy = null, RecordType type = RecordType.A)
        {
            string         dnsStr;
            List <dynamic> recordList = new List <dynamic>();

            using (MWebClient webClient = new MWebClient())
            {
                webClient.Headers["User-Agent"] = "AuroraDNSC/0.1";

//                webClient.AllowAutoRedirect = false;

                if (proxyEnable)
                {
                    webClient.Proxy = wProxy;
                }

                try
                {
                    dnsStr = webClient.DownloadString(
                        DnsSettings.HttpsDnsUrl +
                        @"?ct=application/dns-json&" +
                        $"name={domainName}&type={type.ToString().ToUpper()}&edns_client_subnet={clientIpAddress}");
                }
                catch (WebException e)
                {
                    HttpWebResponse response = (HttpWebResponse)e.Response;
                    try
                    {
                        BgwLog($@"| - Catch WebException : {Convert.ToInt32(response.StatusCode)} {response.StatusCode} | {domainName}");
                    }
                    catch (Exception exception)
                    {
                        BgwLog($@"| - Catch WebException : {exception.Message} | {domainName}");

                        //MainWindow.NotifyIcon.ShowBalloonTip(360, "AuroraDNS - 错误",
                        //    $"异常 : {exception.Message} {Environment.NewLine} {domainName}", ToolTipIcon.Warning);
                    }
                    return(new List <dynamic>(), ReturnCode.ServerFailure);
                }
            }

            JsonValue dnsJsonValue = Json.Parse(dnsStr);

            int statusCode = dnsJsonValue.AsObjectGetInt("Status");

            if (statusCode != 0)
            {
                return(new List <dynamic>(), (ReturnCode)statusCode);
            }

            if (dnsStr.Contains("\"Answer\""))
            {
                var dnsAnswerJsonList = dnsJsonValue.AsObjectGetArray("Answer");

                foreach (var itemJsonValue in dnsAnswerJsonList)
                {
                    string answerAddr       = itemJsonValue.AsObjectGetString("data");
                    string answerDomainName = itemJsonValue.AsObjectGetString("name");
                    int    answerType       = itemJsonValue.AsObjectGetInt("type");
                    int    ttl = itemJsonValue.AsObjectGetInt("TTL");

                    switch (type)
                    {
                    case RecordType.A:
                    {
                        if (Convert.ToInt32(RecordType.A) == answerType)
                        {
                            ARecord aRecord = new ARecord(
                                DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));

                            recordList.Add(aRecord);
                        }
                        else if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));

                            recordList.Add(cRecord);

                            //recordList.AddRange(ResolveOverHttps(clientIpAddress,answerAddr));
                            //return recordList;
                        }

                        break;
                    }

                    case RecordType.Aaaa:
                    {
                        if (Convert.ToInt32(RecordType.Aaaa) == answerType)
                        {
                            AaaaRecord aaaaRecord = new AaaaRecord(
                                DomainName.Parse(answerDomainName), ttl, IPAddress.Parse(answerAddr));
                            recordList.Add(aaaaRecord);
                        }
                        else if (Convert.ToInt32(RecordType.CName) == answerType)
                        {
                            CNameRecord cRecord = new CNameRecord(
                                DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                            recordList.Add(cRecord);
                        }
                        break;
                    }

                    case RecordType.CName when answerType == Convert.ToInt32(RecordType.CName):
                    {
                        CNameRecord cRecord = new CNameRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(cRecord);
                        break;
                    }

                    case RecordType.Ns when answerType == Convert.ToInt32(RecordType.Ns):
                    {
                        NsRecord nsRecord = new NsRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(nsRecord);
                        break;
                    }

                    case RecordType.Mx when answerType == Convert.ToInt32(RecordType.Mx):
                    {
                        MxRecord mxRecord = new MxRecord(
                            DomainName.Parse(answerDomainName), ttl,
                            ushort.Parse(answerAddr.Split(' ')[0]),
                            DomainName.Parse(answerAddr.Split(' ')[1]));
                        recordList.Add(mxRecord);
                        break;
                    }

                    case RecordType.Txt when answerType == Convert.ToInt32(RecordType.Txt):
                    {
                        TxtRecord txtRecord = new TxtRecord(DomainName.Parse(answerDomainName), ttl, answerAddr);
                        recordList.Add(txtRecord);
                        break;
                    }

                    case RecordType.Ptr when answerType == Convert.ToInt32(RecordType.Ptr):
                    {
                        PtrRecord ptrRecord = new PtrRecord(
                            DomainName.Parse(answerDomainName), ttl, DomainName.Parse(answerAddr));
                        recordList.Add(ptrRecord);
                        break;
                    }

                    default:
                    {
                        statusCode = Convert.ToInt32(ReturnCode.ServerFailure);
                        break;
                    }
                    }
                }
            }

            return(recordList, (ReturnCode)statusCode);
        }
Пример #35
0
        private static void WriteDataToLog(Device device, string content, RecordType recordType)
        {
            DateTime now = DateTime.Now;
            FileStream stream = RecordManager.GetLogFileStream(device, now);
            string time = string.Format("[{0:HH:mm:ss}] ", now);
            StringBuilder sb = new StringBuilder(time);
            sb.Append(string.Format(" <{0}> ", recordType.ToString()));
            sb.Append(content);
            sb.Append("\r\n");
            string line = sb.ToString();

            byte[] bytes = Encoding.ASCII.GetBytes(line);
            stream.Write(bytes, 0, bytes.Length);

            // Flush Control.
            if (flushCtrlCount % 10 == 0)
            {
                stream.Flush();
            }
            flushCtrlCount = (flushCtrlCount + 1) % 5;
        }
Пример #36
0
 private static string GetMutexName(string ApplicationName, RecordType recordType)
 {
     return($"{GetConsumerRecordHeaderFileName(ApplicationName)}-{recordType.ToString()}-Mutex");
 }