OPC UA Foundation SDK: Server does not have an instance certificate assigned - c#

I am using the Foundation SDK with C#, trying to launch a simple server in a minimal fashion.
Here is my attempt sofar.
public void StartServer()
{
var config = new ApplicationConfiguration
{
ApplicationName = "TestServer",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier
{
StoreType = #"Windows",
StorePath = #"CurrentUser\My",
SubjectName = Utils.Format(#"CN={0}, DC={1}", "TestServer", Dns.GetHostName())
},
TrustedPeerCertificates = new CertificateTrustList
{
StoreType = #"Windows",
StorePath = #"CurrentUser\TrustedPeople",
},
NonceLength = 32,
AutoAcceptUntrustedCertificates = true,
ConfigureFirewall = false
},
TransportConfigurations = new TransportConfigurationCollection(),
TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
ServerConfiguration = new ServerConfiguration
{
SecurityPolicies = new ServerSecurityPolicyCollection
{
new ServerSecurityPolicy
{
SecurityLevel = 0,
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#None"
}
},
UserTokenPolicies = new UserTokenPolicyCollection
{
new UserTokenPolicy { TokenType = UserTokenType.Anonymous }
},
DiagnosticsEnabled = true,
MaxSessionCount = 100,
MinSessionTimeout = 5000,
MaxSessionTimeout = 10000,
MaxBrowseContinuationPoints = 10,
MaxQueryContinuationPoints = 10,
MaxHistoryContinuationPoints = 100,
MaxRequestAge = 600000,
MinPublishingInterval = 100,
MaxPublishingInterval = 3600000,
PublishingResolution = 50,
MaxSubscriptionLifetime = 3600000,
MaxMessageQueueSize = 10,
MaxNotificationQueueSize = 100,
MaxNotificationsPerPublish = 1000,
MinMetadataSamplingInterval = 1000
}
};
config.Validate(ApplicationType.Server);
var server = new MyCustomServer();
server.Start(config);
}
When I try to call the method, I get the following exception:
Opc.Ua.ServiceResultException: Server does not have an instance certificate assigned.
à Opc.Ua.ServerBase.OnServerStarting(ApplicationConfiguration configuration) dans ...\OPC Foundation\Stack\Core\Stack\Server\ServerBase.cs:ligne 1607
à Opc.Ua.Server.StandardServer.OnServerStarting(ApplicationConfiguration configuration) dans ...\OPC Foundation\SampleApplications\SDK\Server\Server\StandardServer.cs:ligne 2628
à Opc.Ua.ServerBase.Start(ApplicationConfiguration configuration) dans ...\OPC Foundation\Stack\Core\Stack\Server\ServerBase.cs:ligne 232
à SlimFixtures.ServerDriver.StartServer() dans ...\ServerDriver.cs:ligne 71
What am I doing wrong?

So you found that servers based on foundation code always need a certificate.
Creating a self-signed certificate is easy, and does not need Admin login if you are using the Current User/My Windows store.
You can call this extension method after you validate:
config.Validate(ApplicationType.Server);
config.EnsureApplicationCertificate();
elsewhere
public static class ServiceExtensions
{
/// <summary>
/// Ensures the application certificate is present and valid.
/// </summary>
public static void EnsureApplicationCertificate(this ApplicationConfiguration configuration)
{
const ushort keySize = 1024;
const ushort lifetimeInMonths = 300;
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
bool errorFlag = false;
string hostName = Dns.GetHostName();
var serverDomainNames = configuration.GetServerDomainNames();
var applicationCertificate = configuration.SecurityConfiguration.ApplicationCertificate;
var certificate = applicationCertificate.Find(true);
if (certificate != null)
{
// if cert found then check domains
var domainsFromCertficate = Utils.GetDomainsFromCertficate(certificate);
foreach (string serverDomainName in serverDomainNames)
{
if (Utils.FindStringIgnoreCase(domainsFromCertficate, serverDomainName))
{
continue;
}
if (String.Equals(serverDomainName, "localhost", StringComparison.OrdinalIgnoreCase))
{
if (Utils.FindStringIgnoreCase(domainsFromCertficate, hostName))
{
continue;
}
var hostEntry = Dns.GetHostEntry(hostName);
if (hostEntry.Aliases.Any(alias => Utils.FindStringIgnoreCase(domainsFromCertficate, alias)))
{
continue;
}
if (hostEntry.AddressList.Any(ipAddress => Utils.FindStringIgnoreCase(domainsFromCertficate, ipAddress.ToString())))
{
continue;
}
}
Trace.TraceInformation("The application is configured to use domain '{0}' which does not appear in the certificate.", serverDomainName);
errorFlag = true;
} // end for
// if no errors and keySizes match
if (!errorFlag && (keySize == certificate.PublicKey.Key.KeySize))
{
return; // cert okay
}
}
// if we get here then we'll create a new cert
if (certificate == null)
{
certificate = applicationCertificate.Find(false);
if (certificate != null)
{
Trace.TraceInformation("Matching certificate with SubjectName '{0}' found but without a private key.", applicationCertificate.SubjectName);
}
}
// lets check if there is any to delete
if (certificate != null)
{
using (var store2 = applicationCertificate.OpenStore())
{
store2.Delete(certificate.Thumbprint);
}
}
if (serverDomainNames.Count == 0)
{
serverDomainNames.Add(hostName);
}
CertificateFactory.CreateCertificate(applicationCertificate.StoreType, applicationCertificate.StorePath, configuration.ApplicationUri, configuration.ApplicationName, null, serverDomainNames, keySize, lifetimeInMonths);
Trace.TraceInformation("Created new certificate with SubjectName '{0}', in certificate store '{1}'.", applicationCertificate.SubjectName, applicationCertificate.StorePath);
configuration.CertificateValidator.Update(configuration.SecurityConfiguration);
}
}

