Page 1 of 1

Cвязка WCF + WinForms + Stealth 7.9.2

Posted: 17.02.2017 19:01
by drabadan
Решил заморочится, не знаю сработает ли оно в будущем, сейчас пишу на заказ скрипт с гуи и чот захотелось мне стелс оставить одним слоем а гуй, который чисто декларативный другим слоем. Каналом связи получилась самоподнимаемая вцф хттп служба через которую и идет "общение".
Мало ли кому-то пригодится.
StealthCode

Code: Select all

Program OutGui_HelloWorld;

const
  OutScriptFilePath = '\Scripts\SourceCode\OutGui\StealthScript_OUTGui.exe';
  port = '25555';

var
  baseAddress : String;

function MakeRequest(Command : String) : String;
begin
  //AddToSystemJournal(baseAddress + '/' + Command);
  HTTP_Get(baseAddress + '/' + Command);
  //AddToSystemJournal(HTTP_Header);
  Result := HTTP_Header;
end;

procedure GetTargetId;
begin
  //AddToSystemJournal('1');
  ClientRequestObjectTarget;
  while not ClientTargetResponsePresent do
    Wait(1000);

  //AddToSystemJournal('2');

  MakeRequest('SetScriptResponse?response=0x' + IntToHex(ClientTargetResponse.Id, 8));
  //AddToSystemJournal('3');
  //AddToSystemJournal('4');
end;



begin  
  baseAddress := 'http://localhost:' + port;
  WinExec(StealthPath + OutScriptFilePath, port);
  Wait(3000);  
  AddToSystemJournal('Gui service started, listening commands...');
  while true do
    begin
      Wait(3000); 
      case MakeRequest('GetScriptRequest') of
        '"NoRequest"' : Wait(1000);
        '"GetTargetId"' : GetTargetId;
      end;
    end;
end.
WCFServiceCode

Code: Select all

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;

namespace StealthScript_OUTGui
{
    public enum ActionState : Byte
    {
        NoAction = 0x1,
        PendingAction
    }

    [ServiceContract]
    public interface IStealthOutGUIService
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        ActionState GuiState();

        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        ActionState ScriptState();

        [OperationContract]
        [WebGet(UriTemplate = "SetGuiState?state={state}")]
        void SetGuiState(byte state);

        [OperationContract]
        [WebGet(UriTemplate = "SetScriptState?state={state}")]
        void SetScriptState(byte state);

        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "SetScriptResponse?response={response}")]
        void SetScriptResponse(string response);

        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        string GetScriptResponse();

        [OperationContract]
        [WebGet(UriTemplate = "SetScriptRequest?request={request}")]
        void SetScriptRequest(string request);

        [OperationContract]
        [WebGet(UriTemplate = "GetScriptRequest", ResponseFormat = WebMessageFormat.Json)]
        string GetScriptRequest();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class StealthOutGUIService : IStealthOutGUIService
    {
        private ActionState _guiStateValue = ActionState.NoAction;
        private ActionState _scriptStateValue = ActionState.NoAction;        

        public ActionState GuiState()
        {
            return _guiStateValue;
        }

        public ActionState ScriptState()
        {
            return _scriptStateValue;
        }

        public void SetGuiState(byte state)
        {
            _guiStateValue = (ActionState)state;
        }

        public void SetScriptState(byte state)
        {
            _scriptStateValue = (ActionState)state;
        }

        private string _scriptResponse = "No response";
        public void SetScriptResponse(string response)
        {
            _scriptStateValue = ActionState.NoAction;
            //return response;
            _scriptRequest = "NoRequest";
            _scriptResponse = response;
        }
        public string GetScriptResponse()
        {
            return _scriptResponse;
        }

        private string _scriptRequest = "NoRequest";
        public void SetScriptRequest(string request)
        {
            _scriptStateValue = ActionState.PendingAction;
            _scriptRequest = request;
        }

        public string GetScriptRequest()
        {
            return _scriptRequest;
        }
    }
}
WinFormsCode

