Размещение веб-службы WCF внутри приложения WPF - PullRequest
0 голосов
/ 26 февраля 2012

Я разрабатываю приложение WPF. Как часть приложения, мне нужно получить некоторые изображения через другое приложение iOS. И поэтому я написал и службу WCF REST, и iOS, и я могу отправлять изображения в веб-службу только тогда, когда я определяю службу как часть IIS.
Что мне нужно, чтобы это произошло: при запуске приложения WPF веб-служба также будет запущена и предоставит номер порта для устройства iOS для отправки изображений и «пробуждения» приложения WPF при запуске. , Есть мысли?

1 Ответ

1 голос
/ 23 апреля 2012

Да, я сделал. Собственно, как отметил Тим, именно этим я и занимался самостоятельно. Вы можете посмотреть следующее видео (есть много других, посмотрите ссылки). http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Building-RESTful-Services-with-WCF/

Вот полные файлы в моем проекте WCF: (как упомянуто в фильме), я надеюсь, это поможет вам начать .. Просто отметьте, что также важно открыть определенный порт на вашем компьютере, чтобы включить входящий трафик HTTP. Взгляните на WCF ServiceHost права доступа .

Eval.cs

[DataContract]
public class Eval
{
    public string id;

    [DataMember]
    public string Submitter;
    [DataMember]
    public DateTime Timesent;
    [DataMember]
    public string Comments;
}

IEvalService.cs

[ServiceContract]
public interface IEvalService
{
    [WebInvoke(Method="POST", UriTemplate = "evals")]
    [OperationContract]
    void SubmitEval(Eval i_Eval);

    [WebGet(UriTemplate = "evals")]
    [OperationContract]
    List<Eval> GetEvals();

    [WebGet(UriTemplate="eval/{i_Id}")]
    [OperationContract]
    Eval GetEval(string i_Id);

    [WebGet(UriTemplate = "evals/{i_Submitter}")]
    [OperationContract]
    List<Eval> GetEvalsBySubmitters(string i_Submitter);

    [WebInvoke(Method = "DELETE", UriTemplate = "eval/{i_Id}")]
    [OperationContract]
    void RemoveEval(string i_Id);

    [WebGet(UriTemplate = "GetLastPhoto", BodyStyle = WebMessageBodyStyle.Bare)]
    Stream GetLastPhoto();

    [OperationContract] // this web address is for receiving the image for the iOS app.
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "TestPost")]
    string TestPost(Stream stream);
}

EvalService.cs

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class EvalService : IEvalService
{
    private List<Eval> m_Evals = new List<Eval>();
    private int evalCount = 0;
    private string k_FilePath = "C:\\ImageUpload\\";

    public static event Action<LogicImage> ImageLoaded;

    public void SubmitEval(Eval i_Eval)
    {
        i_Eval.id = (++evalCount).ToString();
        m_Evals.Add(i_Eval);
    }

    public List<Eval> GetEvals()
    {
        return m_Evals;
    }

    public Eval GetEval(string i_Id)
    {
        return m_Evals.First(e => e.id.Equals(i_Id));
    }

    public List<Eval> GetEvalsBySubmitters(string i_Submitter)
    {
        if (i_Submitter == null && i_Submitter.Equals(""))
        {
            return null;
        }

        else
        {
            return m_Evals.Where(e => e.Submitter == i_Submitter).ToList();
        }
    }

    public void RemoveEval(string i_ID)
    {
        throw new NotImplementedException();
    }

    public Stream GetLastPhoto()
    {
        Image image = Image.FromFile("C:\\ImageUpload\\014.png");
        MemoryStream ms = new MemoryStream(imageToByteArray(image));
        return ms;
    }

    public string TestPost(Stream stream)
    {
        HttpMultipartParser parser = new HttpMultipartParser(stream, "image");

        if (parser.Success)
        {
            if (parser.Success)
            {
                // deal with exceptions..
                //
                File.WriteAllBytes(k_FilePath + parser.Filename, parser.FileContents);
                if (ImageLoaded != null)
                {
                    ImageLoaded.Invoke(new LogicImage(){FileName = parser.Filename, Location = k_FilePath});
                }
            }
        }

        return "test";
    }

    public static byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }
}

public class LogicImage
{
    public string FileName { get; set; }
    public string Location { get; set; }
}

И последнее, но не менее важное. ** App.config **

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true"/>
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="ImageRecevierWebService.EvalService">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/ImageRecevierWebService/Service1/"/>
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address="" binding="wsHttpBinding" contract="ImageRecevierWebService.IEvalService">
          <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --> 
        <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
...