With a more recent version of the library, there is a built-in option to check the application instance certificate. It's available on the ApplicationInstance class.
Here's how you'd use it:
var applicationConfiguration = new ApplicationConfiguration
{
ApplicationName = "Aggregation server",
...
};
await applicationConfiguration.Validate(ApplicationType.ClientAndServer);
var applicationInstance = new ApplicationInstance(applicationConfiguration);
// This call will check that the application instance certificate exists, and will create it if not
var result =
await applicationInstance.CheckApplicationInstanceCertificate(false, CertificateFactory.DefaultKeySize);
var server = new AggregationServer();
await applicationInstance.Start(server);
System.Console.ReadKey();
server.Stop();

Related

How to fix Amazon.Rekognition.AmazonRekognitionException?

I am getting AmazonRekognitionException as below when trying to run CompareFacesResponse, I am stuck, what should I do or check?
Amazon.Rekognition.AmazonRekognitionException: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details. ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown
AWS credentials access key and secret are checked and correct
public static async Task<Tuple<bool, string>> Rekognition_Compare_Faces(string _source, string _target, string _bucketName)
{
const string HOSTNAME = "https://rekognition.ap-southeast-1.amazonaws.com/";
const string ACCESS_KEY = "my_access_key";
const string ACCESS_SECRET = "my_secret_key";
float _similarityThreshold = 70F;
bool _ret = false;
string _confidence = string.Empty;
try
{
AmazonRekognitionConfig _config = new AmazonRekognitionConfig();
_config.ServiceURL = HOSTNAME + _bucketName;
AmazonRekognitionClient _rekognitionClient = new AmazonRekognitionClient(ACCESS_KEY, ACCESS_SECRET, _config);
Amazon.Rekognition.Model.Image _imageSource = new Amazon.Rekognition.Model.Image();
Amazon.Rekognition.Model.Image _imageTarget = new Amazon.Rekognition.Model.Image();
Amazon.Rekognition.Model.S3Object _s3_source = new Amazon.Rekognition.Model.S3Object { Bucket = _bucketName, Name = _source };
Amazon.Rekognition.Model.S3Object _s3_target = new Amazon.Rekognition.Model.S3Object { Bucket = _bucketName, Name = _target };
CompareFacesRequest _compareFacesRequest = new CompareFacesRequest()
{
SourceImage = new Amazon.Rekognition.Model.Image
{
S3Object = new Amazon.Rekognition.Model.S3Object
{
Bucket = HOSTNAME + _bucketName,
Name = _source
}
},
TargetImage = new Amazon.Rekognition.Model.Image
{
S3Object = new Amazon.Rekognition.Model.S3Object
{
Bucket = HOSTNAME + _bucketName,
Name = _target
}
},
SimilarityThreshold = _similarityThreshold
};
// IT THROWN HERE!!
CompareFacesResponse _compareFacesResponse = await _rekognitionClient.CompareFacesAsync(_compareFacesRequest);
// Display results
foreach (CompareFacesMatch match in _compareFacesResponse.FaceMatches)
{
ComparedFace face = match.Face;
BoundingBox position = face.BoundingBox;
_confidence = match.Similarity.ToString(AppSettings.Decimal_Number_Format) + "%";
_ret = true;
}
}
catch (Exception ex) { await ClsMain.SaveLog("AWS.Compare_Faces: " + ex.ToString()); }
finally { }
return await Task.FromResult(new Tuple<bool, string>(_ret, _confidence));
}
has anybody experience on this?
thanks a lot in advance
Regards
Don
I had the same error.
I tried adding RegionEndpoint = RegionEndpoint.EUWest1 to my AmazonRekognitionConfig so it now looks like this:
var config = new AmazonRekognitionConfig
{
ServiceURL = $"https://rekognition.ap-southeast-1.amazonaws.com/{_awsSettings.BucketName}",
RegionEndpoint = RegionEndpoint.EUWest1
};
var client = new AmazonRekognitionClient(_awsSettings.AccessKey, _awsSettings.Secret, config);
This fixed the problem for me.

