Refactored to .NET 5.0

This commit is contained in:
Imre Kincses 2023-03-17 15:09:54 +01:00
commit 26861a5f99
4 changed files with 387 additions and 0 deletions

175
.gitignore vendored Normal file
View File

@ -0,0 +1,175 @@
#################
## Customer
#################
_ReSharper*
TestResults
#################
## Eclipse
#################
*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
#################
## Visual Studio
#################
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.vspscc
.builds
*.dotCover
.[vV][sS]/
.[nN]uget/
## TODO: If you have NuGet Package Restore enabled, uncomment this
packages/
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
# Visual Studio profiler
*.psess
*.vsp
# ReSharper is a .NET coding add-in
_ReSharper*
# Installshield output folder
[Ee]xpress
#azure
*.PublishSettings
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish
# Others
[Bb]in
[Oo]bj
sql
TestResults
*.Cache
ClientBin
stylecop.*
~$*
*.dbmdl
Generated_Code #added for RIA/Silverlight projects
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
############
## Windows
############
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
#############
## Python
#############
*.py[co]
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg
# Mac crap
.DS_Store

24
GodaddyApi.csproj Normal file
View File

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<AssemblyTitle>This is a simple API solution for handling your GoDaddy DNS records</AssemblyTitle>
<AssemblyCompany>Iminetsoft</AssemblyCompany>
<AssemblyVersion>1.2.0</AssemblyVersion>
<Product>GodaddyApi.Net</Product>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.2.0</Version>
<Deterministic>false</Deterministic>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
<PackageId>Iminetsoft.GodaddyApiNet</PackageId>
<PackageProjectUrl>https://github.com/iminet/GodaddyApi.Net</PackageProjectUrl>
<RepositoryUrl>https://github.com/iminet/GodaddyApi.Net</RepositoryUrl>
<PackageTags>dotnet dns godaddy</PackageTags>
<AssemblyVersion>1.2.0</AssemblyVersion>
<FileVersion>1.2.0</FileVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>

