public Cx9020()
        {
            _spsClient = JsonConvert.DeserializeObject <IpAdressen>(File.ReadAllText("IpAdressen.json"));
            _adsClient = new AdsClient();

            System.Threading.Tasks.Task.Run(SPS_Pingen_TaskAsync);
        }
        public void LoadSymbols()
        {
            try
            {
                using (var adsClient = new AdsClient())
                {
                    // connection
                    adsClient.Connect(new AmsAddress(_appOptions.Value.AMSNetId, _appOptions.Value.Port));

                    // get the symbol loader, FLAT mode
                    var symbolLoader = SymbolLoaderFactory.Create(adsClient, new SymbolLoaderSettings(SymbolsLoadMode.Flat));

                    if (symbolLoader != null)
                    {
                        _symbolCollection = symbolLoader.Symbols;
                        SymbolInfos       = new BindableCollection <ISymbol>(_symbolCollection);
                        NotifyOfPropertyChange(() => SymbolInfos);
                    }
                }
            }
            catch (ObjectDisposedException exDisposed)
            {
                Console.WriteLine("exception\n" + exDisposed.Message);
            }
            catch (InvalidOperationException exInvalid)
            {
                Console.WriteLine("exception\n" + exInvalid.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Undentified exception\n" + ex.Message);
            }
        }
Exemple #3
0
        private static void ReadSingleVariable(AdsClient client)
        {
            var symbol = client.CreateVariableHandle("KLEMME 4 (EL3204).RTD INPUTS CHANNEL 1");

            var buffer = new Memory <byte>(new byte[4]);
            var value  = client.Read(symbol, buffer);
        }
Exemple #4
0
        /// <summary>
        /// Sets the request header namespace in outgoing Soap Requests.
        /// </summary>
        /// <param name="signature">The service creation parameters.</param>
        /// <param name="service">The service object for which RequestHeader
        /// needs to be patched.</param>
        private static void SetRequestHeaderNameSpace(DfaServiceSignature signature,
                                                      AdsClient service)
        {
            // Set the header namespace prefix. For all /cm services, the members
            // shouldn't have xmlns. For all other services, the members should have
            // /cm as xmlns.
            object[] attributes = service.GetType().GetCustomAttributes(false);
            foreach (object attribute in attributes)
            {
                if (attribute is WebServiceBindingAttribute)
                {
                    WebServiceBindingAttribute binding = (WebServiceBindingAttribute)attribute;

                    string        xmlns            = binding.Namespace;
                    RequestHeader svcRequestHeader = null;
                    PropertyInfo  propInfo         = service.GetType().GetProperty("RequestHeader");
                    if (propInfo != null)
                    {
                        svcRequestHeader = (RequestHeader)propInfo.GetValue(service, null);

                        if (svcRequestHeader != null)
                        {
                            PropertyInfo wsPropInfo = svcRequestHeader.GetType().GetProperty("TargetNamespace");
                            if (wsPropInfo != null)
                            {
                                wsPropInfo.SetValue(svcRequestHeader, xmlns, null);
                            }
                        }
                    }
                }
            }
        }
        public void GetSymhandleByNameAsync()
        {
            var amsTestSocket = new AmsSocketTest();

            amsTestSocket.SendMessage = new byte[] {
                0, 0, 58, 0, 0, 0, 5, 1, 204, 123, 1, 1, 33, 3, 10, 0, 0, 120,
                1, 1, 137, 128, 9, 0, 4, 0, 26, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
                3, 240, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 10, 0, 0, 0, 46, 84, 69, 83,
                84, 84, 73, 77, 69, 0
            };

            amsTestSocket.ReceiveMessage = new byte[] {
                0, 0, 44, 0, 0, 0, 10, 0, 0, 120, 1, 1, 137, 128, 5, 1, 204, 123,
                1, 1, 33, 3, 9, 0, 5, 0, 12, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
                0, 4, 0, 0, 0, 141, 2, 0, 164
            };

            using (AdsClient client = new AdsClient(
                       amsNetIdSource: "10.0.0.120.1.1",
                       amsSocket: amsTestSocket,
                       amsNetIdTarget: "5.1.204.123.1.1"))
            {
                var task = client.GetSymhandleByNameAsync(".TESTTIME");
                task.Wait(5000);
                var handle = task.Result;
                Assert.AreEqual(handle, 2751464077);
            }
        }
        public void GetSymhandleByName()
        {
            var amsTestSocket = new AmsSocketTest();
            amsTestSocket.SendMessage = new byte[] {
                    0,0,58,0,0,0,5,1,204,123,1,1,33,3,10,0,0,120,
                    1,1,137,128,9,0,4,0,26,0,0,0,0,0,0,0,1,0,0,0,
                    3,240,0,0,0,0,0,0,4,0,0,0,10,0,0,0,46,84,69,83,
                    84,84,73,77,69,0};

            amsTestSocket.ReceiveMessage = new byte[] {
                    0,0,44,0,0,0,10,0,0,120,1,1,137,128,5,1,204,123,
                    1,1,33,3,9,0,5,0,12,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
                    0,4,0,0,0,141,2,0,164};

            using (AdsClient client = new AdsClient(
                    amsNetIdSource: "10.0.0.120.1.1",
                    amsSocket: amsTestSocket,
                    amsNetIdTarget: "5.1.204.123.1.1"))
            {
                uint handle = client.GetSymhandleByName(".TESTTIME");
                Assert.AreEqual(handle, 2751464077);

                //Symhandle release
                amsTestSocket.SendMessage = new byte[] {
                    0,0,48,0,0,0,5,1,204,123,1,1,33,3,10,0,0,120,1,1,137,
                    128,3,0,4,0,16,0,0,0,0,0,0,0,2,0,0,0,6,240,0,0,0,0,0,
                    0,4,0,0,0,141,2,0,164};

                amsTestSocket.ReceiveMessage = new byte[] {
                     0,0,36,0,0,0,5,1,204,123,1,1,137,128,5,1,204,123,1,1,
                     33,3,3,0,5,0,4,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0};

            }
        }
Exemple #7
0
        public static async Task <IEnumerable <Function> > ListFunctionsAsync(AmsNetId target, CancellationToken cancel)
        {
            var functions = new List <Function>();

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));

                foreach (var key in RegistryDefinitions.Keys)
                {
                    try
                    {
                        var name   = RegistryDefinitions[key];
                        var regKey = @"SOFTWARE\WOW6432Node\Beckhoff\TwinCAT3 Functions\" + name + @"\Common";

                        var version = await Registry.QueryValueAsync(target, regKey, "Version");

                        functions.Add(new Function
                        {
                            Name    = name,
                            Version = System.Version.Parse(version),
                            Type    = key
                        });
                    }
                    catch { }
                }
            }

            return(functions);
        }
        public void GetSymhandleByNameAsync()
        {
            var amsTestSocket = new AmsSocketTest();
            amsTestSocket.SendMessage = new byte[] {
                    0,0,58,0,0,0,5,1,204,123,1,1,33,3,10,0,0,120,
                    1,1,137,128,9,0,4,0,26,0,0,0,0,0,0,0,1,0,0,0,
                    3,240,0,0,0,0,0,0,4,0,0,0,10,0,0,0,46,84,69,83,
                    84,84,73,77,69,0};

            amsTestSocket.ReceiveMessage = new byte[] { 
                    0,0,44,0,0,0,10,0,0,120,1,1,137,128,5,1,204,123,
                    1,1,33,3,9,0,5,0,12,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
                    0,4,0,0,0,141,2,0,164};

            using (AdsClient client = new AdsClient(
                    amsNetIdSource: "10.0.0.120.1.1",
                    amsSocket: amsTestSocket,
                    amsNetIdTarget: "5.1.204.123.1.1"))
            {
                var task = client.GetSymhandleByNameAsync(".TESTTIME");
                task.Wait(5000);
                var handle = task.Result;
                Assert.AreEqual(handle, 2751464077);
            }
        }