OPC UA get specific data type default value

I am working with the OpenSource OPC UA SDK from Microsoft available on GitHub and programming a client with it.
Because of missing documentation, I am struggeling to get custom data types known by the Server into my Client. Also I need them for several method calls e.g. calling "ScanStart" with a paramater from the specific type "ScanSettings" which is only provided by the server. Is it possible to get such a (struct) data type with default values in a simple way?
Does somebody know how and can provide an example?
I found a description of what steps to do, but not how it is done with the Microsoft SDK:
So the client has to
- read the DataTypeDictionaries and parse the value
- browse the address space to map the encoding ids to the structure information
- for binary encoded ExtensionObject: find the structure information from the TypeId and interpret.
Best regards
Below is an sample that calls a method with argument of type "Vector", which is a custom structured type that is provided by UnifiedAutomation's demo server "UaCppServer".
I first used UaExpert to discover the DataTypeId, EncodingId, ObjectId, MethodId, as well as guess the structure.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;
using System.Security.Cryptography.X509Certificates;
namespace NetCoreConsoleClient
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(".Net Core OPC UA Console Client sample");
string endpointURL;
if (args.Length == 0)
{
// use Unified Automation's UaCPPServer server
endpointURL = "opc.tcp://" + Utils.GetHostName() + ":48010";
}
else
{
endpointURL = args[0];
}
try
{
Task t = ConsoleSampleClient(endpointURL);
t.Wait();
}
catch (Exception e)
{
Console.WriteLine("Exit due to Exception: {0}", e.Message);
}
}
public static async Task ConsoleSampleClient(string endpointURL)
{
Console.WriteLine("1 - Create an Application Configuration.");
Utils.SetTraceOutput(Utils.TraceOutput.DebugAndFile);
var config = new ApplicationConfiguration()
{
ApplicationName = "UA Core Sample Client",
ApplicationType = ApplicationType.Client,
ApplicationUri = "urn:" + Utils.GetHostName() + ":OPCFoundation:CoreSampleClient",
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier
{
StoreType = "X509Store",
StorePath = "CurrentUser\\UA_MachineDefault",
SubjectName = "UA Core Sample Client"
},
TrustedPeerCertificates = new CertificateTrustList
{
StoreType = "Directory",
StorePath = "OPC Foundation/CertificateStores/UA Applications",
},
TrustedIssuerCertificates = new CertificateTrustList
{
StoreType = "Directory",
StorePath = "OPC Foundation/CertificateStores/UA Certificate Authorities",
},
RejectedCertificateStore = new CertificateTrustList
{
StoreType = "Directory",
StorePath = "OPC Foundation/CertificateStores/RejectedCertificates",
},
NonceLength = 32,
AutoAcceptUntrustedCertificates = true
},
TransportConfigurations = new TransportConfigurationCollection(),
TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }
};
await config.Validate(ApplicationType.Client);
bool haveAppCertificate = config.SecurityConfiguration.ApplicationCertificate.Certificate != null;
if (!haveAppCertificate)
{
Console.WriteLine(" INFO: Creating new application certificate: {0}", config.ApplicationName);
X509Certificate2 certificate = CertificateFactory.CreateCertificate(
config.SecurityConfiguration.ApplicationCertificate.StoreType,
config.SecurityConfiguration.ApplicationCertificate.StorePath,
null,
config.ApplicationUri,
config.ApplicationName,
config.SecurityConfiguration.ApplicationCertificate.SubjectName,
null,
CertificateFactory.defaultKeySize,
DateTime.UtcNow - TimeSpan.FromDays(1),
CertificateFactory.defaultLifeTime,
CertificateFactory.defaultHashSize,
false,
null,
null
);
config.SecurityConfiguration.ApplicationCertificate.Certificate = certificate;
}
haveAppCertificate = config.SecurityConfiguration.ApplicationCertificate.Certificate != null;
if (haveAppCertificate)
{
config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate);
if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
{
config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
}
}
else
{
Console.WriteLine(" WARN: missing application certificate, using unsecure connection.");
}
Console.WriteLine("2 - Discover endpoints of {0}.", endpointURL);
var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointURL, haveAppCertificate);
Console.WriteLine(" Selected endpoint uses: {0}",
selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1));
Console.WriteLine("3 - Create a session with OPC UA server.");
var endpointConfiguration = EndpointConfiguration.Create(config);
var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);
var session = await Session.Create(config, endpoint, false, ".Net Core OPC UA Console Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null);
Console.WriteLine("4 - Call VectorAdd method with structure arguments.");
EncodeableFactory.GlobalFactory.AddEncodeableType(typeof(Vector));
var v1 = new Vector { X = 1.0, Y = 2.0, Z = 3.0 };
var v2 = new Vector { X = 1.0, Y = 2.0, Z = 3.0 };
var outArgs = session.Call(NodeId.Parse("ns=2;Demo.Method"), NodeId.Parse("ns=2;s=Demo.Method.VectorAdd"), new ExtensionObject(v1), new ExtensionObject(v2) );
var result = ExtensionObject.ToEncodeable((ExtensionObject)outArgs[0]) as Vector;
Console.WriteLine($" {v1}");
Console.WriteLine($"+ {v2}");
Console.WriteLine(#" ------------------");
Console.WriteLine($" {result}");
Console.WriteLine("8 - Press any key to exit...");
Console.ReadKey(true);
}
private static void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e)
{
Console.WriteLine("Accepted Certificate: {0}", e.Certificate.Subject);
e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted);
}
public class Vector : EncodeableObject
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public override ExpandedNodeId TypeId => ExpandedNodeId.Parse("nsu=http://www.unifiedautomation.com/DemoServer/;i=3002");
public override ExpandedNodeId BinaryEncodingId => ExpandedNodeId.Parse("nsu=http://www.unifiedautomation.com/DemoServer/;i=5054");
public override ExpandedNodeId XmlEncodingId => NodeId.Null;
public override void Encode(IEncoder encoder)
{
encoder.WriteDouble("X", this.X);
encoder.WriteDouble("Y", this.Y);
encoder.WriteDouble("Z", this.Z);
}
public override void Decode(IDecoder decoder)
{
this.X = decoder.ReadDouble("X");
this.Y = decoder.ReadDouble("Y");
this.Z = decoder.ReadDouble("Z");
}
public override string ToString() => $"{{ X={this.X}; Y={this.Y}; Z={this.Z}; }}";
}
}
}

