Пример #1
0
        static NewPayLoad GeneratePlatformActionPayload(IActPluginExecution ACT, Agent agent)
        {
            PlatformAction platformAction = ACT.GetAsPlatformAction();

            if (ACT is ActUIElement actUi)
            {
                if (actUi.ElementLocateBy == eLocateBy.POMElement)
                {
                    AddPOMLocators(ref platformAction, ref actUi, agent.ProjEnvironment, agent.BusinessFlow);
                }
            }

            // TODO: calculate VE ??!!

            NewPayLoad payload = new NewPayLoad("RunPlatformAction");

            payload.AddJSONValue <PlatformAction>(platformAction);
            payload.ClosePackage();

            // TODO: Process Valuefordriver!!!!

            return(payload);


            void AddPOMLocators(ref PlatformAction PlatformAction, ref ActUIElement UIElementAction, ProjEnvironment projEnvironment, BusinessFlow businessFlow)
            {
                Dictionary <string, string> Locators = new Dictionary <string, string>();


                List <string> Frames = new List <string>();

                string[]            pOMandElementGUIDs = UIElementAction.ElementLocateValue.ToString().Split('_');
                Guid                selectedPOMGUID    = new Guid(pOMandElementGUIDs[0]);
                ApplicationPOMModel currentPOM         = amdocs.ginger.GingerCoreNET.WorkSpace.Instance.SolutionRepository.GetRepositoryItemByGuid <ApplicationPOMModel>(selectedPOMGUID);

                if (currentPOM == null)
                {
                    UIElementAction.ExInfo = string.Format("Failed to find the mapped element Page Objects Model with GUID '{0}'", selectedPOMGUID.ToString());
                    return;
                }



                Guid        selectedPOMElementGUID = new Guid(pOMandElementGUIDs[1]);
                ElementInfo selectedPOMElement     = (ElementInfo)currentPOM.MappedUIElements.Where(z => z.Guid == selectedPOMElementGUID).FirstOrDefault();


                if (selectedPOMElement == null)
                {
                    UIElementAction.ExInfo = string.Format("Failed to find the mapped element with GUID '{0}' inside the Page Objects Model", selectedPOMElement.ToString());
                    return;
                }
                else
                {
                    List <NewPayLoad> switchframpayload = new List <NewPayLoad>();

                    if (selectedPOMElement.Path != null)
                    {
                        string[] spliter       = new string[] { "," };
                        string[] iframesPathes = selectedPOMElement.Path.Split(spliter, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string iframePath in iframesPathes)
                        {
                            Frames.Add(iframePath);
                        }
                    }

                    PlatformAction.InputParams.Add("Frames", Frames);


                    //adding all locators from POM

                    foreach (ElementLocator locator in selectedPOMElement.Locators.Where(x => x.Active == true).ToList())
                    {
                        string locateValue;
                        if (locator.IsAutoLearned)
                        {
                            locateValue = locator.LocateValue;
                        }
                        else
                        {
                            ElementLocator             evaluatedLocator = locator.CreateInstance() as ElementLocator;
                            GingerCore.ValueExpression VE = new GingerCore.ValueExpression(projEnvironment, businessFlow);
                            locateValue = VE.Calculate(evaluatedLocator.LocateValue);
                        }
                        Locators.Add(locator.LocateBy.ToString(), locateValue);
                    }



                    if (PlatformAction.InputParams.ContainsKey("Locators"))
                    {
                        PlatformAction.InputParams["Locators"] = Locators;
                    }
                    else
                    {
                        PlatformAction.InputParams.Add("Locators", Locators);
                    }
                }
            }
        }