Exemple #9
0
        /// <summary>
        /// Generates a login token for authenticating DFA API calls.
        /// </summary>
        /// <param name="user">The user for which token is generated.</param>
        /// <param name="serviceVersion">The service version.</param>
        /// <returns>A token which may be used for future API calls.</returns>
        private static UserToken GenerateAuthenticationToken(AdsUser user, string serviceVersion)
        {
            DfaAppConfig config = (DfaAppConfig)user.Config;

            if (!String.IsNullOrEmpty(config.DfaAuthToken))
            {
                return(new UserToken(config.DfaUserName, config.DfaAuthToken));
            }
            if (config.AuthorizationMethod == DfaAuthorizationMethod.LoginService)
            {
                if (string.IsNullOrEmpty(config.DfaUserName))
                {
                    throw new ArgumentNullException(DfaErrorMessages.UserNameCannotBeEmpty);
                }
                if (string.IsNullOrEmpty(config.DfaPassword))
                {
                    throw new ArgumentNullException(DfaErrorMessages.PasswordCannotBeEmpty);
                }
            }
            try {
                DfaServiceSignature loginServiceSignature = new DfaServiceSignature(serviceVersion,
                                                                                    "LoginRemoteService");
                AdsClient loginService = user.GetService(loginServiceSignature, config.DfaApiServer);
                object    userProfile  = loginService.GetType().GetMethod("authenticate").Invoke(
                    loginService, new object[] { config.DfaUserName, config.DfaPassword });
                return(new UserToken(
                           userProfile.GetType().GetProperty("name").GetValue(userProfile, null).ToString(),
                           userProfile.GetType().GetProperty("token").GetValue(userProfile, null).ToString()));
            } catch (Exception ex) {
                throw new DfaException("Failed to authenticate user. See inner exception for details.", ex);
            }
        }
        /// <summary>
        /// Performs the SOAP and HTTP logging.
        /// </summary>
        /// <param name="service">The SOAP service.</param>
        /// <param name="soapResponse">The SOAP response xml.</param>
        /// <param name="soapRequest">The SOAP request xml.</param>
        private void PerformLogging(AdsClient service, string soapRequest, string soapResponse)
        {
            if (service == null || service.User == null || soapRequest == null || soapResponse == null)
            {
                return;
            }

            if (config.MaskCredentials)
            {
                XmlDocument xDoc = SerializationUtilities.LoadXml(soapRequest);
                MaskCredentialsInLogs(xDoc, GetFieldsToMask());
                soapRequest = xDoc.OuterXml;
            }

            string formattedSoapRequest  = FormatSoapRequest(service.LastRequest, soapRequest);
            string formattedSoapResponse = FormatSoapResponse(service.LastResponse, soapResponse);
            string formattedHttpRequest  = FormatHttpRequest(soapRequest);
            string formattedHttpResponse = FormatHttpResponse(soapResponse);

            string soapLog    = formattedSoapRequest + formattedSoapResponse;
            string requestLog = string.Format(CultureInfo.InvariantCulture, "host={0},url={1},{2},{3}",
                                              service.LastRequest.RequestUri.Host, service.LastRequest.RequestUri.AbsolutePath,
                                              formattedHttpRequest, formattedHttpResponse);

            ContextStore.AddKey("FormattedSoapLog", soapLog);
            ContextStore.AddKey("FormattedRequestLog", requestLog);

            bool isError = service.LastResponse != null && service.LastResponse is HttpWebResponse &&
                           (service.LastResponse as HttpWebResponse).StatusCode ==
                           HttpStatusCode.InternalServerError;

            TraceUtilities.WriteSoapXmlLogs(soapLog, isError);
            TraceUtilities.WriteRequestInfoLogs(requestLog, isError);
        }
        public void ReadStateAsync()
        {
            var amsTestSocket = new AmsSocketTest();

            amsTestSocket.SendMessage = new byte[] {
                0, 0, 32, 0, 0, 0, 5, 1, 204, 123, 1, 1, 33, 3, 10, 0, 0, 120,
                1, 1, 137, 128, 4, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0
            };

            amsTestSocket.ReceiveMessage = new byte[] {
                0, 0, 40, 0, 0, 0, 10, 0, 0, 120, 1, 1, 137, 128, 5, 1, 204, 123, 1, 1,
                33, 3, 4, 0, 5, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0
            };

            using (AdsClient client = new AdsClient(
                       amsNetIdSource: "10.0.0.120.1.1",
                       amsSocket: amsTestSocket,
                       amsNetIdTarget: "5.1.204.123.1.1"))
            {
                var task = client.ReadStateAsync();
                task.Wait(5000);
                var state = task.Result;
                Assert.AreEqual(state.ToString(), "Ads state: 5 (Run) Device state: 0");
            }
        }
        public void ReadDeviceInfoAsync()
        {
            var amsTestSocket = new AmsSocketTest();

            amsTestSocket.SendMessage = new byte[] {
                0, 0, 32, 0, 0, 0, 5, 1, 204, 123, 1, 1, 33, 3, 10, 0, 0,
                120, 1, 1, 137, 128, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0
            };

            amsTestSocket.ReceiveMessage = new byte[] {
                0, 0, 56, 0, 0, 0, 10, 0, 0, 120, 1, 1, 137, 128, 5, 1, 204, 123,
                1, 1, 33, 3, 1, 0, 5, 0, 24, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
                0, 2, 11, 234, 5, 84, 67, 97, 116, 80, 108, 99, 67, 116, 114, 108, 0, 0, 0, 0, 0
            };

            using (AdsClient client = new AdsClient(
                       amsNetIdSource: "10.0.0.120.1.1",
                       amsSocket: amsTestSocket,
                       amsNetIdTarget: "5.1.204.123.1.1"))
            {
                var task = client.ReadDeviceInfoAsync();
                task.Wait(5000);
                AdsDeviceInfo deviceInfo = task.Result;
                Assert.AreEqual(deviceInfo.ToString(), "Version: 2.11.1514 Devicename: TCatPlcCtrl");
            }
        }
        /// <summary>
        /// Handles the message.
        /// </summary>
        /// <param name="soapMessage">The SOAP message.</param>
        /// <param name="service">The service.</param>
        /// <param name="direction">The direction.</param>
        public void HandleMessage(XmlDocument soapMessage, AdsClient service,
                                  SoapMessageDirection direction)
        {
            XmlNamespaceManager xmlnt = new XmlNamespaceManager(soapMessage.NameTable);

            xmlnt.AddNamespace(SOAP_PREFIX, SOAP_NAMESPACE);
            if (direction == SoapMessageDirection.OUT)
            {
                UserToken     token         = (UserToken)ContextStore.GetValue("Token");
                RequestHeader requestHeader = (RequestHeader)ContextStore.GetValue("RequestHeader");

                if (token != null || requestHeader != null)
                {
                    XmlElement soapHeader = GetSoapHeaderNode(soapMessage, xmlnt, true);

                    if (token != null)
                    {
                        AddSecurityHeader(soapHeader, token);
                    }
                    if (requestHeader != null)
                    {
                        AddRequestHeader(soapHeader, requestHeader);
                    }
                }
            }
            else
            {
                ContextStore.AddKey("ResponseHeader", ParseResponseHeader(soapMessage, xmlnt));
            }
        }