CefSharp 3 set proxy at Runtime

I downloaded CEF (chromuim embedded framework) binary distributation that comes with (cefclient & cefsimple) c++ examples, And Realized that cefclient can change proxy settings on run-time.
And the key to do that is to Grab the RequestContext and call the function SetPreference.
on CefClient all works just nice.
but on CefSharp calling SetPreference always returns false, and also HasPreference returns false for the preference name "proxy".
thanks to amaitland the proper way to actively inforce changing the request-context prefrences, is to run the code on CEF UIThread as following:
Cef.UIThreadTaskFactory.StartNew(delegate {
var rc = this.browser.GetBrowser().GetHost().RequestContext;
var v = new Dictionary<string, object>();
v["mode"] = "fixed_servers";
v["server"] = "scheme://host:port";
string error;
bool success = rc.SetPreference("proxy", v, out error);
//success=true,error=""
});
if anyone need any other soulition i found this solution.
Cef.UIThreadTaskFactory.StartNew(delegate
{
string ip = "ip or adress";
string port = "port";
var rc = this.browser.GetBrowser().GetHost().RequestContext;
var dict = new Dictionary<string, object>();
dict.Add("mode", "fixed_servers");
dict.Add("server", "" + ip + ":" + port + "");
string error;
bool success = rc.SetPreference("proxy", dict, out error);
});
I downloaded CefSharp.WinForms 65.0.0 and made class, that can help to start working with proxy:
public class ChromeTest
{
public static ChromiumWebBrowser Create(WebProxy proxy = null, Action<ChromiumWebBrowser> onInited = null)
{
var result = default(ChromiumWebBrowser);
var settings = new CefSettings();
result = new ChromiumWebBrowser("about:blank");
if (proxy != null)
result.RequestHandler = new _requestHandler(proxy?.Credentials as NetworkCredential);
result.IsBrowserInitializedChanged += (s, e) =>
{
if (!e.IsBrowserInitialized)
return;
var br = (ChromiumWebBrowser)s;
if (proxy != null)
{
var v = new Dictionary<string, object>
{
["mode"] = "fixed_servers",
["server"] = $"{proxy.Address.Scheme}://{proxy.Address.Host}:{proxy.Address.Port}"
};
if (!br.GetBrowser().GetHost().RequestContext.SetPreference("proxy", v, out string error))
MessageBox.Show(error);
}
onInited?.Invoke(br);
};
return result;
}
private class _requestHandler : DefaultRequestHandler
{
private NetworkCredential _credential;
public _requestHandler(NetworkCredential credential = null) : base()
{
_credential = credential;
}
public override bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
{
if (isProxy == true)
{
if (_credential == null)
throw new NullReferenceException("credential is null");
callback.Continue(_credential.UserName, _credential.Password);
return true;
}
return false;
}
}
}
Using:
var p = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));
var p1 = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));
var p2 = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));
wb1 = ChromeTest.Create(p1, b => b.Load("http://speed-tester.info/check_ip.php"));
groupBox1.Controls.Add(wb1);
wb1.Dock = DockStyle.Fill;
wb2 = ChromeTest.Create(p2, b => b.Load("http://speed-tester.info/check_ip.php"));
groupBox2.Controls.Add(wb2);
wb2.Dock = DockStyle.Fill;
wb3 = ChromeTest.Create(p, b => b.Load("http://speed-tester.info/check_ip.php"));
groupBox3.Controls.Add(wb3);
wb3.Dock = DockStyle.Fill;
If you want dynamic proxy resolver (proxy hanlder), which allow you to use different proxy for different host - you should:
1) Prepare javascript
var proxy1Str = "PROXY 1.2.3.4:5678";
var proxy2Str = "PROXY 2.3.4.5:6789";
var ProxyPacScript =
$"var proxy1 = \"{(proxy1Str.IsNullOrEmpty() ? "DIRECT" : proxy1Str)}\";" +
$"var proxy2 = \"{(proxy2Str.IsNullOrEmpty() ? "DIRECT" : proxy2Str)}\";" +
#"function FindProxyForURL(url, host) {
if (shExpMatch(host, ""*example.com"")) {
return proxy1;
}
return proxy2;
}";
var bytes = Encoding.UTF8.GetBytes(ProxyPacScript);
var base64 = Convert.ToBase64String(bytes);
2) Set it correctly
var v = new Dictionary<string, object>();
v["mode"] = "pac_script";
v["pac_url"] = "data:application/x-ns-proxy-autoconfig;base64," + base64;
3) Call SetPreference as in accepted answer https://stackoverflow.com/a/36106994/9252162
As result all request to *example.com will flow throught proxy1, all others through proxy2.
To do it I spent all day but with help of source (https://cs.chromium.org/) I found solution. Hope it helps someone.
Main problems:
1) In new version (72 or 74 as I remember) there is no ability to use "file://..." as pac_url.
2) We can't use https://developer.chrome.com/extensions/proxy in cef.. or i can't find how to do it.
p.s. How to use another types of proxy (https, socks) - https://chromium.googlesource.com/chromium/src/+/master/net/docs/proxy.md#evaluating-proxy-lists-proxy-fallback
With the new version of CefSharp, it's quite simple to set proxy:
browser = new ChromiumWebBrowser();
panel1.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
await browser.LoadUrlAsync("about:blank");
await Cef.UIThreadTaskFactory.StartNew(() =>
{
browser.GetBrowser().GetHost().RequestContext.SetProxy("127.0.0.1", 1088, out string _);
});

