public void Add(DnsRecord[] dnsRecords) { using (ConfigDatabase db = this.Store.CreateContext()) { this.Add(db, dnsRecords); db.SubmitChanges(); } }
public void UpdateDateTest() { DnsRecord target = new DnsRecord(); DateTime expected = new DateTime(); target.UpdateDate = expected; DateTime actual = target.UpdateDate; Assert.Equal(expected, actual); }
public async Task <ActionResult> DeleteRecord(DnsRecord request) { // https://api-docs.dnsmadeeasy.com/ determine record id, if it exists // delete based on zoneid, recordId //https://api.dnsmadeeasy.com/V2.0/dns/managed/1119443/records/66814826 DnsRecord domainInfo = null; try { domainInfo = await DetermineZoneDomainRoot(request.RecordName, request.ZoneId); if (string.IsNullOrEmpty(domainInfo.RootDomain)) { return(new ActionResult { IsSuccess = false, Message = "Failed to determine root domain in zone." }); } } catch (Exception exp) { return(new ActionResult { IsSuccess = false, Message = $"[{ProviderTitle}] Failed to create record: {exp.Message}" }); } var recordName = NormaliseRecordName(domainInfo, request.RecordName); var existingRecords = await GetDnsRecords(request.ZoneId); foreach (var r in existingRecords) { if (r.RecordName == recordName && r.RecordType == request.RecordType) { //delete existing record var url = $"{_apiUrl}dns/managed/{request.ZoneId}/records/{r.RecordId}"; var apiRequest = CreateRequest(HttpMethod.Delete, url, DateTimeOffset.Now); var result = await _httpClient.SendAsync(apiRequest); if (!result.IsSuccessStatusCode) { return(new ActionResult { IsSuccess = false, Message = $"Could not delete dns record {recordName} from zone {request.ZoneId}. Result: {result.StatusCode}" }); } } } return(new ActionResult { IsSuccess = true, Message = $"Dns record deleted: {recordName}" }); }
public void RecordDataTest() { DnsRecord target = new DnsRecord(); byte[] expected = System.Text.Encoding.UTF8.GetBytes("this is just a test"); target.RecordData = expected; byte[] actual = target.RecordData; Assert.Equal(expected, actual); }
public void DomainNameTest() { DnsRecord target = new DnsRecord(); string expected = BuildDomainName(1); target.DomainName = expected; string actual = target.DomainName; Assert.Equal(expected, actual); }
public void RecordIDTest() { DnsRecord target = new DnsRecord(); const long expected = 777; target.ID = expected; long actual = target.ID; Assert.Equal(expected, actual); }
public void TypeIDTest() { DnsRecord target = new DnsRecord(); const int expected = 777; target.TypeID = expected; int actual = target.TypeID; Assert.Equal(expected, actual); }
public void NotesTest() { DnsRecord target = new DnsRecord(); const string expected = "these are some test notes"; target.Notes = expected; string actual = target.Notes; Assert.Equal(expected, actual); }
public void CreateDateTest() { DnsRecord target = new DnsRecord(); DateTime expected = DateTime.UtcNow; target.CreateDate = expected; DateTime actual = target.CreateDate; Assert.Equal(expected, actual); }
public void TestSerialization() { var sut = new DnsRecord(); JsonHelper.GetSerializedKeys(sut).Should().BeEquivalentTo(new SortedSet <string> { "id", "type", "name", "content", "proxiable", "proxied", "priority", "ttl", "locked", "zone_id", "zone_name", "created_on", "modified_on", "data" }); }
public async Task Cleanup(string recordSetName) { DnsRecord acmeChallengeRecord = await GetRecord(recordSetName); if (acmeChallengeRecord != null) { var res = await this.httpClient.DeleteAsync($"{acmeChallengeRecord.record_id}"); res.EnsureSuccessStatusCode(); } }
public void UpdateDnsRecord(DnsRecord dnsRecord) { try { Store.DnsRecords.Update(dnsRecord); } catch (Exception ex) { throw CreateFault("UpdateDnsRecord", ex); } }
private void recordDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex != -1) { DnsRecord record = (DnsRecord)recordDataGridView.Rows[e.RowIndex].DataBoundItem; if (record.PendingAction != ChildPendingAction.Create) { record.PendingAction = ChildPendingAction.Update; } } }
private void addRecord(DnsRecord record) { // Always add to main list even if deleted. recordResultList.Add(record); // Editor could be re-opened after deletion, so only add visible. if (record.PendingAction != ChildPendingAction.Delete) { recordBindingList.Add(record); } }
void Print(DnsRecord dnsRecord) { CommandUI.Print("RecordID", dnsRecord.ID); DnsResourceRecord resourceRecord = dnsRecord.Deserialize(); m_printer.Print(resourceRecord); CommandUI.Print("CreateDate", dnsRecord.CreateDate); CommandUI.Print("UpdateDate", dnsRecord.UpdateDate); CommandUI.Print("Notes", dnsRecord.Notes); }
/// <inheritdoc/> public override void DeleteRecord(DnsRecord record) { var itemIndex = records.IndexOf(record); if (itemIndex < 0) { throw new ArgumentException("Record is not part of this zone"); } records.RemoveAt(itemIndex); }
public async Task UpdateDnsRecordAsync(IPAddress newAddress) { var zoneRequestUri = string.Format(ZoneIdApiEndpointFormat, Options.Zone); Logger.LogDebug("Getting zone."); var zoneResponse = await HttpClient.GetFromJsonAsync <ApiResponse <Zone> >(zoneRequestUri); var zoneId = zoneResponse?.Result?.FirstOrDefault()?.Id; if (zoneId is null) { Logger.LogCritical("Could not locate id for zone."); return; } var dnsRecordRequestUri = string.Format(DnsRecordIdApiEndpointFormat, zoneId, Options.DnsRecord); Logger.LogDebug("Getting current DNS record."); var dnsRecordResponse = await HttpClient.GetFromJsonAsync <ApiResponse <DnsRecord> >(dnsRecordRequestUri); var dnsRecord = dnsRecordResponse?.Result?.FirstOrDefault(); if (dnsRecord is null) { Logger.LogCritical("Could not locate id for DNS record."); return; } var dnsRecordUpdateRequestUri = string.Format(DnsRecordUpdateApiEndpointFormat, zoneId, dnsRecord.Id); var newDnsRecord = new DnsRecord { Id = dnsRecord.Id, Type = dnsRecord.Type, Name = dnsRecord.Name, Content = newAddress.ToString(), Ttl = dnsRecord.Ttl, Proxied = dnsRecord.Proxied }; Logger.LogDebug("Updating DNS record."); var updateResponse = await HttpClient.PutAsJsonAsync(dnsRecordUpdateRequestUri, newDnsRecord); if (updateResponse.IsSuccessStatusCode) { return; } var updateError = await updateResponse.Content.ReadFromJsonAsync <ErrorResponse>(); if (updateError?.Errors is null || updateError.Errors.Count == 0) { var rawResponse = updateResponse.Content.ReadAsStringAsync(); Logger.LogCritical($"Response indicated a failure, but no error message received. Raw response: {rawResponse}", rawResponse); }
public void EnsureCNAME(string[] args) { DnsRecord record = m_parser.ParseCNAME(args); if (!this.VerifyIsUnique(record, false)) { return; } Client.AddDnsRecord(record); }
//private void addSubDomain(String subDomain) //{ // TreeMap<String, String> urlArgs = new TreeMap<>(); // putUrlArg(urlArgs, "domain", subDomain); // // String createResult = createTenAccess("DomainCreate", CVM_REQUEST_ADDR, urlArgs); // // System.out.println(createResult); //} public RestRequestAsyncHandle AddDNSRecord(DnsRecord dnsRecord, Action <IRestResponse <DnsOperatorResult> > callBackActoin) { var urlArgs = new SortedDictionary <string, string>(StringComparer.Ordinal); PutUrlArg(urlArgs, "domain", mTenDnsApiSecret.PrivDomain); PutUrlArg(urlArgs, "subDomain", dnsRecord.Name); PutUrlArg(urlArgs, "recordType", dnsRecord.type); PutUrlArg(urlArgs, "recordLine", dnsRecord.line); PutUrlArg(urlArgs, "value", dnsRecord.Value); return(createTenAccess("RecordCreate", CVM_REQUEST_ADDR, urlArgs, callBackActoin)); }
private async Task <DnsRecord> EnrichRecordByZoneIfRequired(DnsRecord request) { if (string.IsNullOrEmpty(request.ZoneId)) { var zones = await GetZones(); request.ZoneId = zones.Single(z => request.TargetDomainName.Contains(z.Name)).ZoneId; } return(request); }
public static ZoneRecordsResponse ToZoneRecordsResponse(this DnsRecord record, int minimumTTL, string zoneName) { //Declare the result var response = new ZoneRecordsResponse(); //Check that the record is in SDNS format if (!record.RecordName.Contains(zoneName)) { record.RecordName = $"{record.RecordName}.{zoneName}"; } //Build up the response response.Name = record.RecordName; response.Type = record.RecordType.ToString(); //response.Ttl = record.RecordText == null ? minimumTTL : Convert.ToInt32(record.RecordText.Split('\t')[1]); // ReSharper disable once SwitchStatementMissingSomeCases switch (record.RecordType) { case DnsRecordType.MX: if (!record.RecordData.EndsWith(".") && record.RecordData.Length > 0) { response.Data = $"{record.MxPriority} {record.RecordData}."; break; } response.Data = $"{record.MxPriority} {record.RecordData}"; break; case DnsRecordType.SRV: if (!record.RecordData.EndsWith(".") && record.RecordData.Length > 0) { response.Data = $"{record.SrvPriority} {record.SrvWeight} {record.SrvPort} {record.RecordData}."; break; } response.Data = $"{record.SrvPriority} {record.SrvWeight} {record.SrvPort} {record.RecordData}"; break; case DnsRecordType.CNAME: case DnsRecordType.NS: if (!record.RecordData.EndsWith(".") && record.RecordData.Length > 0) { response.Data = $"{record.RecordData}."; break; } response.Data = $"{record.RecordData}"; break; default: response.Data = record.RecordData ?? ""; break; } //Return the response return(response); }
private DnsRecord QueryDns(string lookup, DnsRecord ignored) { if (!string.IsNullOrWhiteSpace(kdc)) { var split = kdc.Split(':'); var record = new DnsRecord { Target = split[0] }; if (split.Length > 1) { record.Port = int.Parse(split[1]); } else { record.Port = DefaultKerberosPort; } return(record); } var results = Query(lookup).Where(r => r.Type == DnsRecordType.SRV); if (ignored != null && ignored.Ignore) { // can get here through expiration, and we don't actually want to negative cache // something that has just expired because it could still genuinely be good negativeCache[ignored.Target] = ignored; } results = results.Where(s => !negativeCache.TryGetValue(s.Target, out DnsRecord record) || record.Expired); var weighted = results.GroupBy(r => r.Weight).OrderBy(r => r.Key).OrderByDescending(r => r.Sum(a => a.Canonical.Count())).FirstOrDefault(); var rand = random.Next(0, weighted?.Count() ?? 0); var srv = weighted?.ElementAtOrDefault(rand); if (srv == null) { throw new KerberosTransportException($"Cannot locate SRV record for {lookup}"); } if (srv.Port <= 0) { srv.Port = DefaultKerberosPort; } return(srv); }
public async Task <ActionResult> DeleteRecord(DnsRecord request) { var zone = await ResolveMatchingZone(request); if (zone != null) { _log?.Information($"Route53 :: Delete Record : Zone matched {zone.Id} {zone.Id} : Fetching TXT record set {request.RecordName} "); var response = await _route53Client.ListResourceRecordSetsAsync( new ListResourceRecordSetsRequest { StartRecordName = request.RecordName, StartRecordType = "TXT", MaxItems = "1", HostedZoneId = zone.Id } ); var targetRecordSet = response.ResourceRecordSets.FirstOrDefault(r => (r.Name == request.RecordName || r.Name == request.RecordName + ".") && r.Type.Value == "TXT"); if (targetRecordSet != null) { _log?.Information($"Route53 :: Delete Record : Fetched TXT record set OK {targetRecordSet.Name} "); try { var result = await ApplyDnsChange(zone, targetRecordSet, ChangeAction.DELETE); return(new ActionResult { IsSuccess = true, Message = $"Dns Record Delete completed: {request.RecordName}" }); } catch (AmazonRoute53Exception exp) { return(new ActionResult { IsSuccess = false, Message = $"Dns Record Delete failed: {request.RecordName} - {exp.Message}" }); } } else { return(new ActionResult { IsSuccess = true, Message = $"Dns Record Delete skipped (record set does not exist): {request.RecordName}" }); } } else { return(new ActionResult { IsSuccess = false, Message = "DNS Zone match could not be determined." }); } }
/// <summary> /// Generic method to add a dns record to the database /// </summary> /// <typeparam name="T">DnsResourceRecord instance to be added</typeparam> /// <param name="path">path to the file to load the binary data from</param> /// <param name="typeID">type id used to identify the type of record being added</param> protected void ImportRecord <T>(string path , int typeID) where T : DnsResourceRecord { DnsRecord dnsRecord = new DnsRecord { TypeID = typeID }; T record = this.LoadAndVerifyDnsRecordFromBin <T>(path); dnsRecord.RecordData = GetBytesFromRecord(record); dnsRecord.DomainName = record.Name; Client.AddDnsRecord(dnsRecord); }
public void CopyFixedTest() { DnsRecord target = new DnsRecord(); DnsRecord source = new DnsRecord { ID = 777, DomainName = BuildDomainName(1), TypeID = 3 }; target.CopyFixed(source); Assert.Equal(777, target.ID); Assert.Equal(BuildDomainName(1), target.DomainName); Assert.Equal(3, target.TypeID); }
public async Task <ActionResult> DeleteRecord(DnsRecord request) { var session = CreateCimSession(); var strQuery = string.Format("SELECT * FROM MicrosoftDNS_TXTType WHERE OwnerName = '{0}' AND DescriptiveText = '{1}'", request.RecordName, request.RecordValue); var txtRecords = session.QueryInstances(@"root\MicrosoftDNS", "WQL", strQuery); foreach (var txtRecord in txtRecords) { session.DeleteInstance(txtRecord); } return(await Task.FromResult(new ActionResult { IsSuccess = true, Message = "DNS record removed." })); }
public void Add(ConfigDatabase db, DnsRecord record) { if (db == null) { throw new ArgumentNullException("db"); } if (record == null) { throw new ConfigStoreException(ConfigStoreError.InvalidDnsRecord); } db.DnsRecords.InsertOnSubmit(record); }
private void recordAddButton_Click(object sender, EventArgs e) { DnsRecord record = new DnsRecord(RhspDataID.Generate()); record.PendingAction = ChildPendingAction.Create; recordResultList.Add(record); recordBindingList.Add(record); recordBindingList.ResetBindings(); selectGridViewRow(recordDataGridView.Rows.Cast <DataGridViewRow>().Last().Index); recordDataGridView.BeginEdit(false); }
//public List<DnsRecord> Lookup //( // string szDomain, // UInt16 dnstype, // UInt32 querytype //) //{ // return HiddenLookup (ref szDomain, dnstype, querytype); //} private List <DnsRecord> HiddenLookup(string domain, DnsTypes dnstype, DnsQueryTypes querytype) { List <DnsRecord> records = null; try { UInt32 queryResultsSet = 0; if ((BypassCache) || (_dnsServer != null)) { querytype |= DnsQueryTypes.BypassCache; } byte[] data = null; if (_dnsServer != null) { data = new Byte [Marshal.SizeOf(typeof(UInt32)) * 2]; var memoryWriter = new BinaryWriter(new MemoryStream(data)); memoryWriter.Write((UInt32)1); byte [] address = _dnsServer.GetAddressBytes(); memoryWriter.Write(address); } uint dnsLookupResult = NativeMethods.DnsQuery(domain, (ushort)dnstype, (uint)querytype, data, ref queryResultsSet, 0); if (dnsLookupResult == 0) { records = new List <DnsRecord> (); var results = new IntPtr(queryResultsSet); do { var response = (ResponseStructure)Marshal.PtrToStructure(results, typeof(ResponseStructure)); DnsRecord newRecord = ResponseDecoder.Decode(results.ToInt32(), ref response); records.Add(newRecord); results = response.next; } while (results.ToInt32() != 0); if (records.Count > 0) { NativeMethods.DnsRecordListFree(ref queryResultsSet, 1); } } } catch (COMException) { } return(records); }
public async Task <ActionResult> CreateRecord(DnsRecord request) { // create or load registration settings var(registration, isNewRegistration) = await Register(_settingsPath, request.TargetDomainName); if (isNewRegistration) { return(new ActionResult { IsSuccess = false, Message = $"[Action Required] To complete setup, add a CNAME record in your DNS pointing {request.RecordName} to {registration.fulldomain} " }); } var req = new HttpRequestMessage(HttpMethod.Post, "/update"); req.Headers.Add("X-Api-User", registration.username); req.Headers.Add("X-Api-Key", registration.password); var update = new { subdomain = registration.subdomain, txt = request.RecordValue }; var json = JsonConvert.SerializeObject(update, _serializerSettings); req.Content = new StringContent(json); var result = await _client.SendAsync(req); try { if (result.IsSuccessStatusCode) { return(new ActionResult { IsSuccess = true, Message = $"acme-dns updated: {request.RecordName} :: {registration.fulldomain}" }); } else { return(new ActionResult { IsSuccess = false, Message = $"acme-dns update failed: Ensure the {request.RecordName} CNAME points to {registration.fulldomain}" }); } } catch (Exception exp) { return(new ActionResult { IsSuccess = false, Message = $"acme-dns update failed: {exp.Message}" }); } }
/// <summary> /// 获取dns记录对象 /// </summary> /// <returns></returns> private DnsRecord GetDnsRecordParams() { var dnsType = DnsTypeListBox.SelectedItem as ListBoxItem; var dnsRecord = new DnsRecord { id = MdnsRecord?.id, Name = TextBlockDomain.Text, type = null == dnsType ? "A" : Convert.ToString(dnsType.Content), line = "默认", Value = TextBlockValue.Text }; return(dnsRecord); }
public void DeleteZoneRecord(string zoneName, DnsRecord record) { try { Log.WriteStart("'{0}' DeleteZoneRecord", ProviderSettings.ProviderName); DnsProvider.DeleteZoneRecord(zoneName, record); Log.WriteEnd("'{0}' DeleteZoneRecord", ProviderSettings.ProviderName); } catch (Exception ex) { Log.WriteError(String.Format("'{0}' DeleteZoneRecord", ProviderSettings.ProviderName), ex); throw; } }
public void Add(ConfigDatabase db , DnsRecord[] dnsRecords) { if (db == null) { throw new ArgumentNullException("db"); } if (dnsRecords == null || dnsRecords.Length.Equals(0)) { return; } foreach (DnsRecord dnsRecord in dnsRecords) { db.DnsRecords.InsertOnSubmit(dnsRecord); } }
public void RemoveDnsRecord(DnsRecord dnsRecord) { Store.DnsRecords.Remove(dnsRecord); }
public void CopyFixedTest() { DnsRecord target = new DnsRecord(); DnsRecord source = new DnsRecord {ID = 777, DomainName = BuildDomainName(1), TypeID = 3}; target.CopyFixed(source); Assert.Equal(777, target.ID); Assert.Equal(BuildDomainName(1), target.DomainName); Assert.Equal(3, target.TypeID); }
public void Update(ConfigDatabase db, DnsRecord dnsRecord) { if (db == null) { throw new ArgumentNullException("db"); } if (dnsRecord == null) { throw new ConfigStoreException(ConfigStoreError.InvalidDnsRecord); } DnsRecord update = Get(db, dnsRecord.ID); update.ApplyChanges(dnsRecord); }
public void Update(DnsRecord dnsRecord) { using (ConfigDatabase db = this.Store.CreateContext()) { Update(db, dnsRecord); db.SubmitChanges(); } }
/// <summary> /// simple method to remove an dns record by ID /// </summary> /// <param name="db">database context to use</param> /// <param name="dnsRecord">DnsRecord instance to be removed</param> public void Remove(ConfigDatabase db , DnsRecord dnsRecord) { db.DnsRecords.DeleteOnSubmit(dnsRecord); }
public void AddDnsRecords(DnsRecord[] dnsRecords) { Store.DnsRecords.Add(dnsRecords); }
public void ApplyChangesTest() { DnsRecord target = new DnsRecord(); DnsRecord source = new DnsRecord(); DateTime update = DateTimeHelper.Now; byte[] bytes = System.Text.Encoding.UTF8.GetBytes("test this"); source.RecordData = bytes; source.Notes = "some notes here"; source.UpdateDate = update; target.ApplyChanges(source); Assert.Equal(bytes, target.RecordData); Assert.Equal("some notes here", target.Notes); Assert.True(update <= target.UpdateDate ); }
public void Delete(DnsRecord record) { Client.RemoveDnsRecordByID(record.ID); }
public DnsRecord Update(DnsRecord address) { Client.UpdateDnsRecord(address); address.UpdateDate = DateTimeHelper.Now; return address; }
public DnsRecord Add(DnsRecord record) { return Client.AddDnsRecord(record); }
public void ValidateHasDataTest() { DnsRecord target = new DnsRecord(); bool failed; try{ target.ValidateHasData(); failed = false; }catch{ failed = true; } Assert.True(failed); try{ target.RecordData = System.Text.Encoding.UTF8.GetBytes("this is some test string"); target.ValidateHasData(); failed = false; }catch{ failed = true; } Assert.False(failed); }
public DnsRecord AddDnsRecord(DnsRecord record) { Store.DnsRecords.Add(record); return record; }
/// <summary> /// simple method to remove an dns record by ID /// </summary> /// <param name="dnsRecord">DnsRecord instance to be removed</param> public void Remove(DnsRecord dnsRecord) { using (ConfigDatabase db = Store.CreateContext()) { db.DnsRecords.Attach(dnsRecord); this.Remove(db , dnsRecord); } }