Exemple #14
0
 public static void Restart(AmsNetId target)
 {
     using (AdsClient client = new AdsClient())
     {
         client.Connect(new AmsAddress(target, AmsPort.SystemService));
         client.WriteControl(new StateInfo(AdsState.Reset, 0));
     }
 }
Exemple #15
0
 public static async Task RestartAsync(AmsNetId target, CancellationToken cancel)
 {
     using (AdsClient client = new AdsClient())
     {
         client.Connect(new AmsAddress(target, AmsPort.SystemService));
         await client.WriteControlAsync(AdsState.Reset, 0, cancel);
     }
 }
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         _adsClient?.Dispose();
         _adsClient = null;
     }
 }
 /// <summary>
 /// Calls the SOAP listeners.
 /// </summary>
 /// <param name="document">The SOAP message as an xml document.</param>
 /// <param name="service">The service for which call is being made.</param>
 /// <param name="direction">The direction of SOAP message.</param>
 internal void CallListeners(XmlDocument document, AdsClient service,
                             SoapMessageDirection direction)
 {
     foreach (SoapListener listener in listeners)
     {
         listener.HandleMessage(document, service, direction);
     }
 }
 public void TestCreateServices()
 {
     StubIntegrityTestHelper.EnumerateServices <DfpService>(
         delegate(ServiceSignature serviceSignature) {
         Assert.DoesNotThrow(delegate() {
             AdsClient service = user.GetService(serviceSignature);
         });
     });
 }