25
GodaddyApi.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.33027.164
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GodaddyApi", "GodaddyApi.csproj", "{400225B2-093F-42C4-A828-1E71AD5E3EF0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{400225B2-093F-42C4-A828-1E71AD5E3EF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{400225B2-093F-42C4-A828-1E71AD5E3EF0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{400225B2-093F-42C4-A828-1E71AD5E3EF0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{400225B2-093F-42C4-A828-1E71AD5E3EF0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A0B37328-B968-49AD-8C80-78D7752FFE63}
EndGlobalSection
EndGlobal

163
Iminetsoft.Godaddy.cs Normal file
View File

@ -0,0 +1,163 @@
using System;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Iminetsoft
{
/// <summary>
/// Simple and fast GoDaddy (godaddy.com) API
/// You might need a developer key and secret code first! In this case, visit https://developer.godaddy.com/keys
/// <description>Developed and maintained by Iminetsoft | Version: 0.1 | Date: 17.01.2021</description>
/// </summary>
public class Godaddy
{
public enum RecordTypes { A, Nameserver, CNAME, MX, TXT, SRV, AAA, CAA }
public enum StatusCodes { OK = 0, EmptyResponse = 1, RequestMalformed = 400, AuthInvalid = 401, Unauthorized = 403, NotFound = 404, ProcessInvalid = 422, ProcessTimeout = 429, InternalError = 500, GatewayTimeout = 504 }
public string Domain { get; set; } = String.Empty;
public RecordTypes Type { get; set; } = RecordTypes.A;
public string Name { get; set; } = String.Empty;
public int Ttl { get; set; } = 3600;
public int Port { get; set; } = 1;
public int Weight { get; set; } = 0;
public string Key { private get; set; } = String.Empty;
public string Secret { private get; set; } = String.Empty;
public string Data { get; set; } = String.Empty;
public int Priority { get; set; } = 0;
public string UserAgent { get; set; } = "Iminetsoft.Godaddy.Net";
public Dictionary<string, string> ResponseHeaders { get; private set; } = new Dictionary<string, string>();
public string ExceptionMessage { private set; get; } = String.Empty;
public StatusCodes StatusCode = StatusCodes.EmptyResponse;
public Godaddy() { }
public Godaddy(string domain, string name, RecordTypes type, int ttl, string key, string secret)
{
Domain = (domain.Length > 0 ? domain.Trim() : Domain);
Name = (name.Length > 0 ? name.Trim() : Name);
Type = type;
Ttl = (ttl >= 10 && ttl <= 3600 ? ttl : Ttl);
Key = (key.Length > 0 ? key.Trim() : Key);
Secret = (secret.Length > 0 ? secret.Trim() : Secret);
}
/// <summary>
/// Gets the current data of the specified domain and DNS record
/// </summary>
/// <returns></returns>
public bool GetDnsRecord()
{
GetSetDnsRecord();
return (StatusCode == StatusCodes.OK ? true : false);
}
/// <summary>
/// Gets the current IP/hostname of the specified domain and DNS record, typed A
/// </summary>
/// <returns></returns>
public string GetDnsRecordString()
{
GetSetDnsRecord();
return (StatusCode == StatusCodes.OK ? Data : "");
}
/// <summary>
/// Creates or updates the specified DNS record
/// </summary>
/// <returns></returns>
public bool SetDnsRecord()
{
GetSetDnsRecord(true);
return (StatusCode == StatusCodes.OK ? true : false);
}
private void GetSetDnsRecord(bool UpdateData = false)
{
string HtmlContent = String.Empty;
string apiurl = $"https://api.godaddy.com/v1/domains/{Domain}/records/{Type.ToString()}/{Name}";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpWebRequest webreq = (HttpWebRequest)System.Net.WebRequest.Create(apiurl);
webreq.Headers.Add("Authorization", $"sso-key {Key}:{Secret}");
webreq.ContentType = "application/json";
webreq.Accept = "application/json";
webreq.UserAgent = UserAgent;
if (UpdateData == true && RecordToJson().Length > 0)
{
webreq.Method = "PUT";
webreq.ContentLength = RecordToJson().Length;
using (var writer = new StreamWriter(webreq.GetRequestStream()))
{
writer.Write(RecordToJson());
}
}
else webreq.Method = "GET";
try
{
HttpWebResponse WebResponse = (HttpWebResponse)webreq.GetResponse();
Stream responseStream = responseStream = WebResponse.GetResponseStream();
StreamReader Reader = new StreamReader(responseStream, Encoding.Default);
HtmlContent = Reader.ReadToEnd();
ResponseHeaders.Clear();
foreach (string headkey in WebResponse.Headers.AllKeys)
{
ResponseHeaders.Add(headkey, WebResponse.Headers[headkey]);
}
if (WebResponse.StatusCode == HttpStatusCode.OK && HtmlContent.Length > 0)
{
dynamic jsondata = JsonConvert.DeserializeObject(HtmlContent);
if (jsondata != null && jsondata.Count != null && jsondata.Count > 0 && jsondata[0] != null)
{
if (jsondata[0].data != null) Data = jsondata[0].data.ToString().Trim();
if (jsondata[0].name != null) Name = jsondata[0].name.ToString().Trim();
if (jsondata[0].ttl != null) Ttl = jsondata[0].ttl;
if (jsondata[0].type != null) Type = (RecordTypes)System.Enum.Parse(typeof(RecordTypes), jsondata[0].type.ToString().Trim()); //jsondata[0].type.ToString().Trim();
StatusCode = StatusCodes.OK;
}
else StatusCode = StatusCodes.EmptyResponse;
}
else StatusCode = StatusCodes.EmptyResponse;
WebResponse.Close();
responseStream.Close();
}
catch (Exception e)
{
ExceptionMessage = e.Message;
StatusCode = StatusCodes.EmptyResponse;
}
}
/// <summary>
/// Current record export in JSON format - this needs primarly to create/update your DNS record
/// </summary>
/// <returns></returns>
public string RecordToJson()
{
Dictionary<string, object> pushrecord = new Dictionary<string, object>()
{
{ "data", Data },
{ "name", Name },
{ "ttl", Ttl },
{ "type", Type.ToString() },
{ "port", Port },
{ "priority", Priority },
{ "protocol", "string" },
{ "service", "string" },
{ "weight", Weight },
};
return JsonConvert.SerializeObject(new object[1] { pushrecord });
}
}
}