Code: Select all

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StealthScript_OUTGui
{
    public partial class StealthOutGui : Form
    {
        int _port;
        public StealthOutGui(int port)
        {
            _port = port;
            InitializeComponent();
        }

        public void SendConsoleMessage(string message)
        {
            this.Invoke((MethodInvoker)delegate
            {
                Console_textBox.AppendText(DateTime.Now.ToLongTimeString() + ": " + message + Environment.NewLine);
            });
        }

        Uri _baseAddress;
        private void StealthOutGui_Load(object sender, EventArgs e)
        {
            _baseAddress = new Uri("http://localhost:" + _port);

            WebServiceHost svcHost = new WebServiceHost(typeof(StealthOutGUIService), _baseAddress);

            try
            {
                svcHost.Open();
            }
            catch (CommunicationException cex)
            {
                SendConsoleMessage($"An exception occurred: {cex.Message}");
                svcHost.Abort();
            }

            SendConsoleMessage($"Service opened at: {svcHost.BaseAddresses.First()}");
            this.FormClosing += (sender1, e1) => FormClosingHandler(svcHost);
        }

        private void FormClosingHandler(WebServiceHost svcHost)
        {
            svcHost.Close();
        }

        private async Task<string> SendRequest(string request)
        {
            WebRequest wrequest = WebRequest.Create(_baseAddress + "/SetScriptRequest?request=" + request);
            await wrequest.GetResponseAsync();

            string result = string.Empty;
            int counter = 0;

            while (counter < 30)
            {
                await Task.Delay(1000);
                string response;
                WebRequest wr1 = WebRequest.Create(_baseAddress + "/ScriptState");
                var wr = await wr1.GetResponseAsync();
                using (StreamReader sr = new StreamReader(wr.GetResponseStream()))
                    response = await sr.ReadToEndAsync();
                SendConsoleMessage(response);
                byte outresp = 0;
                if (byte.TryParse(response, out outresp))
                    switch ((ActionState)outresp)
                    {
                        case ActionState.NoAction:
                            counter = 100;
                            break;
                        case ActionState.PendingAction:
                            break;
                        default:
                            break;
                    }

                ++counter;
            }

            WebRequest wresponse = WebRequest.Create(_baseAddress + "/GetScriptResponse");
            var wrr = await wresponse.GetResponseAsync();
            using (StreamReader sr = new StreamReader(wrr.GetResponseStream()))
                result = await sr.ReadToEndAsync();

            return result;
        }

        private async void Test_button_Click(object sender, EventArgs e)
        {
            var res = await SendRequest("GetTargetId");
            SendConsoleMessage(res);
        }
    }
}


Re: Cвязка WCF + WinForms + Stealth 7.9.2

Posted: 17.02.2017 19:44
by GeeZeR
крутизна, т.е. стелс общается с прогой с гуи через этот вцф? Кто ж такое заказал? Новый русский с ностальгией по 90-м )))
А что-то я помню такое в ранних версиях Стелса была возможность делать гуи прям в клиенте но её выпилили, сказали ваяй через винапи, но у меня слабые нервы для винапи Ж(

Re: Cвязка WCF + WinForms + Stealth 7.9.2

Posted: 17.02.2017 21:22
by drabadan
GeeZeR wrote:крутизна, т.е. стелс общается с прогой с гуи через этот вцф? Кто ж такое заказал? Новый русский с ностальгией по 90-м )))
А что-то я помню такое в ранних версиях Стелса была возможность делать гуи прям в клиенте но её выпилили, сказали ваяй через винапи, но у меня слабые нервы для винапи Ж(
ммм, такое никто не заказывал, я писал на шарпе скрипт. Написал, все вроде и агонь, а вроде бы и нет. Вот решил себе напилить так, чтоб и гуи был и кодить скриптовую всю шнягу в скрипте, который уже сам и поднимает гуи.