Exemple #19
0
        private static void PrintSymbols(AdsClient client)
        {
            SymbolLoaderSettings settings = new SymbolLoaderSettings(TwinCAT.SymbolsLoadMode.VirtualTree);
            ISymbolLoader        loader   = SymbolLoaderFactory.Create(client, settings);

            var symbols = loader.Symbols;

            PrintSymbols(symbols);
        }
Exemple #20
0
 /// <summary>
 /// Handles the SOAP message.
 /// </summary>
 /// <param name="soapMessage">The SOAP message.</param>
 /// <param name="service">The SOAP service.</param>
 /// <param name="direction">The direction of message.</param>
 public void HandleMessage(XmlDocument soapMessage, AdsClient service,
                           SoapMessageDirection direction)
 {
     if (direction == SoapMessageDirection.IN)
     {
         AdWordsUser user       = service.User as AdWordsUser;
         string      methodName = (string)ContextStore.GetValue("SoapMethod");
         RecordApiOperationCount(user, service, methodName, GetApiUnitsForCall(soapMessage));
     }
 }
        private void Initialize()
        {
            _adsClient = new AdsClient();
            _adsClient.Connect(Target, AmsPort.SystemService);

            if (!_adsClient.IsConnected)
            {
                throw new Exception("Could not connect to target " + Target.ToString());
            }
        }
 /// <summary>
 /// Records API operation count for a user.
 /// </summary>
 /// <param name="user">The AdWords user who made the call.</param>
 /// <param name="service">The AdWords API service that was called.</param>
 /// <param name="methodName">The name of the method that was called.</param>
 /// <param name="operationCount">The number of API operations for the
 /// current call.</param>
 private static void RecordApiOperationCount(AdWordsUser user, AdsClient service,
     string methodName, int operationCount) {
   if (user != null) {
     ApiCallEntry entry = new ApiCallEntry();
     entry.Service = service;
     entry.Method = methodName;
     entry.OperationCount = operationCount;
     user.AddCallDetails(entry);
   }
 }
Exemple #23
0
        public static IDisposable GetTypedBeckhoffNotification(this AdsClient beckhoff, ISymbol symbol, Type type, IPlc plc, string address, TimeSpan regularTransmissionCycle)
        {
            if (type == typeof(byte[]))
            {
                return(Observable.Timer(TimeSpan.FromMilliseconds(100), regularTransmissionCycle)
                       .Select(_ => beckhoff.ReadVariable <byte[]>(symbol))
                       .Do(value => Log.Logger.Debug($"Writing {symbol.InstancePath} to {address}: {ByteToString(value)}"))
                       .SelectMany(value => plc.Write(address, value))
                       .Retry()
                       .Subscribe());
            }

            var typecode = Type.GetTypeCode(type);

            switch (typecode)
            {
            case TypeCode.Boolean:
                return(beckhoff.WhenNotification <bool>(symbol.InstancePath, NotificationSettings.Default)
                       .SelectMany(value => plc.Write(address, value))
                       .Subscribe());

            case TypeCode.Char:
            case TypeCode.SByte:
            case TypeCode.Byte:
                return(beckhoff.WhenNotification <byte>(symbol.InstancePath, NotificationSettings.Default)
                       .SelectMany(value => plc.Write(address, value))
                       .Subscribe());

            case TypeCode.Int16:
            case TypeCode.UInt16:
                return(beckhoff.WhenNotification <short>(symbol.InstancePath, NotificationSettings.Default)
                       .SelectMany(value => plc.Write(address, value))
                       .Subscribe());

            case TypeCode.Int32:
            case TypeCode.UInt32:
                return(beckhoff.WhenNotification <int>(symbol.InstancePath, NotificationSettings.Default)
                       .SelectMany(value => plc.Write(address, value))
                       .Subscribe());

            case TypeCode.Int64:
            case TypeCode.UInt64:
                return(beckhoff.WhenNotification <long>(symbol.InstancePath, NotificationSettings.Default)
                       .SelectMany(value => plc.Write(address, value))
                       .Subscribe());

            case TypeCode.Single:
                return(beckhoff.WhenNotification <float>(symbol.InstancePath, NotificationSettings.Default)
                       .SelectMany(value => plc.Write(address, value))
                       .Subscribe());

            default:
                throw new ArgumentException($"Unsupported Type {type.Name}");
            }
        }