Пример #2
0
        // Each time new data arrive we get callback
        private void ReceiveCallback(IAsyncResult ar)
        {
            // Console.WriteLine("Receive Callback");
            // TODO: add timeout to prevent partial package to get stuck

            lock (mSendLockObject)
            {
                // Console.WriteLine("Send lock obtained");
            };


            try
            {
                // Retrieve the state object and the  socket
                // from the asynchronous state object.
                GingerSocketInfo gingerSocketInfo = (GingerSocketInfo)ar.AsyncState;
                Socket           socket           = gingerSocketInfo.Socket;

                // Read data from the socket
                int bytesRead = socket.EndReceive(ar);
                BytesIn += bytesRead;
                if (bytesRead > 0)
                {
                    if (gingerSocketInfo.BufferPOS == 0) // do only once per Payload
                    {
                        //TODO: There might be more data, so store the data received so far - need to veruf completion, create TC !!
                        byte[] rcvLenBytesBB = gingerSocketInfo.buffer;  // TODO: !!!!!!!!!!!!!temp do work direct - avoid creating a new byte array
                        PayloadLen = ((rcvLenBytesBB[0]) << 24) + (rcvLenBytesBB[1] << 16) + (rcvLenBytesBB[2] << 8) + rcvLenBytesBB[3];

                        if (PayloadLen > gingerSocketInfo.buffer.Length)
                        {
                            Array.Resize(ref gingerSocketInfo.buffer, PayloadLen + 4);   // Make sure we will have enough space  // Add 1024 !!!
                            // TODO: check if buffer is more than x size release it back....
                        }
                    }

                    gingerSocketInfo.BufferPOS += bytesRead;

                    if (gingerSocketInfo.BufferPOS == PayloadLen + 4)
                    {
                        NewPayLoad Resp = new NewPayLoad(gingerSocketInfo.buffer, true);

                        // We got the full packet, convert to Payload and process
                        if (Resp.PaylodType == NewPayLoad.ePaylodType.ResponsePayload || Resp.PaylodType == NewPayLoad.ePaylodType.SocketResponse)
                        {
                            mProcessingStatus = eProcessingStatus.ResponseStarted;
                            // Create new Payload from the buffer, ignoring the extra space at the end
                            Response = new NewPayLoad(gingerSocketInfo.buffer, true);

                            mProcessingStatus = eProcessingStatus.ResponseCompleted;
                            // we are done with pair of Req/Resp - good job - mission completed
                            // signal receive is complete so ready for processing
                            mRequestProcessingDone.Set(); // !!!
                        }
                        else  // this is new request, we need to process and respond
                        {
                            IncomingRequetsesCounter++;
                            mProcessingStatus = eProcessingStatus.ProcessingRequest;
                            // This is a request  need to respond

                            switch (Resp.PaylodType)
                            {
                            case NewPayLoad.ePaylodType.RequestPayload:
                                MessageHandler(gingerSocketInfo);
                                gingerSocketInfo.Response.PaylodType = NewPayLoad.ePaylodType.ResponsePayload;
                                break;

                            case NewPayLoad.ePaylodType.SocketRequest:
                                SocketRequestHandler(gingerSocketInfo);
                                break;

                            default:
                                throw new InvalidOperationException("Unknown Payload Type, Payload.Name: " + Resp.Name);
                            }

                            mProcessingStatus = eProcessingStatus.SendingResponse;
                            byte[] bb = gingerSocketInfo.Response.GetPackage();
                            bytesOut += bb.Length;
                            mSocket.BeginSend(bb, 0, bb.Length, SocketFlags.None, SendCallback, this);
                            mSendDone.WaitOne();
                        }

                        gingerSocketInfo.BufferPOS = 0;

                        // be ready to accept more new request or incoming data
                        socket.BeginReceive(gingerSocketInfo.buffer, 0, gingerSocketInfo.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), gingerSocketInfo);

                        mProcessingStatus = eProcessingStatus.Ready;
                    }
                    else
                    {
                        // we got a big package more than 1024, starting collecting the bytes until all received
                        socket.BeginReceive(gingerSocketInfo.buffer, gingerSocketInfo.BufferPOS, gingerSocketInfo.buffer.Length - gingerSocketInfo.BufferPOS, SocketFlags.None, new AsyncCallback(ReceiveCallback), gingerSocketInfo);
                    }
                }
                else
                {
                    // All the data has arrived; put it in response.
                    // ????????????????????????????????????????????????????????????????????
                    // Signal that all bytes have been received.
                    mRequestProcessingDone.Set();    //move up like server ???
                }
            }
            catch (SocketException e)
            {
                if (e.SocketErrorCode == SocketError.ConnectionReset)
                {
                    Console.WriteLine("SocketException: " + e.Message);
                    //TODO: raise event

                    // other side closed connection - mark socket as dead TODO !!!!!!!!!!!!!!!!!!!!!!!
                    return;
                }
                throw e;
            }
            catch (OutOfMemoryException ex)
            {
                Console.WriteLine("OutOfMemoryException: ", ex.Message);
                return;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #3
0
        private void GingerSocketServerMessageHandler(GingerSocketInfo gingerSocketInfo)
        {
            NewPayLoad p = gingerSocketInfo.DataAsPayload;

            switch (p.Name)
            {
            case "List":      //TODO: use const
            {
                NewPayLoad RC = new NewPayLoad("RC");
                RC.AddValue("OK");

                //TODO: return the list of GingerNodeInfo

                RC.ClosePackage();
                gingerSocketInfo.Response = RC;
                break;
            }

            case SocketMessages.Register:
            {
                string NodeName      = p.GetValueString();
                string NodeServiceID = p.GetValueString();
                string NodeOS        = p.GetValueString();
                string NodeHost      = p.GetValueString();
                string NodeIP        = p.GetValueString();

                NewPayLoad RC = new NewPayLoad("SessionID", gingerSocketInfo.SessionID);
                gingerSocketInfo.Response = RC;

                // add the info of the new node to the grid list
                mGingerNodeInfo.Add(new GingerNodeInfo()
                    {
                        Name = NodeName, ServiceId = NodeServiceID, OS = NodeOS, Host = NodeHost, IP = NodeIP, SessionID = gingerSocketInfo.SessionID, Status = GingerNodeInfo.eStatus.Ready
                    });
                break;
            }

            case SocketMessages.Unregister:
            {
                Guid           SessionID = p.GetGuid();
                GingerNodeInfo GNI       = (from x in mGingerNodeInfo where x.SessionID == SessionID select x).FirstOrDefault();
                if (GNI == null)
                {
                    gingerSocketInfo.Response = new NewPayLoad("Error", "Ginger node info not found for session id " + SessionID.ToString());
                }

                mGingerNodeInfo.Remove(GNI);

                NewPayLoad RC = new NewPayLoad("OK");
                RC.ClosePackage();
                gingerSocketInfo.Response = RC;
                break;
            }


            // Combine find and send to one - send session id or how to find
            // Change to reserve node
            case SocketMessages.FindNode:      // Find node which match criteria, used for remote grid
                string ServiceID = p.GetValueString();

                // !!! find first or use better algorithm
                GingerNodeInfo gingerNodeInfo1 = (from x in NodeList where x.ServiceId == ServiceID select x).FirstOrDefault();

                // Reserve
                // TODO: lock !!!!!!!!!!!!!!!!!!!!
                gingerNodeInfo1.Status = GingerNodeInfo.eStatus.Reserved;     // TODO: release !!!!!!!!!!!!!!!!
                NewPayLoad RC2 = new NewPayLoad("NodeInfo", gingerNodeInfo1.SessionID);
                gingerSocketInfo.Response = RC2;
                break;

            case SocketMessages.SendToNode:      // Send action to Node, used when Grid is remote
                Guid           SessionID2               = p.GetGuid();
                GingerNodeInfo gingerNodeInfo           = (from x in NodeList where x.SessionID == SessionID2 select x).SingleOrDefault();
                NewPayLoad     actionPayload            = p.ReadPayload();
                NewPayLoad     remoteNodeActionResponce = SendRequestPayLoad(gingerNodeInfo.SessionID, actionPayload);
                remoteNodeActionResponce.Truncate();
                gingerSocketInfo.Response = remoteNodeActionResponce;
                gingerNodeInfo.Status     = GingerNodeInfo.eStatus.Ready;  //TODO: in case of session to do not release
                break;

            default:
                throw new Exception("GingerSocketServerMessageHandler: Unknown Message type: " + p.Name);
            }
        }
Пример #4
0
        // Move code to the ActPlugIn and make it impl IACtPlug...
        public static NewPayLoad CreateActionPayload(ActPlugIn ActPlugIn)
        {
            // Here we decompose the GA and create Payload to transfer it to the agent
            NewPayLoad PL = new NewPayLoad("RunAction");

            PL.AddValue(ActPlugIn.ActionId);
            //Add Params
            List <NewPayLoad> Params = new List <NewPayLoad>();

            // if this is the first time the action run it will not have param type
            // so read it from plugin action info
            if (ActPlugIn.InputValues.Count > 0)
            {
                if (ActPlugIn.InputValues[0].ParamType == null)
                {
                    UpdateParamsType(ActPlugIn);
                }
            }

            foreach (ActInputValue AP in ActPlugIn.InputValues)
            {
                // Why we need GA?
                if (AP.Param == "GA")
                {
                    continue;
                }
                // TODO: use const
                NewPayLoad p = new NewPayLoad("P");   // To save network traffic we send just one letter
                p.AddValue(AP.Param);
                if (AP.ParamType == typeof(string))
                {
                    p.AddValue(AP.ValueForDriver.ToString());
                }
                else if (AP.ParamType == typeof(int))
                {
                    p.AddValue(AP.IntValue);
                }
                else if (AP.ParamType == typeof(bool))
                {
                    p.AddValue(AP.BoolValue);
                }
                else if (AP.ParamType == typeof(DynamicListWrapper))
                {
                    p.AddValue(AP.ValueForDriver.ToString());
                }
                else if (AP.ParamType == typeof(EnumParamWrapper))
                {
                    p.AddValue(AP.ValueForDriver.ToString());
                }

                else
                {
                    throw new Exception("Unknown param type to pack: " + AP.ParamType.FullName);
                }
                p.ClosePackage();
                Params.Add(p);
            }
            PL.AddListPayLoad(Params);

            PL.ClosePackage();
            return(PL);
        }
Пример #5
0
 internal NewPayLoad SendPayLoad(Guid sessionID, NewPayLoad pL)
 {
     return(mGingerSocketServer.SendPayLoad(sessionID, pL));
 }
Пример #6
0
        private NewPayLoad RunAction(NewPayLoad pl)
        {
            ScanService();

            Console.WriteLine(">>> Payload - Run Ginger Action");
            string ActionID = pl.GetValueString();

            Console.WriteLine("Received RunAction, ActionID - " + ActionID);

            ActionHandler AH = (from x in mServiceActions where x.ServiceActionId == ActionID select x).FirstOrDefault();

            if (AH == null)
            {
                Console.WriteLine("Unknown ActionID to handle - " + ActionID);
                throw new Exception("Unknown ActionID to handle - " + ActionID);
            }

            //Conver the Payload to GingerAction
            NodeGingerAction nodeGingerAction = new NodeGingerAction();

            AH.NodeGingerAction = nodeGingerAction;
            Console.WriteLine("Found Action Handler, setting parameters");

            // setting parameters
            List <NewPayLoad> Params = pl.GetListPayLoad();

            Console.WriteLine("Found " + Params.Count + " parameters");
            ActionInputParams actionInputParams = new ActionInputParams();

            foreach (NewPayLoad PLP in Params)
            {
                // we get Param name and value
                string Name  = PLP.GetValueString();
                object Value = PLP.GetValueByObjectType();
                Console.WriteLine("Param " + Name + " = " + Value);
                ActionParam AP = actionInputParams[Name];
                if (AP != null)
                {
                    actionInputParams[Name].Value = Value;
                }
                else
                {
                    Console.WriteLine("Cannot find input param - " + Name);
                }
            }

            // TODO: add hookd for before and after using interface
            //if (IBeforeAfterAction != null)
            //    mService.BeforeRunAction(AH.GingerAction);
            // mService.RunAction(AH.GingerAction);

            ExecuteMethod(AH, actionInputParams, nodeGingerAction);

            // We send back only item which can change - ExInfo and Output values
            NewPayLoad PLRC = new NewPayLoad("ActionResult");   //TODO: use const

            PLRC.AddValue(nodeGingerAction.ExInfo);
            PLRC.AddValue(nodeGingerAction.Errors);
            PLRC.AddListPayLoad(GetOutpuValuesPayLoad(nodeGingerAction.Output.OutputValues));
            PLRC.ClosePackage();
            return(PLRC);
        }
Пример #7
0
 private NewPayLoad SendRequestPayLoad(NewPayLoad pL)
 {
     // if local grid use
     return(GingerGrid.SendRequestPayLoad(mGingerNodeInfo.SessionID, pL));
     // else use remote grid
 }
Пример #8
0
        private void MessageHandler(GingerSocketInfo gingerSocketInfo)
        {
            NewPayLoad PLRC = HandlePayLoad(gingerSocketInfo.DataAsPayload);

            gingerSocketInfo.Response = PLRC;
        }
Пример #9
0
            public NewPayLoad Send(NewPayLoad data)
            {
                NewPayLoad rc = mGingerSocketClient2.SendRequestPayLoad(data);

                return(rc);
            }
Пример #10
0
        public NewPayLoad RunAction(NewPayLoad newPayLoad)
        {
            NewPayLoad RC = SendRequestPayLoad(newPayLoad);

            return(RC);
        }
Пример #11
0
 NewPayLoad HandlePayLoadFromServer(NewPayLoad pL)
 {
     return(new NewPayLoad("Client Response to server", "OK"));
 }
Пример #12
0
        /// <summary>
        /// Connect to Services Grid
        /// Retry mechanism will retry every 5 seconds up to total 30 seconds
        /// </summary>
        /// <param name="IP"></param>
        /// <param name="port"></param>
        public void Connect(string IP, int port)
        {
            try
            {
                //Local host
                IPAddress  ipAddress = IPAddress.Parse(IP);
                IPEndPoint remoteIP  = new IPEndPoint(ipAddress, port);
                Socket     socket    = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                Console.WriteLine("Connecting to: " + remoteIP + ":" + port);
                // Connect to Ginger Server async, retry max 30 seconds
                Stopwatch stopwatch  = Stopwatch.StartNew();
                int       retrycount = 0;
                while (!socket.Connected && stopwatch.ElapsedMilliseconds < 30000)
                {
                    socket.BeginConnect(remoteIP, new AsyncCallback(ConnectCallback), socket);
                    mConnectDone.WaitOne();
                    if (!socket.Connected)
                    {
                        retrycount++;
                        Console.WriteLine("Connect retry #" + retrycount);
                        Thread.Sleep(5000);
                    }
                }

                if (socket.Connected)
                {
                    // Now Ginger client is ready for incoming data
                    mConnected = true;
                }
                else
                {
                    Console.WriteLine("Failed to connect, exiting");
                    mConnected = false;
                    return;
                }

                //start waiting for incoming data async - non blocking

                // Create the state object.
                mGingerSocketInfo                = new GingerSocketInfo();
                mGingerSocketInfo.Socket         = socket;
                mGingerSocketInfo.MessageHandler = MessageHandler;
                mGingerSocketInfo.Receive();   // not blocking


                // if there is code here it will run - no wait

                //TODO: handshake: version, security, encryption
                NewPayLoad HandShake1 = new NewPayLoad("GetSession", "v1");
                HandShake1.PaylodType = NewPayLoad.ePaylodType.SocketRequest;
                NewPayLoad RC = SendSocketPayLoad(HandShake1);
                if (RC.Name == "SessionID")
                {
                    mGingerSocketInfo.SessionID = RC.GetGuid();
                }
                else
                {
                    throw new Exception("Error in connecting to GingerSocketServer invalid Session");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
                throw e;
            }
        }
Пример #13
0
 public NewPayLoad SendSocketPayLoad(NewPayLoad pl)
 {
     pl.PaylodType = NewPayLoad.ePaylodType.SocketRequest;
     return(mGingerSocketInfo.SendRequest(pl));
 }
        public NewPayLoad RunAction(NewPayLoad actionPayload)
        {
            NewPayLoad resultPayload = SendRequestPayLoad(actionPayload);

            return(resultPayload);
        }
Пример #15
0
        private NewPayLoad RunAction(NewPayLoad pl)
        {
            ScanService();

            Console.WriteLine(">>> Payload - Run Ginger Action");
            string ActionID = pl.GetValueString();

            Console.WriteLine("Received RunAction, ActionID - " + ActionID);


            ActionHandler AH = null;

            //if (mDriver != null)
            //{
            //    AH = (from x in this.mDriver.ActionHandlers where x.ID == ActionID select x).FirstOrDefault();
            //}
            //else if (mService != null)
            //{
            AH = (from x in mServiceActions where x.ServiceActionId == ActionID select x).FirstOrDefault();
            //}


            if (AH == null)
            {
                Console.WriteLine("Unknown ActionID to handle - " + ActionID);
                throw new Exception("Unknown ActionID to handle - " + ActionID);
            }

            //Conver the Payload to GingerAction

            NodeGingerAction NGA = new NodeGingerAction();

            AH.NodeGingerAction = NGA;
            //AH.GingerAction.ID = ActionID;   // !!!!!!!!!!!!!!!!!!!!! why do we need to keep the ID twice !!

            Console.WriteLine("Found Action Handler, setting parameters");
            List <NewPayLoad> Params = pl.GetListPayLoad();

            Console.WriteLine("Found " + Params.Count + " parameters");

            ActionInputParams actionInputParams = new ActionInputParams();

            foreach (NewPayLoad PLP in Params)
            {
                // we get Param name and value
                string Name  = PLP.GetValueString();
                string Value = PLP.GetValueString();
                Console.WriteLine("Param " + Name + " = " + Value);
                ActionParam AP = actionInputParams[Name];
                if (AP != null)
                {
                    actionInputParams[Name].Value = Value;
                }
                else
                {
                    Console.WriteLine("Cannot find input param - " + Name);
                }
            }

            //Console.WriteLine("Setting params done");

            //TODO: print to console:  Running Action: GotoURL(URL="aaa");  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            // TODO: cache  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

            //if (mDriver != null)
            //{
            //    mDriver.BeforeRunAction(AH.GingerAction);
            //    mDriver.RunAction(AH.GingerAction);
            //    mDriver.AfterRunAction(AH.GingerAction);
            //}
            //else if (mService != null)
            //{
            //    mService.BeforeRunAction(AH.GingerAction);
            // mService.RunAction(AH.GingerAction);

            // GA.Output = new ActionOutput();
            RunServiceAction(AH, actionInputParams, NGA);
            //    mService.AfterRunAction(AH.GingerAction);
            //}

            // We send back only item which can change - ExInfo and Output values
            NewPayLoad PLRC = new NewPayLoad("ActionResult");   //TODO: use const

            PLRC.AddValue(NGA.ExInfo);
            PLRC.AddValue(NGA.Errors);


            PLRC.AddListPayLoad(GetOutpuValuesPayLoad(NGA.Output.Values));


            PLRC.ClosePackage();
            return(PLRC);
        }
Пример #16
0
        internal NewPayLoad SendRequestPayLoad(Guid sessionID, NewPayLoad pL)
        {
            NewPayLoad rc = mGingerSocketServer.SendPayLoad(sessionID, pL);

            return(rc);
        }
Пример #17
0
        public void StartGingerNode(string Name, string HubIP, int HubPort)
        {
            Console.WriteLine("Starting Ginger Node");
            Console.WriteLine("ServiceID: " + mServiceID);

            string Domain      = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            string IP          = SocketHelper.GetLocalHostIP();
            string MachineName = System.Environment.MachineName;
            string OSVersion   = System.Environment.OSVersion.ToString();

            //TODO: first register at the hub
            mHubClient = new GingerSocketClient2();
            mHubClient.MessageHandler = HubClientMessageHandler;

            // We have retry mechanism
            bool IsConnected = false;
            int  count       = 0;

            while (!IsConnected)
            {
                try
                {
                    Console.WriteLine("Connecting to Ginger Grid Hub: " + HubIP + ":" + HubPort);
                    mHubClient.Connect(HubIP, HubPort);
                    IsConnected = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Connection failed: " + ex.Message);
                    Console.WriteLine("Will retry in 5 seconds");
                    Thread.Sleep(5000);
                    count++;
                    if (count > 50) //TODO: Change it to stop watch wait for 60 seconds, or based on config
                    {
                        Console.WriteLine("All connection attempts failed, exiting");
                        return;
                    }
                }
            }

            //Register the service in GG
            NewPayLoad PLRegister = new NewPayLoad(SocketMessages.Register);

            PLRegister.AddValue(Name);
            PLRegister.AddValue(mServiceID);
            PLRegister.AddValue(OSVersion);   // TODO: translate to normal name?
            PLRegister.AddValue(MachineName); // TODO: if local host write local host
            PLRegister.AddValue(IP);

            PLRegister.ClosePackage();
            NewPayLoad RC = mHubClient.SendRequestPayLoad(PLRegister);

            //TODO: we can disconnect from hub, make Register/Unregister a function

            if (RC.Name == "SessionID")
            {
                mSessionID = RC.GetGuid();
                Console.WriteLine("Ginger Node started SessionID - " + mSessionID);
                if (GingerNodeMessage != null)
                {
                    GingerNodeMessage.Invoke(this, eGingerNodeEventType.Started);
                }
            }
            else
            {
                throw new Exception("Unable to find Ginger Grid at: " + HubIP + ":" + HubPort);
            }
        }
Пример #18
0
        // Handle Client request
        private NewPayLoad HandlePayLoad(NewPayLoad PL)
        {
            switch (PL.Name)
            {
            case "GetObject":
                string             id  = PL.GetValueString();
                object             obj = GetObjectHandler(id);
                RemoteObjectHandle remoteObjectHandle = new RemoteObjectHandle();
                Guid guid = Guid.NewGuid();
                remoteObjectHandle.GUID   = guid;
                remoteObjectHandle.Object = obj;

                //check if the object have Dispatcher - means GUI element so STA thread then run it on the STA, so we keep the Dispatcher for the invoke part later
                PropertyInfo PI = obj.GetType().GetProperty("Dispatcher");
                if (PI != null)
                {
                    object  DispObj = obj;
                    dynamic d       = DispObj;
                    // It means it is UI control - so invoke on the UI control Dispatcher, this way we avoid code on the page to change the UI on the Dispatcher every time
                    // temp comment for build
                    // !!!!!!!!! d. requires Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo
                    // remoteObjectHandle.Dispatcher = d.Dispatcher;
                }

                mObjects.Add(guid, remoteObjectHandle);
                NewPayLoad PLEcho = new NewPayLoad("Object", guid.ToString());
                return(PLEcho);

            case "SendObject":
                string     txt2    = "a=1;b=2";
                NewPayLoad PLEcho2 = new NewPayLoad("Object", txt2);
                return(PLEcho2);

            case "Invoke":
                Guid               objguid    = Guid.Parse(PL.GetValueString());
                string             methodName = PL.GetValueString();
                RemoteObjectHandle ROH;
                // Get the object by guid
                bool   bFound = mObjects.TryGetValue(objguid, out ROH);
                object obj1   = ROH.Object;
                //TODO: if not found...
                MethodInfo mi = obj1.GetType().GetMethod(methodName);

                int ParamCounter = PL.GetValueInt();

                object[] param = new object[ParamCounter];
                for (int i = 0; i < ParamCounter; i++)
                {
                    param[i] = PL.GetValueByObjectType();
                }

                // invoke
                object rc = null;

                // temp comment for build
                // !!!!!!!!! d. requires Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo
                //if (ROH.Dispatcher == null)
                //{

                //    // Non UI object safe to call from another thread
                //    rc = mi.Invoke(obj1, param);
                //}
                //else
                //{
                //    // It means the obj is UI control like driver Page- so invoke on the UI control Dispatcher,
                //    // this way we avoid code on the page to change the UI on the Dispatcher every time we do UI changes and avoid getting exception
                //    ROH.Dispatcher.BeginInvoke(
                //                    (Action)(() => {
                //                        rc = mi.Invoke(obj1, param);
                //                    }
                //                ));
                //}

                // return result
                NewPayLoad PLRC = new NewPayLoad("OK");
                if (rc != null)
                {
                    PLRC.AddValueByObjectType(rc);
                }
                else
                {
                    PLRC.AddValue("NULL");
                    PLRC.AddValue("NULL");
                }
                PLRC.ClosePackage();
                return(PLRC);

            default:
                throw new Exception("Unknown PayLoad Action - " + PL.Name);
            }
        }
Пример #19
0
        public NewPayLoad GetActionPayload()
        {
            NewPayLoad PL = new NewPayLoad("RunPlatformAction");

            PL.AddValue("BrowserAction");
            List <NewPayLoad> PLParams = new List <NewPayLoad>();

            foreach (FieldInfo FI in typeof(ActBrowserElement.Fields).GetFields())
            {
                string Name  = FI.Name;
                string Value = GetOrCreateInputParam(Name).ValueForDriver;

                if (string.IsNullOrEmpty(Value))
                {
                    object Output = this.GetType().GetProperty(Name) != null?this.GetType().GetProperty(Name).GetValue(this, null) : string.Empty;

                    if (Output != null)
                    {
                        Value = Output.ToString();
                    }
                }

                if (!string.IsNullOrEmpty(Value))
                {
                    NewPayLoad FieldPL = new NewPayLoad("Field", Name, Value);
                    PLParams.Add(FieldPL);
                }
            }

            foreach (FieldInfo FI in typeof(Act.Fields).GetFields())
            {
                string Name  = FI.Name;
                string Value = GetOrCreateInputParam(Name).ValueForDriver;

                if (string.IsNullOrEmpty(Value))
                {
                    object Output = this.GetType().GetProperty(Name) != null?this.GetType().GetProperty(Name).GetValue(this, null) : string.Empty;

                    if (Output != null)
                    {
                        Value = Output.ToString();
                    }
                }

                if (!string.IsNullOrEmpty(Value))
                {
                    NewPayLoad FieldPL = new NewPayLoad("Field", Name, Value);
                    PLParams.Add(FieldPL);
                }
            }


            foreach (ActInputValue AIV in this.InputValues)
            {
                if (!string.IsNullOrEmpty(AIV.ValueForDriver))
                {
                    NewPayLoad AIVPL = new NewPayLoad("AIV", AIV.Param, AIV.ValueForDriver);
                    PLParams.Add(AIVPL);
                }
            }



            PL.AddListPayLoad(PLParams);
            PL.ClosePackage();

            return(PL);
        }
Пример #20
0
            // Handle server messages
            private void MessageHandler(GingerSocketInfo obj)
            {
                NewPayLoad PLRC = HandlePayLoadFromServer(obj.DataAsPayload);

                obj.Response = PLRC;
            }
Пример #21
0
        public void RunAction(GingerAction GA)
        {
            // Here we decompose the GA and create Payload to transfer it to the agent
            NewPayLoad PL = new NewPayLoad("RunAction");

            PL.AddValue(GA.ID);
            List <NewPayLoad> Params = new List <NewPayLoad>();

            foreach (ActionParam AP in GA.InputParams.Values)
            {
                // TODO: use const
                NewPayLoad p = new NewPayLoad("P");   // To save network trafic we send just one letter
                p.AddValue(AP.Name);
                p.AddValue(AP.Value.ToString());
                p.ClosePackage();
                Params.Add(p);
            }

            PL.AddListPayLoad(Params);
            PL.ClosePackage();

            // TODO: use function which goes to local grid or remote grid
            NewPayLoad RC = SendRequestPayLoad(PL);

            // After we send it we parse the driver response

            if (RC.Name == "ActionResult")
            {
                // We read the ExInfo, Err and output params
                GA.ExInfo = RC.GetValueString();
                string Error = RC.GetValueString();
                if (!string.IsNullOrEmpty(Error))
                {
                    GA.AddError("Driver", RC.GetValueString());   // We need to get Error even if Payload is OK - since it might be in
                }

                List <NewPayLoad> OutpuValues = RC.GetListPayLoad();
                foreach (NewPayLoad OPL in OutpuValues)
                {
                    //TODO: change to use PL AddValueByObjectType

                    // it is param name, type and value
                    string PName            = OPL.GetValueString();
                    string mOutputValueType = OPL.GetValueEnum();

                    switch (mOutputValueType)
                    {
                    case nameof(OutputValueType.String):
                        string v = OPL.GetValueString();
                        GA.Output.Values.Add(new ActionOutputValue()
                        {
                            Param = PName, ValueString = v
                        });
                        break;

                    case nameof(OutputValueType.ByteArray):
                        byte[] b = OPL.GetBytes();
                        GA.Output.Values.Add(new ActionOutputValue()
                        {
                            Param = PName, ValueByteArray = b
                        });
                        break;

                    default:
                        throw new Exception("Unknown param type: " + mOutputValueType);
                    }
                }
            }
            else
            {
                // The RC is not OK when we faced some unexpected exception
                //TODO:
                string Err = RC.GetValueString();
                GA.AddError("RunAction", Err);
            }
        }