Google Calendar API, Adding an event to someones calendar just by knowing their e-mail address

I have downloaded the Google.Apis namespace:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
I've spent the entire day looking on the web to see .NET samples about how I can possible add an event to someones calendar just by knowing their e-mail address.
I tried the following code, but it's bringing up errors and it's quite obvious that it isn't going to work:
Public void Method(string email, string text)
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "CLIENTID",
ClientSecret = "CLIENTSECRET",
},
new[] { CalendarService.Scope.Calendar },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
Event event1 = new Event()
{
Summary = "Something",
Location = "Somewhere",
Start = new EventDateTime() {
DateTime = DateTime.Now,
TimeZone = "America/Los_Angeles"
},
End = new EventDateTime() {
DateTime = DateTime.Now,
TimeZone = "America/Los_Angeles"
},
Attendees = new List<EventAttendee>()
{
new EventAttendee() { Email: email } //bringing up an error "Syntax ',' expected
}
};
Event thisevent = service.Events.Insert(event1, "primary").Fetch(); // Another error. "Does not contain a definition for Fetch"
}
Any help is appreciated! Even samples of other code :)
There are syntax errors in the part where you create the event and insert it. Here is a snippet that has correct syntax for the Google API .NET library:
Event myEvent = new Event
{
Summary = "Appointment",
Location = "Somewhere",
Start = new EventDateTime() {
DateTime = new DateTime(2014, 6, 2, 10, 0, 0),
TimeZone = "America/Los_Angeles"
},
End = new EventDateTime() {
DateTime = new DateTime(2014, 6, 2, 10, 30, 0),
TimeZone = "America/Los_Angeles"
},
Recurrence = new String[] {
"RRULE:FREQ=WEEKLY;BYDAY=MO"
},
Attendees = new List<EventAttendee>()
{
new EventAttendee() { Email = "johndoe#gmail.com" }
}
};
Event recurringEvent = service.Events.Insert(myEvent, "primary").Execute();
public static string ApplicationName = "Google Console ApplicationName";
public static string ClientId = "Google Console ClientId";
public static string ClientSecret = "Google Console ClientSecret";
public static string RedirectURL = "Google Console RedirectURL";
public static ClientSecrets GoogleClientSecrets = new ClientSecrets()
{
ClientId = ClientId,
ClientSecret = ClientSecret
};
public static string[] Scopes =
{
CalendarService.Scope.Calendar,
CalendarService.Scope.CalendarReadonly
};
public static UserCredential GetUserCredential(out string error)
{
UserCredential credential = null;
error = string.Empty;
try
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = ClientId,
ClientSecret = ClientSecret
},
Scopes,
Environment.UserName,
CancellationToken.None,
null).Result;
}
catch (Exception ex)
{
credential = null;
error = "Failed to UserCredential Initialization: " + ex.ToString();
}
return credential;
}
public static IAuthorizationCodeFlow GoogleAuthorizationCodeFlow(out string error)
{
IAuthorizationCodeFlow flow = null;
error = string.Empty;
try
{
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = GoogleClientSecrets,
Scopes = Scopes
});
}
catch (Exception ex)
{
flow = null;
error = "Failed to AuthorizationCodeFlow Initialization: " + ex.ToString();
}
return flow;
}
public static UserCredential GetGoogleUserCredentialByRefreshToken(string refreshToken, out string error)
{
TokenResponse respnseToken = null;
UserCredential credential = null;
string flowError;
error = string.Empty;
try
{
// Get a new IAuthorizationCodeFlow instance
IAuthorizationCodeFlow flow = GoogleAuthorizationCodeFlow(out flowError);
respnseToken = new TokenResponse() { RefreshToken = refreshToken };
// Get a new Credential instance
if ((flow != null && string.IsNullOrWhiteSpace(flowError)) && respnseToken != null)
{
credential = new UserCredential(flow, "user", respnseToken);
}
// Get a new Token instance
if (credential != null)
{
bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;
}
// Set the new Token instance
if (credential.Token != null)
{
string newRefreshToken = credential.Token.RefreshToken;
}
}
catch (Exception ex)
{
credential = null;
error = "UserCredential failed: " + ex.ToString();
}
return credential;
}
public static CalendarService GetCalendarService(string refreshToken, out string error)
{
CalendarService calendarService = null;
string credentialError;
error = string.Empty;
try
{
var credential = GetGoogleUserCredentialByRefreshToken(refreshToken, out credentialError);
if (credential != null && string.IsNullOrWhiteSpace(credentialError))
{
calendarService = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
}
}
catch (Exception ex)
{
calendarService = null;
error = "Calendar service failed: " + ex.ToString();
}
return calendarService;
}
public static string AddCalenderEvents(string refreshToken, string emailAddress, string summary, DateTime? start, DateTime? end, out string error)
{
string eventId = string.Empty;
error = string.Empty;
string serviceError;
try
{
var calendarService = GetCalendarService(refreshToken, out serviceError);
if (calendarService != null && string.IsNullOrWhiteSpace(serviceError))
{
var list = calendarService.CalendarList.List().Execute();
var calendar = list.Items.SingleOrDefault(c => c.Summary == emailAddress);
if (calendar != null)
{
Google.Apis.Calendar.v3.Data.Event calenderEvent = new Google.Apis.Calendar.v3.Data.Event();
calenderEvent.Summary = summary;
//calenderEvent.Description = summary;
//calenderEvent.Location = summary;
calenderEvent.Start = new Google.Apis.Calendar.v3.Data.EventDateTime
{
//DateTime = new DateTime(2018, 1, 20, 19, 00, 0)
DateTime = start//,
//TimeZone = "Europe/Istanbul"
};
calenderEvent.End = new Google.Apis.Calendar.v3.Data.EventDateTime
{
//DateTime = new DateTime(2018, 4, 30, 23, 59, 0)
DateTime = start.Value.AddHours(12)//,
//TimeZone = "Europe/Istanbul"
};
calenderEvent.Recurrence = new List<string>();
//Set Remainder
calenderEvent.Reminders = new Google.Apis.Calendar.v3.Data.Event.RemindersData()
{
UseDefault = false,
Overrides = new Google.Apis.Calendar.v3.Data.EventReminder[]
{
new Google.Apis.Calendar.v3.Data.EventReminder() { Method = "email", Minutes = 24 * 60 },
new Google.Apis.Calendar.v3.Data.EventReminder() { Method = "popup", Minutes = 24 * 60 }
}
};
#region Attendees
//Set Attendees
calenderEvent.Attendees = new Google.Apis.Calendar.v3.Data.EventAttendee[] {
new Google.Apis.Calendar.v3.Data.EventAttendee() { Email = "kaptan.cse#gmail.com" },
new Google.Apis.Calendar.v3.Data.EventAttendee() { Email = emailAddress }
};
#endregion
var newEventRequest = calendarService.Events.Insert(calenderEvent, calendar.Id);
newEventRequest.SendNotifications = true;
var eventResult = newEventRequest.Execute();
eventId = eventResult.Id;
}
}
}
catch (Exception ex)
{
eventId = string.Empty;
error = ex.Message;
}
return eventId;
}
public static Google.Apis.Calendar.v3.Data.Event UpdateCalenderEvents(string refreshToken, string emailAddress, string summary, DateTime? start, DateTime? end, string eventId, out string error)
{
Google.Apis.Calendar.v3.Data.Event eventResult = null;
error = string.Empty;
string serviceError;
try
{
var calendarService = GetCalendarService(refreshToken, out serviceError);
if (calendarService != null)
{
var list = calendarService.CalendarList.List().Execute();
var calendar = list.Items.SingleOrDefault(c => c.Summary == emailAddress);
if (calendar != null)
{
// Define parameters of request
EventsResource.ListRequest request = calendarService.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// Get selected event
Google.Apis.Calendar.v3.Data.Events events = request.Execute();
var selectedEvent = events.Items.FirstOrDefault(c => c.Id == eventId);
if (selectedEvent != null)
{
selectedEvent.Summary = summary;
selectedEvent.Start = new Google.Apis.Calendar.v3.Data.EventDateTime
{
DateTime = start
};
selectedEvent.End = new Google.Apis.Calendar.v3.Data.EventDateTime
{
DateTime = start.Value.AddHours(12)
};
selectedEvent.Recurrence = new List<string>();
// Set Remainder
selectedEvent.Reminders = new Google.Apis.Calendar.v3.Data.Event.RemindersData()
{
UseDefault = false,
Overrides = new Google.Apis.Calendar.v3.Data.EventReminder[]
{
new Google.Apis.Calendar.v3.Data.EventReminder() { Method = "email", Minutes = 24 * 60 },
new Google.Apis.Calendar.v3.Data.EventReminder() { Method = "popup", Minutes = 24 * 60 }
}
};
// Set Attendees
selectedEvent.Attendees = new Google.Apis.Calendar.v3.Data.EventAttendee[]
{
new Google.Apis.Calendar.v3.Data.EventAttendee() { Email = "kaptan.cse#gmail.com" },
new Google.Apis.Calendar.v3.Data.EventAttendee() { Email = emailAddress }
};
}
var updateEventRequest = calendarService.Events.Update(selectedEvent, calendar.Id, eventId);
updateEventRequest.SendNotifications = true;
eventResult = updateEventRequest.Execute();
}
}
}
catch (Exception ex)
{
eventResult = null;
error = ex.ToString();
}
return eventResult;
}
public static void DeletCalendarEvents(string refreshToken, string emailAddress, string eventId, out string error)
{
string result = string.Empty;
error = string.Empty;
string serviceError;
try
{
var calendarService = GetCalendarService(refreshToken, out serviceError);
if (calendarService != null)
{
var list = calendarService.CalendarList.List().Execute();
var calendar = list.Items.FirstOrDefault(c => c.Summary == emailAddress);
if (calendar != null)
{
// Define parameters of request
EventsResource.ListRequest request = calendarService.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// Get selected event
Google.Apis.Calendar.v3.Data.Events events = request.Execute();
var selectedEvent = events.Items.FirstOrDefault(c => c.Id == eventId);
if (selectedEvent != null)
{
var deleteEventRequest = calendarService.Events.Delete(calendar.Id, eventId);
deleteEventRequest.SendNotifications = true;
deleteEventRequest.Execute();
}
}
}
}
catch (Exception ex)
{
result = string.Empty;
error = ex.ToString();
}
}
public static void Run()
{
string refreshToken = string.Empty;
string credentialError;
var credential = GetUserCredential(out credentialError);
if (credential != null && string.IsNullOrWhiteSpace(credentialError))
{
//Save RefreshToken into Database
refreshToken = credential.Token.RefreshToken;
}
string addEventError;
string calendarEventId = string.Empty;
calendarEventId = AddCalenderEvents(refreshToken, "kaptan.cse#gmail.com", "My Calendar Event", DateTime.Now, DateTime.Now.AddHours(12), out addEventError);
string updateEventError;
if (!string.IsNullOrEmpty(calendarEventId))
{
UpdateCalenderEvents(refreshToken, "kaptan.cse#gmail.com", "Modified Calendar Event ", DateTime.Now, DateTime.Now.AddDays(1), calendarEventId, out updateEventError);
}
string deleteEventError;
if (!string.IsNullOrEmpty(calendarEventId))
{
DeletCalendarEvents(refreshToken, "kaptan.cse#gmail.com", calendarEventId, out deleteEventError);
}
}
}