Exemple #24
0
        public static async Task RebootAsync(AmsNetId target, TimeSpan delay, CancellationToken cancel)
        {
            var data   = BitConverter.GetBytes((int)delay.TotalSeconds);
            var buffer = new ReadOnlyMemory <byte>(data);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                await client.WriteControlAsync(AdsState.Shutdown, 1, buffer, cancel);
            }
        }
Exemple #25
0
        public static void Reboot(AmsNetId target, TimeSpan delay)
        {
            var data   = BitConverter.GetBytes((int)delay.TotalSeconds);
            var buffer = new ReadOnlyMemory <byte>(data);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                client.WriteControl(new StateInfo(AdsState.Shutdown, 1), buffer);
            }
        }
 /// <summary>
 /// Records API call cost in AdWordsUser instance.
 /// </summary>
 /// <param name="units">The API cost for the current call.</param>
 /// <param name="service">The Ads API service that was called.</param>
 private static void RecordApiUnitCost(int units, AdsClient service) {
   AdWordsUser user = service.User as AdWordsUser;
   string methodName = (string) ContextStore.GetValue("SoapMethod");
   if (user != null) {
     ApiUnitsEntry entry = new ApiUnitsEntry();
     entry.Service = service;
     entry.Method = methodName;
     entry.Units = units;
     user.AddUnits(entry);
   }
 }
Exemple #27
0
 private static T ReadVariable <T>(this AdsClient beckhoff, ISymbol symbol)
 {
     try
     {
         return((T)beckhoff.ReadValue(symbol));
     }
     catch (Exception e)
     {
         Log.Logger.Error(e, $"Error while reading symbol {symbol.InstancePath}");
         throw;
     }
 }
Exemple #28
0
 /// <summary>
 /// Records API operation count for a user.
 /// </summary>
 /// <param name="user">The AdWords user who made the call.</param>
 /// <param name="service">The AdWords API service that was called.</param>
 /// <param name="methodName">The name of the method that was called.</param>
 /// <param name="operationCount">The number of API operations for the
 /// current call.</param>
 private static void RecordApiOperationCount(AdWordsUser user, AdsClient service,
                                             string methodName, int operationCount)
 {
     if (user != null)
     {
         ApiCallEntry entry = new ApiCallEntry();
         entry.Service        = service;
         entry.Method         = methodName;
         entry.OperationCount = operationCount;
         user.AddCallDetails(entry);
     }
 }
 /// <summary>
 /// Handles the SOAP message.
 /// </summary>
 /// <param name="soapMessage">The SOAP message.</param>
 /// <param name="service">The SOAP service.</param>
 /// <param name="direction">The direction of message.</param>
 public void HandleMessage(XmlDocument soapMessage, AdsClient service,
     SoapMessageDirection direction) {
   if (direction == SoapMessageDirection.OUT) {
     ContextStore.AddKey("SoapRequest", soapMessage.OuterXml);
   } else {
     ContextStore.AddKey("SoapResponse", soapMessage.OuterXml);
   }
   if (direction == SoapMessageDirection.IN) {
     PerformLogging(service, (string) ContextStore.GetValue("SoapRequest"),
         (string) ContextStore.GetValue("SoapResponse"));
   }
 }
Exemple #30
0
 private static async Task <Unit> Write <T>(this AdsClient beckhoff, ISymbol symbol, T value)
 {
     try
     {
         await beckhoff.WriteValueAsync(symbol, value, CancellationToken.None);
     }
     catch (Exception e)
     {
         Log.Logger.Error(e, $"Error while writing Beckhoff value {value} into {symbol.InstancePath}");
     }
     return(Unit.Default);
 }
Exemple #31
0
        public static int GetCpuUsage(AmsNetId target)
        {
            var buffer = new Memory <byte>(new byte[4]);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.R0_Realtime));
                client.Read(0x01, 0x06, buffer);
            }

            return(BitConverter.ToInt32(buffer.ToArray(), 0));
        }
Exemple #32
0
        public static int GetSystemLatencyMaximum(AmsNetId target)
        {
            var buffer = new Memory <byte>(new byte[8]);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.R0_Realtime));
                client.Read(0x01, 0x02, buffer);
            }

            return(BitConverter.ToInt32(buffer.ToArray(), 4));
        }
Exemple #33
0
        public static async Task SetLocalTimeAsync(AmsNetId target, DateTime time, CancellationToken cancel)
        {
            var buffer = new ReadOnlyMemory <byte>(BitConverter.GetBytes(time.Ticks));

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.SystemService));
                var result = await client.WriteAsync(400, 1, buffer, cancel);

                result.ThrowOnError();
            }
        }
Exemple #34
0
        public static async Task <int> GetSystemLatencyMaximumAsync(AmsNetId target, CancellationToken cancel)
        {
            var buffer = new Memory <byte>(new byte[8]);

            using (AdsClient client = new AdsClient())
            {
                client.Connect(new AmsAddress(target, AmsPort.R0_Realtime));
                var result = await client.ReadAsync(0x01, 0x02, buffer, cancel);

                result.ThrowOnError();
            }

            return(BitConverter.ToInt32(buffer.ToArray(), 4));
        }
Exemple #35
0
        public static async Task <DateTime> GetTimeAsync(AmsNetId target, CancellationToken cancel)
        {
            var buffer = new Memory <byte>(new byte[16]);

            using (AdsClient client = new AdsClient())
            {
                await client.ConnectAsync(new AmsAddress(target, AmsPort.SystemService), cancel);

                var result = await client.ReadAsync(400, 1, buffer, cancel);

                result.ThrowOnError();
            }

            return(DateTime.FromBinary(BitConverter.ToInt64(buffer.ToArray(), 0)));
        }
Exemple #36
0
        public void RunTest()
        {
            using (AdsClient client = new AdsClient(settings))
            {
                var deviceInfo = client.ReadDeviceInfo();
                Console.WriteLine("Device info: " + deviceInfo.ToString());

                Console.WriteLine();
                Console.WriteLine("Available symbols: ");
                var symbols = client.Special.GetSymbols();
                foreach (var symbol in symbols)
                {
                    Console.WriteLine("  " + symbol.ToString());
                }
                Console.WriteLine();

                uint startTestHandle = client.GetSymhandleByName("MAIN.STARTTEST");
                Console.WriteLine("Handle StartTest: " + startTestHandle.ToString());

                uint testIsRunningHandle = client.GetSymhandleByName("MAIN.TESTISRUNNING");
                Console.WriteLine("Handle TestIsRunning: " + testIsRunningHandle.ToString());

                uint stopTestHandle = client.GetSymhandleByName("MAIN.STOPTEST");
                Console.WriteLine("Handle StopTest: " + stopTestHandle.ToString());

                var testIsRunning = client.Read<bool>(testIsRunningHandle);
                Console.WriteLine("Is test running? " + testIsRunning.ToString());

                client.Write<bool>(startTestHandle, true);
                Console.WriteLine("Starting test");

                testIsRunning = client.Read<bool>(testIsRunningHandle);
                Console.WriteLine("Is test running? " + testIsRunning.ToString());

                //TODO

                client.Write<bool>(stopTestHandle, true);
                Console.WriteLine("Stopping test");

                testIsRunning = client.Read<bool>(testIsRunningHandle);
                Console.WriteLine("Is test running? " + testIsRunning.ToString());
            }
        }
        public void ReadState()
        {
            var amsTestSocket = new AmsSocketTest();
            amsTestSocket.SendMessage = new byte[] {
                    0,0,32,0,0,0,5,1,204,123,1,1,33,3,10,0,0,120,
                    1,1,137,128,4,0,4,0,0,0,0,0,0,0,0,0,1,0,0,0};

            amsTestSocket.ReceiveMessage = new byte[] { 
                    0,0,40,0,0,0,10,0,0,120,1,1,137,128,5,1,204,123,1,1,
                    33,3,4,0,5,0,8,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,5,0,0,0};

            using (AdsClient client = new AdsClient(
                    amsNetIdSource: "10.0.0.120.1.1",
                    amsSocket: amsTestSocket,
                    amsNetIdTarget: "5.1.204.123.1.1"))
            {
                var state = client.ReadState();
                Assert.AreEqual(state.ToString(), "Ads state: 5 (Run) Device state: 0");
            }
        }
        public void ReadDeviceInfo()
        {
            var amsTestSocket = new AmsSocketTest();
            amsTestSocket.SendMessage = new byte[] {
                    0,0,32,0,0,0,5,1,204,123,1,1,33,3,10,0,0,
                    120,1,1,137,128,1,0,4,0,0,0,0,0,0,0,0,0,1,0,0,0};

            amsTestSocket.ReceiveMessage = new byte[] {
                    0,0,56,0,0,0,10,0,0,120,1,1,137,128,5,1,204,123,
                    1,1,33,3,1,0,5,0,24,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
                    0,2,11,234,5,84,67,97,116,80,108,99,67,116,114,108,0,0,0,0,0};

            using (AdsClient client = new AdsClient(
                    amsNetIdSource: "10.0.0.120.1.1",
                    amsSocket: amsTestSocket,
                    amsNetIdTarget: "5.1.204.123.1.1"))
            {
                AdsDeviceInfo deviceInfo = client.ReadDeviceInfo();
                Assert.AreEqual(deviceInfo.ToString(), "Version: 2.11.1514 Devicename: TCatPlcCtrl");
            }
        }
    /// <summary>
    /// Performs the SOAP and HTTP logging.
    /// </summary>
    /// <param name="service">The SOAP service.</param>
    /// <param name="soapResponse">The SOAP response xml.</param>
    /// <param name="soapRequest">The SOAP request xml.</param>
    private void PerformLogging(AdsClient service, string soapRequest, string soapResponse) {
      if (service == null || service.User == null || soapRequest == null || soapResponse == null) {
        return;
      }

      if (config.MaskCredentials) {
        XmlDocument xDoc = SerializationUtilities.LoadXml(soapRequest);
        MaskCredentialsInLogs(xDoc, GetFieldsToMask());
        soapRequest = xDoc.OuterXml;
      }

      string formattedSoapRequest = FormatSoapRequest(service.LastRequest, soapRequest);
      string formattedSoapResponse = FormatSoapResponse(service.LastResponse, soapResponse);
      string formattedHttpRequest = FormatHttpRequest(soapRequest);
      string formattedHttpResponse = FormatHttpResponse(soapResponse);

      string soapLog = formattedSoapRequest + formattedSoapResponse;
      string requestLog = string.Format(CultureInfo.InvariantCulture, "host={0},url={1},{2},{3}",
          service.LastRequest.RequestUri.Host, service.LastRequest.RequestUri.AbsolutePath,
          formattedHttpRequest, formattedHttpResponse);

      ContextStore.AddKey("FormattedSoapLog", soapLog);
      ContextStore.AddKey("FormattedRequestLog", requestLog);

      bool isError = service.LastResponse != null && service.LastResponse is HttpWebResponse &&
          (service.LastResponse as HttpWebResponse).StatusCode ==
              HttpStatusCode.InternalServerError;

      TraceUtilities.WriteSoapXmlLogs(soapLog, isError);
      TraceUtilities.WriteRequestInfoLogs(requestLog, isError);
    }
    /// <summary>
    /// Performs the SOAP and HTTP logging.
    /// </summary>
    /// <param name="service">The SOAP service.</param>
    /// <param name="soapResponse">The SOAP response xml.</param>
    /// <param name="soapRequest">The SOAP request xml.</param>
    private void PerformLogging(AdsClient service, string soapRequest, string soapResponse) {
      if (service == null || service.User == null || soapRequest == null || soapResponse == null) {
        return;
      }

      bool isFailure = service.LastResponse != null && service.LastResponse is HttpWebResponse &&
          (service.LastResponse as HttpWebResponse).StatusCode ==
                HttpStatusCode.InternalServerError;

      LogEntry logEntry = new LogEntry(config, dateTimeProvider);
      logEntry.LogRequestDetails(service.LastRequest, soapRequest, GetFieldsToMask(),
          new SoapTraceFormatter());
      logEntry.LogResponseDetails(service.LastResponse, soapResponse, new HashSet<string>(),
          new DefaultBodyFormatter());
      logEntry.LogRequestSummary(service.LastRequest, GetSummaryRequestLogs(soapRequest));
      logEntry.LogResponseSummary(isFailure, GetSummaryResponseLogs(soapResponse));
      logEntry.Flush();

      ContextStore.AddKey("FormattedSoapLog", logEntry.DetailedLog);
      ContextStore.AddKey("FormattedRequestLog", logEntry.SummaryLog);
    }
 /// <summary>
 /// Calls the SOAP listeners.
 /// </summary>
 /// <param name="document">The SOAP message as an xml document.</param>
 /// <param name="service">The service for which call is being made.</param>
 /// <param name="direction">The direction of SOAP message.</param>
 internal void CallListeners(XmlDocument document, AdsClient service,
     SoapMessageDirection direction) {
   foreach (SoapListener listener in listeners) {
     listener.HandleMessage(document, service, direction);
   }
 }
 /// <summary>
 /// Handles the SOAP message.
 /// </summary>
 /// <param name="soapMessage">The SOAP message.</param>
 /// <param name="service">The SOAP service.</param>
 /// <param name="direction">The direction of message.</param>
 public override void HandleMessage(XmlDocument soapMessage, AdsClient service,
     SoapListener.Direction direction) {
   if (direction == Direction.IN) {
     RecordApiUnitCost(GetApiUnitsForCall(soapMessage), service);
   }
 }
        /// <summary>
        /// Sets the request header namespace in outgoing Soap Requests.
        /// </summary>
        /// <param name="signature">The service creation parameters.</param>
        /// <param name="service">The service object for which RequestHeader
        /// needs to be patched.</param>
        private static void SetRequestHeaderNameSpace(DfaServiceSignature signature,
        AdsClient service)
        {
            // Set the header namespace prefix. For all /cm services, the members
              // shouldn't have xmlns. For all other services, the members should have
              // /cm as xmlns.
              object[] attributes = service.GetType().GetCustomAttributes(false);
              foreach (object attribute in attributes) {
            if (attribute is WebServiceBindingAttribute) {
              WebServiceBindingAttribute binding = (WebServiceBindingAttribute) attribute;

              string xmlns = binding.Namespace;
              RequestHeader svcRequestHeader = null;
              PropertyInfo propInfo = service.GetType().GetProperty("RequestHeader");
              if (propInfo != null) {
            svcRequestHeader = (RequestHeader) propInfo.GetValue(service, null);

            if (svcRequestHeader != null) {
              PropertyInfo wsPropInfo = svcRequestHeader.GetType().GetProperty("TargetNamespace");
              if (wsPropInfo != null) {
                wsPropInfo.SetValue(svcRequestHeader, xmlns, null);
              }
            }
              }
            }
              }
        }
    /// <summary>
    /// Performs the SOAP and HTTP logging.
    /// </summary>
    /// <param name="service">The SOAP service.</param>
    /// <param name="soapResponse">The SOAP response xml.</param>
    /// <param name="soapRequest">The SOAP request xml.</param>
    private void PerformLogging(AdsClient service, string soapRequest, string soapResponse) {
      if (service == null || service.User == null || soapRequest == null || soapResponse == null) {
        return;
      }

      if (config.MaskCredentials) {
        XmlDocument xDoc = SerializationUtilities.LoadXml(soapRequest);
        MaskCredentialsInLogs(xDoc, GetFieldsToMask());
        soapRequest = xDoc.OuterXml;
      }

      string formattedSoapRequest = FormatSoapRequest(service.LastRequest, soapRequest);
      string formattedSoapResponse = FormatSoapResponse(service.LastResponse, soapResponse);
      string formattedHttpRequest = FormatHttpRequest(soapRequest);
      string formattedHttpResponse = FormatHttpResponse(soapResponse);

      string soapLog = formattedSoapRequest + formattedSoapResponse;
      string requestLog = string.Format(CultureInfo.InvariantCulture, "host={0},url={1},{2},{3}",
          service.LastRequest.RequestUri.Host, service.LastRequest.RequestUri.AbsolutePath,
          formattedHttpRequest, formattedHttpResponse);

      bool isError = service.LastResponse != null && service.LastResponse is HttpWebResponse &&
          (service.LastResponse as HttpWebResponse).StatusCode ==
              HttpStatusCode.InternalServerError;

      if (!logErrorsOnly || logErrorsOnly && isError) {
        if (logToFile) {
          WriteToFile(soapFileName, soapLog);
          WriteToFile(requestInfoFileName, requestLog);
        }
        if (logToConsole) {
          WriteToStream(Console.Out, soapLog);
          WriteToStream(Console.Out, requestLog);
        }
      }
    }
    /// <summary>
    /// Fix the request header namespace in outgoing Soap Requests, so that
    /// cross namespace requests can work properly.
    /// </summary>
    /// <param name="signature">The service creation parameters.</param>
    /// <param name="service">The service object for which RequestHeader
    /// needs to be patched.</param>
    private static void FixRequestHeaderNameSpace(AdWordsServiceSignature signature,
        AdsClient service) {
      // Set the header namespace prefix. For all /cm services, the members
      // shouldn't have xmlns. For all other services, the members should have
      // /cm as xmlns.
      object[] attributes = service.GetType().GetCustomAttributes(false);
      foreach (object attribute in attributes) {
        if (attribute is WebServiceBindingAttribute) {
          WebServiceBindingAttribute binding = (WebServiceBindingAttribute) attribute;
          string delimiter = "/api/adwords/";
          string xmlns = String.Join("", new String[] {
              binding.Namespace.Substring(0, binding.Namespace.IndexOf(delimiter) +
                  delimiter.Length), "cm/", signature.Version});
          if (xmlns == binding.Namespace) {
            xmlns = "";
          }

          RequestHeader svcRequestHeader = null;
          PropertyInfo propInfo = service.GetType().GetProperty("RequestHeader");
          if (propInfo != null) {
            svcRequestHeader = (RequestHeader) propInfo.GetValue(service, null);

            if (svcRequestHeader != null) {
              PropertyInfo wsPropInfo = svcRequestHeader.GetType().GetProperty("TargetNamespace");
              if (wsPropInfo != null) {
                wsPropInfo.SetValue(svcRequestHeader, xmlns, null);
              }
            }
          }
        }
      }
    }
 /// <summary>
 /// Handles the SOAP message.
 /// </summary>
 /// <param name="soapMessage">The SOAP message.</param>
 /// <param name="service">The SOAP service.</param>
 /// <param name="direction">The direction of message.</param>
 public void HandleMessage(XmlDocument soapMessage, AdsClient service,
     SoapMessageDirection direction) {
   if (direction == SoapMessageDirection.IN) {
     AdWordsUser user = service.User as AdWordsUser;
     string methodName = (string) ContextStore.GetValue("SoapMethod");
     RecordApiOperationCount(user, service, methodName, GetApiUnitsForCall(soapMessage));
   }
 }
        /// <summary>
        /// Handles the message.
        /// </summary>
        /// <param name="soapMessage">The SOAP message.</param>
        /// <param name="service">The service.</param>
        /// <param name="direction">The direction.</param>
        public void HandleMessage(XmlDocument soapMessage, AdsClient service,
        SoapMessageDirection direction)
        {
            XmlNamespaceManager xmlnt = new XmlNamespaceManager(soapMessage.NameTable);
              xmlnt.AddNamespace(SOAP_PREFIX, SOAP_NAMESPACE);
              if (direction == SoapMessageDirection.OUT) {
            UserToken token = (UserToken) ContextStore.GetValue("Token");
            RequestHeader requestHeader = (RequestHeader) ContextStore.GetValue("RequestHeader");

            if (token != null || requestHeader != null) {
              XmlElement soapHeader = GetSoapHeaderNode(soapMessage, xmlnt, true);

              if (token != null) {
            AddSecurityHeader(soapHeader, token);
              }
              if (requestHeader != null) {
            AddRequestHeader(soapHeader, requestHeader);
              }
            }
              } else {
            ContextStore.AddKey("ResponseHeader", ParseResponseHeader(soapMessage, xmlnt));
              }
        }
 /// <summary>
 /// Handles the SOAP message.
 /// </summary>
 /// <param name="soapMessage">The SOAP message.</param>
 /// <param name="service">The SOAP service.</param>
 /// <param name="direction">The direction of message.</param>
 public abstract void HandleMessage(XmlDocument soapMessage, AdsClient service,
     Direction direction);