PCAP.net RAW DNS query not giving any response

I have create a DNS request using C# and PCAP. I checked the request using the wireshark. but there are not response.
I have compared DNS request which have a response. The flags and DNS query values are same.
I cant figure out why the dns resolver is not sending the response. Please help me.
Thank you.
My packet generating method:
private Packet getPacket(string s, string d,string domain)
{
Random r = new Random();
EthernetLayer ethernetLayer =
new EthernetLayer
{
Source = new MacAddress("00:0C:29:E5:FA:36"),
Destination = new MacAddress("00:0c:29:e5:fa:36"),
EtherType = EthernetType.None, // Will be filled automatically.
};
IpV4Layer ipV4Layer =
new IpV4Layer
{
Source = new IpV4Address(s),
CurrentDestination = new IpV4Address(d),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null, // Will be filled automatically.
Identification = 123,
Options = IpV4Options.None,
Protocol = null, // Will be filled automatically.
Ttl = 100,
TypeOfService = 0,
};
UdpLayer udpLayer =
new UdpLayer
{
SourcePort =ushort.MaxValue,
DestinationPort = 53,
Checksum = null, // Will be filled automatically.
CalculateChecksumValue = true,
};
DnsLayer dnsLayer =
new DnsLayer
{
Id = ushort.Parse(r.Next(0,99999).ToString()),
IsResponse = false,
OpCode = DnsOpCode.Query,
IsAuthoritativeAnswer = false,
IsTruncated = false,
IsRecursionDesired = true,
IsRecursionAvailable = false,
FutureUse = false,
IsAuthenticData = false,
IsCheckingDisabled = false,
ResponseCode = DnsResponseCode.NoError,
Queries = new[]
{
new DnsQueryResourceRecord(new DnsDomainName("col.stc.s-msn.com"),
DnsType.A,
DnsClass.Internet),
},
Answers = null,
Authorities = null,
Additionals = null,
DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
};
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, dnsLayer);
return builder.Build(DateTime.Now);
}
}
This is my packet sending function:
private static void performRequest(LivePacketDevice device)
{
using (PacketCommunicator communicator = device.Open(100,PacketDeviceOpenAttributes.Promiscuous,1000))
{
for (int i = 0; i < threadCount; i++)
{
Thread requester= new Thread(() =>
{
try
{
Program p = new Program();
Random r = new Random();
string resolve = resolvers[r.Next(0, resolvers.Count-1)].ToString();
communicator.SendPacket(p.getPacket(destinationIP.ToString(), resolve, domainName));
p = null;
r = null;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
});
requester.Start();
Thread.Sleep(1000);
}
}
}
I checked your "getPacket" method but have not found obvious problem, so I just tried it, of course, changed mac addresses and IP addresses, I did get response.
But your packet sending method seems wrong, what is the "DestinationIP", it should source IP, in other words, local IP address of the selected device.

Categories